mpegts.js Documentation

repository·master·Indexed 25 days ago

https://github.com/xqq/mpegts.js

An HTML5 MPEG2-TS stream player designed for low-latency playback of MPEG2-TS and FLV streams. It transmuxes streams into fragmented MP4 segments for playback via the Media Source Extensions (MSE) API. Version 1.8.0 supports various media types including 'mse', 'mpegts', 'm2ts', 'flv', and 'mp4', and provides tools for H.265 Annex B parsing and decoder configuration.

Tokens
7.9K
Snippets
16
Records
50
Agent score
80%

What's inside mpegts.js

  1. How mpegts.js works

    master

    mpegts.js is an HTML5 MPEG2-TS stream player optimized for low-latency live stream playback (e.g., DVB/ISDB television or surveillance cameras).

    It works by transmuxing MPEG2-TS streams into ISO BMFF (Fragmented MP4) segments, which are then fed into an HTML5 <video> element using the Media Source Extensions (MSE) API.

  2. Build mpegts.js from source

    master

    To build the project manually, follow these steps:

    1. Install development dependencies: npm install
    2. Install the build tool: npm install -g webpack-cli
    3. Run the build: npm run build (emits packaged & minimized JS in the dist folder).

    For a debug build, use: npm run build:debug

    npm install                 # install dev-dependencies
    npm install -g webpack-cli  # install build tool
    npm run build               # packaged & minimized js will be emitted in dist folder
  3. Configure CORS for static file playback

    master

    When playing static MPEG2-TS or FLV files, it is recommended to include the Content-Length header in your CORS configuration so the player knows the file size. Alternatively, you must provide the accurate file size manually in the MediaDataSource object.

    Access-Control-Expose-Headers: Content-Length
  4. Get started with mpegts.js playback

    master

    To play a live stream, first check if the browser supports mseLivePlayback using mpegts.getFeatureList(). Then, create a player instance using mpegts.createPlayer, attach it to a video element, and call load() and play().

    <script src="mpegts.js"></script>
    <video id="videoElement"></video>
    <script>
        if (mpegts.getFeatureList().mseLivePlayback) {
            var videoElement = document.getElementById('videoElement');
            var player = mpegts.createPlayer({
                type: 'mse',  // could also be mpegts, m2ts, flv
                isLive: true,
                url: 'http://example.com/live/livestream.ts'
            });
            player.attachMediaElement(videoElement);
            player.load();
            player.play();
        }
    </script>
  5. Handle CORS with 301/302 redirects

    master

    If your video server uses 3xx redirects, the redirection response itself must contain the Access-Control-Allow-Origin header.

    Note that browsers may send Origin: null in redirected requests due to current CORS policies. To support this, your edge server should respond with:

    Access-Control-Allow-Origin: null
    # OR
    Access-Control-Allow-Origin: *

    Alternatively, you can dynamically determine the allowed origin by reading the Origin request header.

    Access-Control-Allow-Origin: null | *
  6. Implement multipart playback using MediaDataSource

    master

    To enable multipart playback, pass a MediaDataSource object to the FlvPlayer constructor. Multipart playback is currently only supported for the flv type.

    Important: You must provide accurate duration values for every segment to ensure smooth playback transitions.

    MediaDataSource Schema

    KeyTypeRequiredDescription
    typestringYesMust be set to "flv" for multipart support.
    durationnumberNoTotal duration of the entire playlist in milliseconds.
    corsbooleanNoEnable CORS for segment requests.
    withCredentialsbooleanNoWhether to include credentials in requests.
    hasAudiobooleanNoSet to false if the stream is video-only. Defaults to true.
    hasVideobooleanNoSet to false if the stream is audio-only. Defaults to true.
    segmentsArray<Object>YesAn array of segment objects.

    Segment Object Schema

    KeyTypeRequiredDescription
    urlstringYesThe URL of the segment file.
    durationnumberYesDuration of the specific segment in milliseconds.
    filesizenumberYesSize of the segment in bytes.
  7. Configure Preflight OPTIONS for Range seek

    master

    When using Range seek for cross-origin files, mpegts.js adds a Range header, which triggers a browser Preflight OPTIONS request. Your server must handle this OPTIONS request by responding with the following headers to allow the subsequent GET request:

    Access-Control-Allow-Origin: <your-origin> | *
    Access-Control-Allow-Methods: GET, OPTIONS
    Access-Control-Allow-Headers: range
  8. Configure CORS for cross-origin stream playback

    master
    To play MPEG2-TS or FLV streams from a different origin than your website, the video server must respond with the Access-Control-Allow-Origin header. You can specify your specific origin or use a wildcard * to allow any origin.
  9. Configure livestream playback with MediaDataSource

    master

    To play a livestream, you must provide a configuration object to MediaDataSource where isLive is set to true. The type field determines the protocol used (e.g., mpegts, flv, or mse for WebSocket-based streams).

    // MPEG2-TS over HTTP
    {
        "type": "mpegts",
        "isLive": true,
        "url": "http://127.0.0.1:8080/live/livestream.ts"
    }
    
    // HTTP FLV
    {
        "type": "flv",
        "isLive": true,
        "url": "http://127.0.0.1:8080/live/livestream.flv"
    }
    
    // MPEG2-TS/FLV over WebSocket
    {
        "type": "mse",
        "isLive": true,
        "url": "ws://127.0.0.1:9090/live/livestream.flv"
    }
  10. Configure player behavior with Config

    master

    The Config object allows fine-tuning of the player's performance, latency, and resource usage. Key options include:

    • Threading: enableWorker and enableWorkerForMSE enable DedicatedWorker threads for transmuxing and MediaSource processing.
    • Latency & Live Streaming:
      • enableStashBuffer: Set to false for minimal latency in live streams (at the risk of stalling during network jitter).
      • liveBufferLatencyChasing: Chases latency in the HTMLMediaElement buffer (requires isLive: true).
      • liveSync: Chases latency by adjusting playbackRate (requires isLive: true).
    • Buffering & Cleanup:
      • lazyLoad: Aborts HTTP connections once enough data is buffered for playback.
      • autoCleanupSourceBuffer: Automatically cleans up the SourceBuffer based on autoCleanupMaxBackwardDuration and autoCleanupMinBackwardDuration.
    • Seeking: accurateSeek allows seeking to any frame (not just IDR) but may be slower.
  11. Configure CORS for MPEG2-TS streams

    master
    If you are using a standalone video server for MPEG2-TS streams, you must configure the Access-Control-Allow-Origin header on your video server to allow cross-origin resource fetching.