HLS.js code to reload video when levelLoadTimeOut occurs

CK CK 3788 
Created at  
704 0 0

When the HLS.js player face errors like levelLoadTimeOut, the player stops. This is very helpful to investigate the root cause, but it's not comfortable in terms of user's point of view. What user want to have is comfortable and seamless playback environment.

What we can try will be automatical reloading.

If you can continue to play from the current playback position, that will be a plus!

To handle the levelLoadTimeout event in HLS.js and reload the video when this timeout occurs, you can use the following approach. Here's a sample code snippet to achieve this:

// Initialize HLS.js
if (Hls.isSupported()) {
    var video = document.getElementById('video');
    var hls = new Hls();

    // Attach media
    hls.attachMedia(video);

    // Load the video source
    hls.on(Hls.Events.MEDIA_ATTACHED, function () {
        var videoUrl = 'https://path/to/your/video.m3u8'; // Replace with your video URL
        hls.loadSource(videoUrl);
    });

    // Handle level load timeout
    hls.on(Hls.Events.LEVEL_LOAD_TIMEOUT, function (event, data) {
        console.error('Level load timeout occurred:', data);

        // Optionally, you can try to reload the level or the entire video
        // Example: Reloading the entire video source
        var currentLevel = hls.currentLevel;
        console.log('Reloading level:', currentLevel);

        // Reload the level or fallback to reload the entire source
        hls.loadLevel = currentLevel; // Reload the same level
        hls.loadSource(hls.url); // Reload the entire video source
        hls.startLoad(); // Restart loading
    });

    // Attach error handling for other HLS errors
    hls.on(Hls.Events.ERROR, function (event, data) {
        if (data.fatal) {
            switch (data.type) {
                case Hls.ErrorTypes.NETWORK_ERROR:
                    console.error('Fatal network error encountered, trying to recover...');
                    hls.startLoad(); // Try to recover by restarting load
                    break;
                case Hls.ErrorTypes.MEDIA_ERROR:
                    console.error('Fatal media error encountered, trying to recover...');
                    hls.recoverMediaError();
                    break;
                default:
                    // If it's not recoverable, destroy the instance
                    hls.destroy();
                    break;
            }
        }
    });

    // Attach the video to the DOM
    video.play();
}

Explanation:

  • Hls.isSupported(): Ensures that the browser supports HLS.js.
  • hls.attachMedia(video): Attaches the HLS.js instance to the video element.
  • Hls.Events.LEVEL_LOAD_TIMEOUT: This event is triggered when a level fails to load within the defined timeout period.
  • hls.loadLevel = currentLevel: Attempts to reload the current level.
  • hls.loadSource(hls.url): Reloads the entire video source if needed.
  • hls.startLoad(): Starts loading the media after reloading the source or level.
  • Error Handling: The Hls.Events.ERROR listener handles different error types and tries to recover or reload the video accordingly.

This code ensures that the video will reload if a level load timeout occurs, providing a fallback mechanism to enhance the user's viewing experience.

 

To play continuous playback when the player face the error like above, you may able to have

HTML video object provides the current position like below:

// Function to reload the player and resume from the saved position
function reloadPlayer() {
	savedPlayPosition = video.currentTime;

    // Destroy the current HLS instance
    hls.destroy();

    // Create a new HLS instance
    hls = new Hls();
    hls.loadSource('https://example.com/path/to/your/playlist.m3u8');
    hls.attachMedia(video);

    // Resume playback from the saved position once the video is ready
    hls.on(Hls.Events.MANIFEST_PARSED, function() {
        video.currentTime = savedPlayPosition;
        video.play(); // Automatically play the video after setting the position
    });
}
Tags HLS.js levelLoadTimeout Facebook X
Comments 0
Similar posts
  1. HLS.js code to reload when user face bufferfull error
    703
  2. When HLS.js need to load m3u8 URL redirecting to the different URL (302 Redirection)
    659
  3. Change the manifest loading timeout in HLS.js
    1,028
  4. HLS.js options to support subtitle
    513
  5. How do I display trickplay images with hls.js that elaborated at EXT-X-IMAGE-STREAM-INF in m3u8
    801
  6. Limit Maximum Resolution in HLS.js
    663
  7. Disabling Audio Tracks in HLS.js
    371
  1. Unlock Flawless HLS Audio Sync: The Power of #EXT-X-INDEPENDENT-SEGMENTS
    373
  2. NVIDIA CUDA library which can be integrated with C/C++
    375
  3. Approaches to Scene Detection in Video Processing
    643
  4. FFmpeg CLI to remove audio track from MP4
    540
  5. Building GPU as a Service aka Dockerized GPU
    1,566
  6. IAB Categories (a.k.a. OpenRTB Code)
    1,012
  7. FFmpeg library that can be directly integrated into C/C++/Rust/Python without CLI
    2,057
  8. 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
    593
  9. Progressive MP4 is an application of streaming techniques using the standardized MP4 container invented by MPEG LA consortium
    1,071
  10. FFmpeg CLI to mix two different audios in a single audio file such as mp3
    599
  11. FFmpeg CLI to merge a video only mp4 and mp3 audio file
    332
  12. FFmpeg CLI to convert a video file to an MP3 audio file
    345
  13. HLS.js options to support subtitle
    513
  14. When HLS.js need to load m3u8 URL redirecting to the different URL (302 Redirection)
    659
  15. HLS.js code to reload when user face bufferfull error
    703
  16. Change the manifest loading timeout in HLS.js
    1,028
  17. HLS.js Custom Error Handler to load Main Manifest from unstable HLS Live Stream
    1,427
  18. Mastering Audio Sync: Keyframes, GOP, FFmpeg, and HLS Explained
    536
  19. How do I display trickplay images with hls.js that elaborated at EXT-X-IMAGE-STREAM-INF in m3u8
    801
Recently updated
  1. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    27
  2. Why SPF and DKIM Are Essential for Linux Email Servers?
    24
  3. How do I create animated background for Google Meet?
    19,731
  4. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    217
  5. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    86
  6. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    153
  7. Array of arguments passed to script in PHP
    85
  8. Invalid Auction Storms in Ad Tech
    93
  9. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    198
  10. The Two Clocks of Ad Server Architecture
    63
  11. Frequency Cap Architecture Overview
    509
  12. Collecting Proof-of-Play from 100,000 Screens
    141
  13. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    280
  14. What is RedisVL?
    105
  15. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    224
  16. TPU & GPU Cluster Management Tools
    234
  17. The Concept of Scaffolding in AI Agents
    222
  18. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    576
  19. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    253
  20. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    328
  21. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    197
  22. Machine Learning: Training vs. Ranking
    213
  23. The Continuous Learning Machine: Designing a Loop That Actually Turns
    217
  24. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    189
  25. Designing a Data Curation System Around a Vector Database
    215
  26. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    229
  27. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    649
  28. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    185
  29. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    207
  30. Understanding Data Lineage
    252