Skip to main content

API & Config

Create instance

var engine = new P2PEngineShaka(player, {p2pConfig: [opts]}, shaka = window.shaka);

Creates a new P2PEngineShaka instance; player is an instance of Shaka Player.

If opts is provided, it overrides the default options shown below.

FieldTypeDefaultDescription
logLevelstring|boolean'error'Log level to print (warn, error, none; false=none, true=warn).
tokenstringundefinedToken used to aggregate and display multi-domain data on the console. Also required when customizing channelId.
trackerZonestring'eu'Country code for the tracker server address ('eu', 'hk', 'us').
memoryCacheLimitObject{"pc": 400 * 1024 * 1024, "mobile": 100 * 1024 * 1024}Maximum size of binary data that can be stored in the in-memory cache.
useDiskCachebooleantrueUses IndexedDB to cache data for VOD streaming.
diskCacheLimitObject{"pc": 1500 * 1024 * 1024, "mobile": 1000 * 1024 * 1024}Maximum size of binary data that can be stored in the disk cache.
p2pEnabledbooleantrueEnables or disables the P2P engine.
webRTCConfigObject{}A configuration dictionary for configuring WebRTC connections.
useHttpRangebooleantrueUses HTTP range requests where possible. Allows resuming (not restarting) aborted P2P downloads over HTTP.
sharePlaylistbooleanfalseAllows P2P transmission of m3u8 files.
prefetchOnlybooleanfalseUses only prefetch strategy for P2P downloading (HLS only).
startFromSegmentOffsetnumber3The segment offset at which the client starts connecting to the tracker server.

P2PEngineShaka API

P2PEngineShaka.version (static method)

Returns the current version of P2PEngineShaka.

P2PEngineShaka.protocolVersion (static method)

Returns the P2P protocol version.

P2PEngineShaka.isSupported() (static method)

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

engine.enableP2P()

Resumes P2P streaming after it has been stopped.

engine.disableP2P()

Disables the engine to stop P2P streaming and free up resources.

engine.destroy()

Stops P2P streaming and frees up resources.

P2PEngineShaka Events

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

Emitted when this client's peer ID is received from the server.

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

Emitted when successfully connected to a new peer.

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

Emitted whenever data is downloaded or uploaded.
stats.totalHTTPDownloaded: total data downloaded via HTTP (KB).
stats.totalP2PDownloaded: total data downloaded via P2P (KB).
stats.totalP2PUploaded: total data uploaded via P2P (KB).
stats.p2pDownloadSpeed: P2P download speed (KB/s).

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

Emitted when the WebSocket connection opens or closes.

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

Emitted when an exception occurs.
e.code: Exception identifier(TRACKER_EXPT SIGNAL_EXPT)
e.message: Exception message.
e.stack: Exception stack trace.

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
},
onHttpDownloaded: function (traffic) {
// listen to http downloaded traffic
},
onP2pDownloaded: function (traffic, speed) {
// listen to p2p downloaded traffic
},
onP2pUploaded: function (traffic) {
// listen to p2p uploaded traffic
},
}
note

Download and upload volumes are measured in KB. The unit of download speed is KB/s.

Advanced Usage

Dynamic M3u8/mpd Path Support

Some m3u8/mpd urls play the same live/vod but have different paths on them. For example, example.com/clientId1/streamId.mpd and example.com/clientId2/streamId.mpd. In this case, you can define a common channelId for them.

// Set token in p2pConfig before setting channelId!
p2pConfig: {
token: YOUR_TOKEN,
channelId: function (mpdUrl) {
const videoId = extractVideoIdFromUrl(mpdUrl); // make a channelId by removing the different part which is defined by yourself
return videoId;
}
// channelId: VIDEO_ID // for fixed channel id
}

Dynamic Segment Path Support

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

p2pConfig: {
/*
segmentUrl: The url of segment
range: The byte range of segment
*/
segmentId: function (segmentUrl, range) {
const segId = extractSegmentIdFromUrl(segmentUrl, range);
return segId;
}
}

Use Your Own STUN or TURN Server

STUN (Session Traversal Utilities for NAT) allows clients to discover their public IP address and the type of NAT they are behind. This information is used to establish the media connection. Although there are default STUN servers in this SDK, you can replace them with your own via P2PConfig. TURN (Traversal Using Relays around NAT) server is used to relay traffic if direct connection fails. You can config your TURN server in the same way as STUN.

p2pConfig: {
webRTCConfig: {
iceServers: [
{ urls: YOUR_STUN_OR_TURN_SERVER }
]
}
}

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. 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 (segId, buffer) {
var hash = hashFile.getHash(segId);
return hash === md5(buffer);
}
}