Skip to content

doverunner/cmcdv2-hls-plugin

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

13 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

CMCD v2 Plugin for HLS.js (CmcdV2 POC)

Overview

The cmcdV2Plugin is a JavaScript module designed to work with HLS.js. Its primary purpose is to enable CMCD Version 2 'Response Mode' and 'Event Mode' and report metrics to a third-party server. Currently, the plugin supports two transmission modes: JSON Mode and Query Mode.

This plugin can be used alongside HLS.js's native CMCD (Common Media Client Data) features when available.

Samples

This repo has two samples to try the plugin, sample-hls-latest.html and sample-hls-1-5-0.html. One showcases how this plugin works with the latest version of HLS.js, and the other with HLS.js v1.5.0.

Setup and Integration

Follow these steps to integrate the cmcdV2Plugin into your HLS.js application:

  1. Include Scripts: Make sure both HLS.js and the cmcdV2Plugin.js are included in your HTML file before your application logic:

    <script src="path/to/hls.min.js"></script>
    <script src="path/to/cmcdV2Plugin.js"></script>

    Also, you can use jsDelivr to get these sources:

    <script src="https://cdn.jsdelivr.net/npm/hls.js@latest"></script>
    <script src="https://cdn.jsdelivr.net/gh/qualabs/cmcdv2-hls-plugin/cmcdV2Plugin.js"></script>
  2. Initialize HLS.js: Set up your HLS.js instance as usual.

    // Check for HLS.js support
    if (Hls.isSupported()) {
        initPlayer();
    } else if (video.canPlayType('application/vnd.apple.mpegurl')) {
        // Native HLS support (Safari)
        video.src = manifestUri;
    } else {
        console.error('HLS is not supported!');
    }
    
    function initPlayer() {
        const video = document.getElementById('video');
        const hls = new Hls();
        
        // ... (cmcdV2Plugin configuration - see below)
    
        hls.attachMedia(video);
        hls.loadSource(manifestUri);
    }
  3. (Optional) Configure HLS.js CMCD: The plugin can gather CMCD data generated from Request Mode and includes it on the Response Mode report. If HLS.js CMCD is not enabled, only keys in includeKeys will be included on the Response Mode report.

    const hls = new Hls({
        // HLS.js CMCD configuration (if available in your version)
        // cmcd: {
        //     version: 2,
        //     enabled: true,
        //     contentId: 'your-content-id',
        //     sessionId: 'your-unique-session-id'
        // }
    });
  4. Configure the cmcdV2Plugin: Create a configuration object for the plugin.

    const reportingUrlString = 'https://collector-gcloud-function-560723680185.us-east1.run.app/cmcd/event-mode';
    
    const cmcdV2PluginConfig = {
        reportingMode: 'event', // Specify 'response' or 'event'
        transmissionMode: 'json', // Specify 'json' or 'query'
        batchSize: 8, // Batch is only available with json mode (default: 8)
        batchTimer: 30, // Timer in seconds to send batch even if not full (json mode only, optional)
        url: reportingUrlString, // The URL for the reporting endpoint
        timeInterval: 10, // Time interval in seconds for periodic event reports (event mode only, optional)
        // includeKeys: ['ts', 'ttfb', 'ttlb', 'url', 'pt', 'rc', 'ltc'] // Will send all keys if not configured
        // beforeSend: (batch) => { console.log('Sending:', batch); }, // Optional callback before sending
        // afterSend: (response) => { console.log('Sent:', response); } // Optional callback after successful send
    };
  5. Enable the Plugin: After the HLS.js instance is created and configured, enable the cmcdV2Plugin.

    // In your initPlayer function, after hls creation and configuration:
    hlsCmcdV2Plugin.enableCmcdV2(hls, cmcdV2PluginConfig);

Configuration Options

  • reportingMode: 'response' or 'event' - Determines reporting mode to the server
  • transmissionMode: 'json' or 'query' - Determines how data is sent to the reporting server
  • batchSize: Number (only for JSON mode) - Number of reports to batch before sending (default: 8)
  • batchTimer: Number (optional, JSON mode only) - Time in seconds to automatically send batch even if not full
  • url: String - The reporting endpoint URL
  • timeInterval: Number (optional, event mode only) - Time in seconds for periodic event reports
  • includeKeys: Array (optional) - Specific CMCD keys to include. Available keys: ['ts', 'ttfb', 'ttlb', 'url', 'pt', 'rc', 'ltc', 'pr', 'sta', 'msd', 'df', 'sn', 'e']
  • beforeSend: Function (optional, JSON mode only) - Callback function called before sending batch. Receives batch array as parameter
  • afterSend: Function (optional, JSON mode only) - Callback function called after successful send. Receives response object as parameter

CMCD Keys Supported

  • ts: Timestamp when request was initiated (epoch ms)
  • ttfb: Time To First Byte (ms)
  • ttlb: Time To Last Byte (ms)
  • rc: Response code of the HTTP request
  • url: URL of the requested resource (without query parameters)
  • pt: Playhead time in seconds (VOD) or timestamp (Live)
  • ltc: Live latency in milliseconds (Live streams only)
  • pr: Playback rate
  • sta: Player state (p=playing, a=paused, w=waiting, k=seeking, e=ended)
  • msd: Media Start Delay (sent once per session)
  • df: Dropped video frames count
  • sn: Sequence number for the report
  • e: Event

Events Supported (Event Mode)

  • ps: Player State (playing, pause, seeking, waiting, ended)
  • t: Time Interval (periodic reports based on timeInterval config)
  • m: Muted
  • um: Unmuted
  • e: Error (includes error code as ec)

Key Features

Batch Management (JSON Mode)

  • Automatic batch sending: Sends when batch reaches batchSize
  • Timer-based sending: Optional batchTimer sends batch at regular intervals
  • Smart retry logic: Failed requests are re-queued with overflow protection
  • Prevents data loss: Batch size limit maintained even on retry
  • Send locking: Prevents concurrent send operations

Callback Support (JSON Mode)

  • beforeSend: Called before sending batch, useful for logging or modifying data
  • afterSend: Called after successful send, useful for tracking or analytics

Event Mode Enhancements

  • Time interval reporting: Periodic reports via timeInterval config
  • Comprehensive event tracking: Player state, mute/unmute, errors with error codes
  • Media element event integration: Seamless integration with HTML5 media events

Differences from Shaka Player Plugin

  • Uses HLS.js event system (hlsFragLoaded, hlsManifestLoaded) instead of response filters
  • Adapts timing calculations to HLS.js's event data structure
  • Handles HLS.js-specific player state detection
  • Works with HLS.js's fragment loading architecture
  • Enhanced batch management with retry logic and overflow protection
  • Timer-based batch sending for guaranteed delivery intervals

Browser Compatibility

This plugin works with any browser that supports HLS.js. For Safari and other browsers with native HLS support, additional integration may be needed.

License

This project is licensed under the same terms as the original Shaka Player CMCD v2 plugin.

About

PoC of a CMCD v2 plugin for hls.js

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • JavaScript 64.5%
  • HTML 35.5%