HLS.js Custom Error Handler to load Main Manifest from unstable HLS Live Stream

CK CK 3788 
Created at  
1,432 0 0

To handle manifest load errors in HLS.js with retries, you can set up a custom error handler. This will allow you to retry loading the manifest a specified number of times when encountering manifestLoadError. Below is a sample code that demonstrates how to implement this logic:

// Include the HLS.js script in your HTML file
// <script src="https://cdn.jsdelivr.net/npm/hls.js@latest"></script>

// JavaScript code to handle manifest load errors with retries
document.addEventListener("DOMContentLoaded", function() {
    if (Hls.isSupported()) {
        var video = document.getElementById('video');
        var hls = new Hls();
        var maxRetries = 3; // Maximum number of retries
        var retryCount = 0; // Current retry count
        var retryDelay = 2000; // Delay between retries in milliseconds

        hls.loadSource('https://path/to/your/manifest.m3u8');
        hls.attachMedia(video);

        hls.on(Hls.Events.MANIFEST_PARSED, function() {
            video.play();
        });

        hls.on(Hls.Events.ERROR, function(event, data) {
            if (data.type === Hls.ErrorTypes.NETWORK_ERROR && data.details === Hls.ErrorDetails.MANIFEST_LOAD_ERROR) {
                if (retryCount < maxRetries) {
                    retryCount++;
                    console.log(`Retry ${retryCount}/${maxRetries}`);
                    setTimeout(function() {
                        hls.loadSource('https://path/to/your/manifest.m3u8');
                    }, retryDelay);
                } else {
                    console.error('Maximum retries reached. Could not load the manifest.');
                    // Handle the error appropriately here
                }
            } else {
                console.error('HLS.js error:', data);
                // Handle other errors appropriately here
            }
        });
    } else if (video.canPlayType('application/vnd.apple.mpegurl')) {
        // HLS.js is not supported on this platform, but the native HLS is
        video.src = 'https://path/to/your/manifest.m3u8';
        video.addEventListener('loadedmetadata', function() {
            video.play();
        });
    }
});

 

Explanation:

  1. Initialization and Setup:
    • The script waits for the DOM to load before executing the HLS.js setup.
    • It checks if HLS.js is supported by the browser.
    • It defines variables for the maximum number of retries (maxRetries), the current retry count (retryCount), and the delay between retries (retryDelay).
  2. Loading the Manifest:
    • The hls.loadSource method is used to load the HLS manifest.
    • The hls.attachMedia method is used to attach the video element to HLS.js.
  3. Error Handling and Retrying:
    • The script listens for the Hls.Events.ERROR event.
    • If the error type is NETWORK_ERROR and the detail is MANIFEST_LOAD_ERROR, it increments the retry count and attempts to reload the manifest after a specified delay.
    • If the maximum number of retries is reached, an error message is logged, and further actions can be taken.
  4. Fallback for Native HLS Support:
    • If HLS.js is not supported but the browser supports native HLS, it sets the video source directly to the manifest URL.

This code provides a basic structure for handling manifest load errors with retries in HLS.js. You can further customize the error handling and retry logic as per your requirements.

Tags HLS.js custom error handler HLS.js retry logic for loading manifest HLS.js.manifestLoadError Facebook X
Comments 0
  1. Approaches to Scene Detection in Video Processing
    646
  2. FFmpeg CLI to remove audio track from MP4
    542
  3. Building GPU as a Service aka Dockerized GPU
    1,575
  4. IAB Categories (a.k.a. OpenRTB Code)
    1,013
  5. FFmpeg library that can be directly integrated into C/C++/Rust/Python without CLI
    2,068
  6. HTTP Live Streaming (HLS) was developed by Apple as part of QuickTime X in iOS3.0, and became an official standard (RFC 8126) in 2017
    596
  7. Progressive MP4 is an application of streaming techniques using the standardized MP4 container invented by MPEG LA consortium
    1,076
  8. FFmpeg CLI to mix two different audios in a single audio file such as mp3
    603
  9. FFmpeg CLI to merge a video only mp4 and mp3 audio file
    334
  10. FFmpeg CLI to convert a video file to an MP3 audio file
    348
  11. HLS.js options to support subtitle
    516
  12. When HLS.js need to load m3u8 URL redirecting to the different URL (302 Redirection)
    663
  13. HLS.js code to reload when user face bufferfull error
    705
  14. HLS.js code to reload video when levelLoadTimeOut occurs
    707
  15. Change the manifest loading timeout in HLS.js
    1,038
  16. Mastering Audio Sync: Keyframes, GOP, FFmpeg, and HLS Explained
    538
  17. How do I display trickplay images with hls.js that elaborated at EXT-X-IMAGE-STREAM-INF in m3u8
    804
Recently updated
  1. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    40
  2. Why SPF and DKIM Are Essential for Linux Email Servers?
    34
  3. How do I create animated background for Google Meet?
    20,613
  4. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    245
  5. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    94
  6. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    157
  7. Array of arguments passed to script in PHP
    90
  8. Invalid Auction Storms in Ad Tech
    98
  9. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    202
  10. The Two Clocks of Ad Server Architecture
    70
  11. Frequency Cap Architecture Overview
    514
  12. Collecting Proof-of-Play from 100,000 Screens
    146
  13. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    287
  14. What is RedisVL?
    109
  15. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    230
  16. TPU & GPU Cluster Management Tools
    244
  17. The Concept of Scaffolding in AI Agents
    233
  18. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    583
  19. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    259
  20. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    339
  21. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    202
  22. Machine Learning: Training vs. Ranking
    221
  23. The Continuous Learning Machine: Designing a Loop That Actually Turns
    222
  24. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    195
  25. Designing a Data Curation System Around a Vector Database
    220
  26. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    256
  27. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    656
  28. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    195
  29. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    217
  30. Understanding Data Lineage
    260