Skip to content

Mpegts.js

Mpegts.js is a JavaScript library based on HTML5 and Media Source Extensions (MSE) for playing MPEG-TS format streams. It is designed for modern browsers that do not natively support MPEG-TS (e.g., Chrome, Firefox).

testMpeg(player, channelName)

Description

testMpeg is a passive monitoring method designed to monitor multiple streaming lines (lines) in a specific channel (channelName). It collects playback-related data, such as buffering performance and download speed, and sends this data to a data center for further analysis. The system uses this analysis to determine the optimal streaming line and retrieves the best-performing line through the getResourceUrl method.

⚠️ Note

  1. Mpegts.js Compatibility
    Ensure that Mpegts.js and Media Source Extensions (MSE) are supported in the environment to handle MPEG-TS streams properly.

  2. Data Center Configuration
    Ensure the data center is properly configured to receive and process uploaded data. Otherwise, the getResourceUrl method will not work.

  3. Dynamic Switching
    After obtaining the best-performing line, implement dynamic switching based on playback needs and buffering status to avoid playback interruptions.

  4. Empty Return Value
    If getResourceUrl returns an empty value, ensure a fallback mechanism is implemented, such as setting a default line or notifying the user.


Syntax

javascript
testMpeg(player, channelName);

Parameters

NameTypeDescription
playerMpegts JS ObjectRequired. An instance of Mpegts.js, used to handle MPEG-TS streams.
channelNameStringRequired. The name of the channel to tag or track the ongoing test.

Features and Usage

  1. Line Monitoring and Data Collection

    • Tests and monitors the playback status of multiple streaming lines in a specific channel.
    • Collects data such as buffering state, download speed, and error counts for each line and uploads it to a data center.
  2. Dynamic Line Selection

    • After data collection is complete, the getResourceUrl method can be used to obtain the best-performing line in the current channel for automatic switching.

Examples

1. Initialize Monitoring

The following code demonstrates how to use testMpeg to monitor playback status for a specific channel:

javascript
// Import Mpegts.js and create an instance
import Mpegts from 'mpegts.js';
import JBLWebSocket from '@/assets/js/jbl.es.js';

const authorizationKey = ${Product authorization key};
const channelName = "MovieChannel";

// Establish a connection with WebSocket
JBLWebSocket.connect(authorizationKey, channelName);

// Check if the browser supports Mpegts.js
if (Mpegts.getFeatureList().mseLivePlayback) {
    const player = Mpegts.createPlayer({
        type: 'mse', // Use MSE for playback
        isLive: true,
        url: 'https://example.com/movie_channel/live.mpegts',
    });

    // Attach the player to the video element
    const videoElement = document.getElementById('video');
    player.attachMediaElement(videoElement);
    player.load();
    player.play();

    // Start monitoring the playback status of the channel
    JBLWebSocket.testMpeg(player, channelName);
} else {
    console.error('Your browser does not support Mpegts.js!');
}

2. Retrieve the Best Line getResourceUrl

After the data center has accumulated sufficient data, developers can use the getResourceUrl method to obtain the best-performing line:

javascript
const bestLine = JBLWebSocket.getResourceUrl();

if (bestLine) {
    console.log(`The best line is: ${bestLine}`);
    // Switch to the best line
    player.unload();
    player.load({
        type: 'mse',
        isLive: true,
        url: bestLine,
    });
    player.play();
} else {
    console.error("The best line is empty. Please handle this scenario, such as setting a default line or notifying the user.");
}

Monitoring Mechanism

  1. Playback Event Monitoring

    • Monitors key events during MPEG-TS playback, such as buffering start, buffering complete, and playback errors.
  2. Data Upload

    • Collects data such as download speed, buffering performance, and error counts for each line and uploads it to a data center.
  3. Optimal Line Selection

    • The data center analyzes the collected data to calculate the best-performing line, which can be retrieved using the getResourceUrl method.

sendMpegErrCode(url, errorCode)

Description

The sendMpegErrCode method allows users to specify a custom numerical error code and send it as a parameter to a specified server URL. This method marks the error occurrence time, and the error code is logged by the server and displayed on the dashboard for error tracking and analysis.

Advantages

  • Using numerical error codes improves readability and standardization.
  • The dashboard can directly parse and display error types and timestamps, facilitating issue identification and resolution.
  • Scalable design allows developers to add custom error codes for different scenarios.

⚠️ Note

  1. Error Code Type
    Ensure that the errorCode is a numerical type. Otherwise, the method will reject the input and throw an error.

  2. Request Frequency Control
    To prevent high server load due to frequent errors, implement a throttling mechanism to limit the number of error uploads per second.


Syntax

javascript
sendMpegErrCode(url, errorCode);

Parameters

NameTypeDescription
urlStringRequired. The server's API base URL to receive error data.
errorCodeNumberRequired. A custom numerical error code to specify the type or context of the error.

Features and Usage

  1. Custom Error Codes

    • Users can define a custom numerical error code (e.g., 1001 or 2002) to indicate the cause or type of an error.
  2. Error Tracking and Analysis

    • Error data, including the numerical code and timestamp, is logged on the server and displayed on the dashboard, aiding in problem diagnosis and frequency analysis.
  3. Real-Time Error Logging

    • The method automatically appends the current timestamp to the request, ensuring accurate logging of when the error occurred.

Example Usage

1. Send an Error Code to the Server

javascript
import JBLWebSocket from '@/assets/js/jbl.es.js';

const authorizationKey = ${Product authorization key};
const channelName = "MovieChannel";

// Establish a connection with WebSocket
JBLWebSocket.connect(authorizationKey, channelName);

// Define the server URL and error code
const serverUrl = 'https://example.com/api/log-error';
const errorCode = 1001; // Custom numerical error code

// Send the error code
JBLWebSocket.sendMpegErrCode(serverUrl, errorCode);

2. Handle Errors During Playback

javascript
player.on(Mpegts.Events.ERROR, (type, details, data) => {
    console.error('Playback error:', type, details, data);

    // Assign a custom error code based on the error type
    const errorCode = type === 'networkError' ? 1001 : 2001;

    // Send the error code to the server
    JBLWebSocket.sendMpegErrCode('https://example.com/api/log-error', errorCode);
});

getMpegBuffer()

Description

The getMpegBuffer method retrieves information about the current MPEG video playback buffer, such as the size of the buffered data and buffering progress. This data can be used for debugging or monitoring playback status.

⚠️ Note

  • Ensure the player has been initialized and loaded with data before calling this

method. Otherwise, the bufferInfo object will be empty.

  • Ensure that the video buffer supports standard API interfaces to provide the necessary data.

Syntax

javascript
const bufferInfo = getMpegBuffer();

Return Value

NameTypeDescription
bufferInfoObjectAn object containing current video buffer data, including buffer ranges and buffered data size.

Structure of the bufferInfo Object

javascript
{
    buffered: Number, // Total buffered data (in seconds)
    newBuffer: Number, // Current playback time (in seconds)
    oldBuffer: Number, // Buffer range
}

Example Usage

The following code demonstrates how to use getMpegBuffer to retrieve buffer information:

javascript
// Retrieve the current buffer information
const bufferInfo = getMpegBuffer();

if (bufferInfo) {
    console.log('Buffer Range:', bufferInfo.bufferedRanges);
    console.log('Total Buffered Data:', bufferInfo.totalBuffered, 'seconds');
    console.log('Current Playback Time:', bufferInfo.currentTime, 'seconds');
} else {
    console.error('Unable to retrieve buffer information. Please check the player status.');
}

Features and Usage

  1. Playback Monitoring

    • Retrieve real-time video buffer data to monitor playback status, such as stalling or insufficient buffering.
  2. Performance Debugging

    • Analyze buffer data in development or testing environments to identify bottlenecks and optimize playback.

Overall Process

  1. Use the testMpegts method to start monitoring the playback status of multiple streaming lines within a channel.
  2. Upload the data to the data center for analysis and recording.
  3. When higher playback performance is needed, retrieve the best-performing line using the getResourceUrl method and switch to it.

Through this process, developers can efficiently monitor and dynamically adjust MPEG-TS streaming, enhancing the user experience.