P2P Streaming Engine

vuePress-theme-reco    2018 - 2021
P2P Streaming Engine P2P Streaming Engine

Choose mode

  • dark
  • auto
  • light
Documents
  • Introduction
  • Web SDK

    • Hls.js
    • Dash.js
    • Shaka-Player
    • MP4
    • Downloader
  • Android SDK
  • iOS SDK
  • Flutter SDK
Pricing
Contact Us
Partnership
Console
GitHub
语言
  • English
  • 简体中文

Documents
  • Introduction
  • Web SDK

    • Hls.js
    • Dash.js
    • Shaka-Player
    • MP4
    • Downloader
  • Android SDK
  • iOS SDK
  • Flutter SDK
Pricing
Contact Us
Partnership
Console
GitHub
语言
  • English
  • 简体中文
  • Introduction
  • FAQ
  • Tracking Service
  • Signaling Service
  • P2P Optimization
  • Console

    • Domain/AppId Binding
    • Data Analysis
    • P2P Control
    • Restful API
  • Hls.js SDK

    • Introduction
    • Usage
    • Player Integration
    • API & Config
      • Introduction
      • Use Hls.js wrapped with P2PEngine
      • Create instance
      • P2PEngine API
      • P2PEngine Events
      • Advanced Usage
    • CDN
    • Change Log
  • Android SDK

    • Introduction
    • Usage
    • API & Config
    • Change Log
  • iOS SDK

    • Introduction
    • Usage
    • API & Config
    • Change Log
  • Flutter SDK

    • Introduction
    • Usage
    • API & Config
    • Change Log
  • Shaka-Player SDK

    • Introduction
    • Usage
    • Player Integration
    • API & Config
    • Change Log
  • Web MP4 SDK

    • Introduction
    • Usage
    • Player Integration
    • API & Config
    • Change Log
  • Dash.js SDK

    • Introduction
    • Usage
    • Player Integration
    • API & Config
    • Change Log
  • Web Downloader

    • Introduction
    • Usage
    • API & Config
    • Change Log
  • Android SDK 1.x

    • Introduction
    • Usage
    • API & Config
    • Change Log
  • More

    • Design

API & Config

vuePress-theme-reco    2018 - 2021

API & Config


# Introduction

CDNBye implements WebRTC datachannel to scale live/vod video streaming by peer-to-peer network using bittorrent-like protocol.

To use CDNBye hlsjs-p2p-engine, WebRTC support is required (Chrome, Firefox, Opera, Safari).

# Use Hls.js wrapped with P2PEngine

# Hls.engineVersion (static method)

Show the current version of CDNBye plugin.

# Hls.WEBRTC_SUPPORT (static method)

Is WebRTC natively supported in the environment?

if (Hls.WEBRTC_SUPPORT) {
  // WebRTC is supported
} else {
  // Use a fallback
}

# Create instance

# var hls = new Hls({p2pConfig: [opts]});

Create a new Hls instance.

# var engine = hls.p2pEngine;

Get the P2PEngine instance from Hls instance.

If opts is specified, then the default options (shown below) will be overridden.

Field Type Default Description
logLevel string|boolean 'error' Print log level(warn, error, none,false=none, true=warn).
live boolean false tell engine whether in live or VOD mode.
wsSignalerAddr string 'wss://signal.cdnbye.com' The address of signal server.
announce string 'https://tracker.cdnbye.com/v1' The address of tracker server.
memoryCacheLimit Object {"pc": 1024 * 1024 * 512, "mobile": 1024 * 1024 * 256} The max size of binary data that can be stored in the cache.
p2pEnabled boolean true Enable or disable p2p engine.
wifiOnly boolean false Only allow uploading on Wi-Fi and Ethernet.
dcDownloadTimeout number 25 Max download timeout for WebRTC datachannel.
webRTCConfig Object {} A Configuration dictionary providing options to configure WebRTC connections.
useHttpRange boolean false Use HTTP ranges requests where it is possible. Allows to continue (and not start over) aborted P2P downloads over HTTP(True in live mode by default).
channelIdPrefix string '' Required while using customized channelId(5 <= length <= 15), recommended to set it as the unique identifier of your organization.

# P2PEngine API

# P2PEngine.version (static)

Get the version of P2PEngine.

# P2PEngine.protocolVersion (static)

Get the version of P2P protocol,only have the same protocol version as another platform can both interconnect with each other.

# P2PEngine.isSupported() (static method)

Returns true if WebRTC data channel is supported by the browser.

# var engine = new P2PEngine(hlsjs, p2pConfig);

Create a new P2PEngine instance. Or you can get P2PEngine instance from hlsjs:

var hls = new Hls();
var engine = hls.p2pEngine;

# engine.enableP2P()

Resume P2P if it has been stopped.

# engine.disableP2P()

Disable engine to stop p2p and free used resources.

# engine.destroy()

Stop p2p and free used resources, it will be called automatically before hls.js is destroyed.

# P2PEngine Events

# engine.on('peerId', function (peerId) {})

Emitted when the peer Id of this client is obtained from server.

# engine.on('peers', function (peers) {})

Emitted when successfully connected with new peer.

# engine.on('stats', function (stats) {})

Emitted when data is downloaded/uploaded.
stats.totalHTTPDownloaded: total data downloaded by HTTP(KB).
stats.totalP2PDownloaded: total data downloaded by P2P(KB).
stats.totalP2PUploaded: total data uploaded by P2P(KB).
stats.p2pDownloadSpeed: p2p download speed(KB/s).

# engine.on('serverConnected', function (connected) {})

Emitted when websocket is opened/closed.

# engine.on('exception', function (e) {})

Emitted when exception occured.
e.code: Exception identifier(TRACKER_EXPT SIGNAL_EXPT HLSJS_EXPT)
e.message: Exception message
e.stack: Exception stack

# Get p2p information from p2pConfig

p2pConfig: {
    getStats: function (totalP2PDownloaded, totalP2PUploaded, totalHTTPDownloaded, p2pDownloadSpeed) {
        // get the downloading statistics
    },
    getPeerId: function (peerId) {
        // get peer Id
    },
    getPeersInfo: function (peers) {
        // get peers information
    }
}

# Advanced Usage

# Dynamic m3u8 path issue

The channelId is an identifier used by our backend to match peers that are watching the same content. It is an optional parameter, and by default, we generate channelId from the content URL by removing any query parameters and protocol from it. Some m3u8 urls play the same live/vod but have different paths on them. For example, example.com/clientId1/streamId.m3u8 and example.com/clientId2/streamId.m3u8. In this case, you can format a common channelId for them.

// Set channelIdPrefix in p2pConfig before setting channelId! Connectivity with other platform should have the same channelIdPrefix.
p2pConfig: {
    channelIdPrefix: YOUR_UNIQUE_ID,
    channelId: function (m3u8Url) {
        const videoId = extractVideoIdFromUrl(m3u8Url);   // make a channelId by removing the different part which is defined by yourself
        return videoId;
    },
    // If ts address in m3u8 is relative, you need to set the segmentid
    segmentId: function (streamId, sn, url, range) {
        return ""+sn;               // 默认的segmentId是绝对路径,因此需要替换
    },
}

Interconnect with other platform should ensure that both have the same channelIdPrefix and channelId.

# Dynamic ts path issue

Like dynamic m3u8 path issue, you should format a common segmentId for the same ts file. You can override the segment ID like this:

p2pConfig: {
    /*
        streamId: The id of stream
        sn: The serial number of segment
        segmentUrl: The url of segment
     */
    segmentId: function (streamId, sn, segmentUrl, range) {
        const tsId = extractSegmentIdFromUrl(segmentUrl);
        return tsId;
    }
}

# Config STUN Servers

p2pConfig: {
    webRTCConfig: { 
        config: {         // custom webrtc configuration (used by RTCPeerConnection constructor)
            iceServers: [
                { urls: 'stun:stun.l.google.com:19302' }, 
                { urls: 'stun:global.stun.twilio.com:3478?transport=udp' }
            ] 
        }
    }
}

# Allow Http Range Request

If http range request is activated, we are able to get chunks of data from peer and then complete the segments by getting other chunks from the CDN, thus, reducing your CDN bandwidth. To activate range requests, See Allow Http Range Request. Besides, the code below is needed:

p2pConfig: {
    useHttpRange: true,
}

# How to Check Segment Validity

Sometimes we need to prevent a peer from sending a fake segment (such as the bittorrent with a hash function). CDNBye provides a validation callback with buffer of the downloaded segment, developer should implement the actual validator. For example, you can create a program that generates hashes for the segments and stores them in a specific file or injects into m3u8 playlist files the hashes information. If the callback returns false, then the segment is not valid.

p2pConfig: {
   validateSegment: function (level, sn, buffer) {
       var hash = hashFile.getHash(level, sn);
       return hash === md5(buffer);
   }
}

# Online Debugging

CDNBye provides two query parameters for online debugging:

  • You can display the log information in console by adding a query parameter _debug=1 to the url, such as http://your_website.com?_debug=1.
  • In the case that P2P has been enabled, to temporarily disable P2P, you can add query parameter _p2p=0 to the url, such as http://your_website.com?_p2p=0.