### Install Super Peer Automatically
Source: https://docs.swarmcloud.net/guides/super-peer
Automatically installs and starts a super peer listening on port 8080.
```bash
wget -qN https://cdn.swarmcloud.net/super-peer.sh && bash super-peer.sh --port 8080
```
--------------------------------
### Install SDK with Yarn
Source: https://docs.swarmcloud.net/rn
Install the SwarmCloud SDK using the Yarn package manager.
```bash
yarn add react-native-swarmcloud
```
--------------------------------
### Install SDK with npm
Source: https://docs.swarmcloud.net/rn
Install the SwarmCloud SDK using the npm package manager.
```bash
npm install --save react-native-swarmcloud
```
--------------------------------
### Install rx-player via npm
Source: https://docs.swarmcloud.net/rx-player
Install the rx-player library using npm for use with Browserify or Webpack.
```bash
npm install --save @swarmcloud/rx-player
```
--------------------------------
### Specify Playback Start Point with EXT-X-START Tag
Source: https://docs.swarmcloud.net/web-hls/API
Configure HlsProxy to insert the EXT-X-START tag for live streams, allowing playback to begin from a specified start point. Note that this may introduce additional delay.
```javascript
// sw.js
self.importScripts('https://cdn.jsdelivr.net/npm/@swarmcloud/hls/hls-proxy.js')
new HlsProxy({
insertTimeOffsetTag: true,
playlistTimeOffset: 0.01,
})
```
--------------------------------
### Start Super Peer Manually
Source: https://docs.swarmcloud.net/guides/super-peer
Starts the super peer application by setting the listening port in the .env file and using pm2 to manage the process.
```bash
cd super-peer && echo listenPort=8080 >> .env
```
```bash
npm i -g pm2
sudo ln -s /usr/local/nodejs/bin/pm2 /usr/local/bin
pm2 start index.js -n super-peer
```
--------------------------------
### Enable P2P
Source: https://docs.swarmcloud.net/media/API
Start the P2P functionality using the P2PEngineMedia instance.
```javascript
engine.enableP2P()
```
--------------------------------
### Install Dash.js via npm
Source: https://docs.swarmcloud.net/dashjs
Install the @swarmcloud/dashjs package using npm for use with Browserify or Webpack.
```bash
npm install --save @swarmcloud/dashjs
```
--------------------------------
### Install P2P Engine using npm
Source: https://docs.swarmcloud.net/web-hls
Install the @swarmcloud/hls package using npm for use with Browserify or Webpack.
```bash
npm install --save @swarmcloud/hls
```
--------------------------------
### Initialize Flutter P2P Engine and Load Video
Source: https://docs.swarmcloud.net/flutter
This example demonstrates how to initialize the Flutter P2P Engine with a token and configuration, and then parse a stream URL for video playback.
```dart
import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';
import 'package:flutter_p2p_engine/flutter_p2p_engine.dart';
// Init p2p engine
_initEngine();
// Start playing video
_loadVideo();
_initEngine() async {
await FlutterP2pEngine.init(
YOUR_TOKEN,
config: P2pConfig(
trackerZone: TrackerZone.Europe, // Set HongKong or USA if you changed zone
),
);
}
_loadVideo() async {
var url = YOUR_STREAM_URL;
url = await FlutterP2pEngine.parseStreamURL(url); // Parse your stream url
player = VideoPlayerController.networkUrl(url);
}
```
--------------------------------
### Install VHS via npm
Source: https://docs.swarmcloud.net/vhs
Install the VHS package as a project dependency using npm.
```bash
npm install --save @swarmcloud/vhs
```
--------------------------------
### Install Shaka Player via npm
Source: https://docs.swarmcloud.net/shaka
Install the SwarmCloud Shaka Player package using npm for use with Browserify or Webpack.
```bash
npm install --save @swarmcloud/shaka
```
--------------------------------
### Install WebRTC Adapter via npm
Source: https://docs.swarmcloud.net/faq
Install a specific version of the WebRTC adapter using npm for a more resilient integration. This is recommended for managing dependencies in larger projects.
```bash
npm install --save webrtc-adapter@9.0.3
```
--------------------------------
### Specify Preferred Playback Start Point (Java)
Source: https://docs.swarmcloud.net/android/API
Configures the SDK to insert the EXT-X-START tag to begin playback from a specific point in a live stream. Note that this may introduce additional delay.
```java
P2pConfig config = new P2pConfig.Builder()
.insertTimeOffsetTag(0.0)
.build();
```
--------------------------------
### Install Dependencies with CocoaPods
Source: https://docs.swarmcloud.net/ios
Run this command in your terminal after updating your Podfile to install the specified dependencies.
```bash
$ pod install
```
--------------------------------
### Dynamic m3u8 Path Support Example
Source: https://docs.swarmcloud.net/rn/API
Example demonstrating how to use parseStreamURL with a custom videoId extracted from the original URL to handle dynamic m3u8 paths.
```javascript
const videoId = extractVideoIdFromUrl(originalUrl); /// extractVideoIdFromUrl is a function defined by yourself, you just need to extract video id from url
const url = parseStreamURL(originalUrl, videoId);
```
--------------------------------
### Basic Shaka Player Usage with P2P
Source: https://docs.swarmcloud.net/shaka
Initialize a Shaka Player and integrate the P2P engine. This example shows how to check for P2P support and configure tracker zones.
```javascript
const player = new shaka.Player();
player.attach(video);
if (P2PEngineShaka.isSupported()) {
new P2PEngineShaka(player, {
// trackerZone: 'hk', // if using Hongkong tracker
// trackerZone: 'us', // if using USA tracker
// token: YOUR_TOKEN
}, shaka);
}
player.load(play_url)
```
--------------------------------
### Install THEOplayer with npm
Source: https://docs.swarmcloud.net/theoplayer
Install the THEOplayer package using npm for use in your project. This is suitable for projects using module bundlers like Webpack or Browserify.
```bash
npm install --save @swarmcloud/theoplayer
```
--------------------------------
### Specify Preferred Playback Start Point
Source: https://docs.swarmcloud.net/android/API
Configures the SDK to insert the EXT-X-START tag to begin playback from a specific point in a live stream. Note that this may introduce additional delay.
```kotlin
val config = P2pConfig.Builder()
.insertTimeOffsetTag(0.0)
.build()
```
--------------------------------
### Install Bitmovin P2P Engine via npm
Source: https://docs.swarmcloud.net/bitmovin
Install the SwarmCloud Bitmovin P2P engine using npm for use with Browserify or Webpack. This is the recommended approach for module-based projects.
```bash
npm install --save @swarmcloud/bitmovin
```
--------------------------------
### P2pEngineTheo Static Methods
Source: https://docs.swarmcloud.net/theoplayer/API
Provides static methods to get version information and check browser support.
```APIDOC
## P2pEngineTheo Static Methods
### ** _P2pEngineTheo.version_**
Get the version of P2pEngineTheo.
### **_P2pEngineTheo.protocolVersion_**
Get the version of P2P protocol.
### **_P2pEngineTheo.isSupported()_**
Returns true if WebRTC data channel is supported by the browser.
```
--------------------------------
### Enable Auto Startup with PM2
Source: https://docs.swarmcloud.net/guides/super-peer
Configures pm2 to automatically start the super peer process on system boot.
```bash
pm2 save && pm2 startup
```
--------------------------------
### Setup P2P Engine in Swift
Source: https://docs.swarmcloud.net/guides/troubleshooting
Configure the P2P engine with tracker zone and debug mode enabled. Use this for iOS applications.
```swift
let config = P2pConfig(
trackerZone: .Europe, // Set HongKong or USA if you changed zone
debug: true
)
P2pEngine.setup(token: YOUR_TOKEN, config: config)
```
--------------------------------
### Default P2P Configuration
Source: https://docs.swarmcloud.net/android/API
Configure P2P settings using the P2pConfig builder. This example shows default values for various parameters like logging, tracker zone, timeouts, cache limits, and P2P engine options.
```kotlin
val config = P2pConfig.Builder()
.logEnabled(false) // Enable or disable log
.logLevel(LogLevel.WARN) // Print log level
.trackerZone(TrackerZone.Europe) // The country enum for the tracker server address(Europe, HongKong, USA).
.downloadTimeout(15000, TimeUnit.MILLISECONDS) // TS file download timeout by HTTP
.localPortHls(0) // The port for local http server of HLS(Use random port by default)
.localPortDash(0) // The port for local http server of DASH(Use random port by default)
.diskCacheLimit(2000*1024*1024) // The max size of binary data that can be stored in the disk cache for VOD(Set to 0 will disable disk cache)
.memoryCacheCountLimit(15) // The max count of ts files that can be stored in the memory cache
.p2pEnabled(true) // Enable or disable p2p engine
.withTag(null) // Add a custom label to every different user session, which in turn will provide you the ability to have more meaningful analysis of the data gathered
.webRTCConfig(null) // Providing options to configure WebRTC connections
.maxPeerConnections(25) // Max peer connections at the same time
.startFromSegmentOffset(3) // The segment offset that start to connect to tracker server
.useHttpRange(true) // Use HTTP ranges requests where it is possible. Allows to continue (and not start over) aborted P2P downloads over HTTP
.useStrictHlsSegmentId(false) // Use segment url based segment id instead of sequence number based one
.httpHeadersForHls(null) // Set HTTP Headers while requesting ts and m3u8.
.httpHeadersForDash(null) // Set HTTP Headers while requesting Dash files.
.sharePlaylist(false) // Allow the P2P transmission of m3u8 file.
.prefetchOnly(false) // Only use prefetch strategy in p2p downloading(Only for HLS).
.logPersistent(false) // Save logs to the file({Environment.getExternalStorageDirectory()}/logger/).
.insertTimeOffsetTag(null) // Insert "#ext-x-start: time-offset = [timeOffset]" in m3u8 file to force the player to start loading from the first ts of playlist, where [timeOffset] is the offset in seconds to start playing the video, only works on live mode
.p2pProtocolVersion(P2pProtocolVersion.V8) // The version of P2P protocol, only have the same protocol version as another platform can both interconnect with each other
.dashMediaFiles(
arrayListOf("mp4", "fmp4", "webm", "m4s", "m4v")) // The supported media file type of DASH.
.build()
```
--------------------------------
### Setup Player Interactor for Exoplayer (Java)
Source: https://docs.swarmcloud.net/android
Configure the PlayerInteractor for live streaming with Exoplayer in Java. This snippet provides the onBufferedDuration callback.
```java
P2pEngine.getInstance().setPlayerInteractor(new PlayerInteractor() {
public long onBufferedDuration() {
// Exoplayer in milliseconds
if (play != null) {
return player.getBufferedPosition() - player.getCurrentPosition();
}
return -1;
}
});
```
--------------------------------
### P2pEngine.setup
Source: https://docs.swarmcloud.net/ios/API
Initialize the P2pEngine with your customer token. This should be called during application launch.
```APIDOC
## P2pEngine Setup
### Description
Initialize **_P2pEngine_** in **_AppDelegate.m_**. Replace **_YOUR_TOKEN_** with your Customer ID.
### Method
`setup(token: YOUR_TOKEN)` (Swift)
`setupWithToken:config:` (Objective-C)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```swift
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
P2pEngine.setup(token: YOUR_TOKEN)
return true
}
```
```objective-c
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[P2pEngine setupWithToken:YOUR_TOKEN config:NULL];
return YES;
}
```
### Response
#### Success Response (200)
Engine initialized successfully.
```
--------------------------------
### Initialize P2pEngine (Swift)
Source: https://docs.swarmcloud.net/ios/API
Set up the P2pEngine in your AppDelegate for the first time. Requires your customer token.
```swift
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
P2pEngine.setup(token: YOUR_TOKEN)
return true
}
```
--------------------------------
### Include THEOplayer via Script Tag
Source: https://docs.swarmcloud.net/theoplayer
Include the THEOplayer library by adding this script tag to your HTML. This is a simple way to get started.
```html
```
--------------------------------
### Setup Player Interactor for Exoplayer (Kotlin)
Source: https://docs.swarmcloud.net/android
Configure the PlayerInteractor for live streaming with Exoplayer in Kotlin. This snippet provides the onBufferedDuration callback.
```kotlin
P2pEngine.instance?.setPlayerInteractor(object : PlayerInteractor() {
override fun onBufferedDuration(): Long {
// Exoplayer in milliseconds
return if (player != null) {
player!!.bufferedPosition - player!!.currentPosition
} else {
-1
}
}
})
```
--------------------------------
### Setup P2P Engine in Objective-C
Source: https://docs.swarmcloud.net/guides/troubleshooting
Configure the P2P engine with tracker zone and debug mode enabled. Use this for iOS applications.
```objective-c
P2pConfig* config = [P2pConfig defaultConfiguration];
config.trackerZone = TrackerZoneEurope; // Set HongKong or USA if you changed zone
config.debug = YES;
[P2pEngine setupWithToken:YOUR_TOKEN config:config];
```
--------------------------------
### GET Request for Historical P2P Traffic
Source: https://docs.swarmcloud.net/guides/api
Fetches historical P2P traffic data for a specified time range. Requires start and end timestamps and a granularity parameter.
```http
GET /user/user_id/{user_id}/domain/domain_id/{domain_id}/p2p
```
```json
{
"ret": 0,
"name": "statistic",
"data": {
"max": {
"ts": 1591372800,
"value": 541188637412
},
"list": [
{"ts":1590854400,"value":1591200000},
{"ts":1590940800,"value":194511284034},
{"ts":1591027200,"value":541188637412}
]
}
}
```
--------------------------------
### Initialize P2pEngine in Swift
Source: https://docs.swarmcloud.net/ios
Set up the P2pEngine with your token and configuration, including the tracker zone, in your AppDelegate.
```swift
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
let config = P2pConfig(
trackerZone: .Europe // Set HongKong or USA if you changed zone
)
P2pEngine.setup(token: YOUR_TOKEN, config: config) // replace with your own token
return true
}
```
--------------------------------
### Install Node.js Manually
Source: https://docs.swarmcloud.net/guides/super-peer
Manually installs Node.js version 18.15.0 for Linux x64. This is a prerequisite for manual super peer installation if Node.js is not already present.
```bash
wget https://npmmirror.com/mirrors/node/v18.15.0/node-v18.15.0-linux-x64.tar.xz
tar -xvf node-v18.15.0-linux-x64.tar.xz
sudo mkdir -p /usr/local/nodejs
sudo mv node-v18.15.0-linux-x64/* /usr/local/nodejs/
sudo ln -s /usr/local/nodejs/bin/node /usr/local/bin
sudo ln -s /usr/local/nodejs/bin/npm /usr/local/bin
```
--------------------------------
### P2P Engine Standalone Usage with hls.js
Source: https://docs.swarmcloud.net/web-hls
Instantiate hls.js and P2pEngineHls, passing p2pConfig and hlsjsConfig. This example handles MSE support.
```javascript
var p2pConfig = {
// Other p2pConfig options if applicable
}
var engine;
if (P2pEngineHls.isMSESupported()) {
var hls = new Hls();
p2pConfig.hlsjsInstance = hls; // set hlsjs instance to SDK
engine = new P2pEngineHls(p2pConfig);
// Use hls just like your usual hls.js…
hls.loadSource(contentUrl);
hls.attachMedia(video);
hls.on(Hls.Events.MANIFEST_PARSED,function() {
video.play();
});
} else {
engine = new P2pEngineHls(p2pConfig); // equal to new P2pEngineHls.ServiceWorkerEngine(p2pConfig);
engine.registerServiceWorker().catch(() => {}).finally(() => {
// native video playback here
});
}
```
--------------------------------
### Initialize P2pEngine (Objective-C)
Source: https://docs.swarmcloud.net/ios/API
Set up the P2pEngine in your AppDelegate for the first time. Requires your customer token.
```objective-c
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[P2pEngine setupWithToken:YOUR_TOKEN config:NULL];
return YES;
}
```
--------------------------------
### Initialize and Use P2PEngineMedia
Source: https://docs.swarmcloud.net/media
Import and instantiate P2PEngineMedia, optionally configuring it with various options. Use getProxiedUrl to obtain a P2P-enabled playback URL for media elements.
```javascript
import P2PEngineMedia from '@swarmcloud/media';
// Create P2PEngineMedia instance...
var engine = new P2PEngineMedia({
// logLevel: 'debug',
// swFile: './sw.js', // you may need to change it to the actual path of sw.js
// trackerZone: 'hk', // if using Hongkong tracker
// trackerZone: 'us', // if using USA tracker
// token: YOUR_TOKEN
// Other p2pConfig options provided by P2PEngineMedia
})
// get the proxied playback url
engine.getProxiedUrl('http://example.mp4').then((url) => {
video.src = url;
})
```
--------------------------------
### P2pEngine.startLocalServer
Source: https://docs.swarmcloud.net/ios/API
Restart the local proxy server.
```APIDOC
## Restart Local Proxy
### Description
Restart the local proxy server.
### Method
`startLocalServer()` (Swift)
`startLocalServer` (Objective-C)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```swift
P2pEngine.shared.startLocalServer()
```
```objective-c
[P2pEngine.sharedInstance startLocalServer];
```
### Response
#### Success Response (200)
Operation completed successfully.
```
--------------------------------
### Initialize and Load Video with rx-player and P2P Engine
Source: https://docs.swarmcloud.net/rx-player
Configure and initialize the rx-player with a P2P engine, then load a video playlist. Ensure the video element is present in the DOM.
```javascript
var rxConfig = {
url: YOUR_PLAYLIST_URL,
transport: "dash",
autoPlay: true,
}
const rxPlayer = new RxPlayer({
videoElement: document.getElementById("videoplayer")
});
var engine = new P2pEngineRxPlayer(rxPlayer, {
// trackerZone: 'hk', // if using Hongkong tracker
// trackerZone: 'us', // if using USA tracker
// token: YOUR_TOKEN
})
rxPlayer.loadVideo(rxConfig);
```
--------------------------------
### Initialize THEOplayer and P2P Engine
Source: https://docs.swarmcloud.net/theoplayer
This snippet shows how to initialize a THEOplayer instance and then attach the P2P engine to it. Ensure you replace placeholders like YOUR_THEOplayer_LICENSE_KEY and YOUR_PLAYLIST_URL.
```javascript
var element = document.querySelector(".theoplayer-container");
var player = new THEOplayer.Player(element, {
libraryLocation: '/path/to/your-theoplayer-folder',
liveOffset: 30,
license: YOUR_THEOplayer_LICENSE_KEY,
});
var engine = new P2pEngineTheo(player, {
// trackerZone: 'hk', // if using Hongkong tracker
// trackerZone: 'us', // if using USA tracker
// token: YOUR_TOKEN
});
player.source = {
sources: [{
src: YOUR_PLAYLIST_URL,
}]
};
```
--------------------------------
### Setup HTTP Headers for HLS and DASH (Java)
Source: https://docs.swarmcloud.net/android/API
Adds custom HTTP headers, such as User-Agent, to requests for HLS and DASH streams. This is useful for anti-leeching or analytics.
```java
Map headers = new HashMap();
headers.put("User-Agent", "XXX");
engine.setHttpHeadersForHls(headers);
engine.setHttpHeadersForDash(headers);
```
--------------------------------
### Initialize P2P Engine with Default Options
Source: https://docs.swarmcloud.net/bitmovin/API
Create a new P2pEngineBitmovin instance. Default options will be used unless overridden by opts.
```javascript
var engine = new P2pEngineBitmovin({p2pConfig: [opts]});
```
--------------------------------
### Initialize P2PEngineDash with MediaPlayer
Source: https://docs.swarmcloud.net/dashjs
Create a dash.js MediaPlayer instance and then initialize the P2PEngineDash with the player and an optional configuration object.
```javascript
var player = dashjs.MediaPlayer().create()
if (P2PEngineDash.isSupported()) {
var p2pConfig = {
logLevel: 'debug',
// Other p2pConfig options if applicable
};
new P2PEngineDash(player, p2pConfig);
}
// Use dash.js just like your usual dash.js…
```
--------------------------------
### Super Peer Request Body Example
Source: https://docs.swarmcloud.net/guides/super-peer
This is an example of the JSON body structure for a Super Peer request, detailing various parameters for list items.
```json
{
"list": [
{
"token": "user token"
"channel": "channel ID(Base64 encoded)"
"trackerZone": "cn, hk, us"
"live": "live streaming or vod"
"signal1": "primary signal address"
"signal2": "backup signal address"
"priority": "priority of seeding"
"keepAlive": "always alive"
"noUseDiskCache": "does not use disk cache for vod"
"maxConnections": "maximum p2p connections, default is 80"
"label": "customized super peer label"
}
]
}
```
--------------------------------
### Instantiate P2pEngine
Source: https://docs.swarmcloud.net/rn/API
Call initP2pEngine once to instantiate the P2P engine with a token and configuration.
```javascript
import { initP2pEngine } from 'react-native-swarmcloud';
initP2pEngine(token, config)
```
--------------------------------
### HLS Instance Creation
Source: https://docs.swarmcloud.net/web-hls/API
Demonstrates how to create a new HLS instance, optionally with P2P configuration, and how to access the P2P engine instance.
```APIDOC
## new Hls(config)
### Description
Creates a new HLS instance. If `p2pConfig` is provided in the configuration object, it will be used to initialize the P2P engine.
### Parameters
- **config** (object) - Configuration object for the HLS instance.
- **p2pConfig** (object) - Optional. Configuration object for the P2P engine, equivalent to the `p2pConfig` passed to `P2pEngineHls`.
## hls.p2pEngine
### Description
Returns the instance of `P2pEngineHls` associated with this HLS instance.
```
--------------------------------
### GET Request for Realtime Domain Information
Source: https://docs.swarmcloud.net/guides/api
Retrieves current real-time statistics for a specific domain or all domains. Use '0' for domain_id to get summary data.
```http
GET /user/user_id/{user_id}/domain/domain_id/{domain_id}
```
```json
{
"ret": 0,
"name": "domain",
"data": {
"num_rt": 456,
"num_max": 892,
"traffic_p2p_day": 1022794195,
"traffic_http_day": 1022794195,
"api_frequency_day": 14805,
}
}
```
--------------------------------
### Create P2pEngineRxPlayer Instance
Source: https://docs.swarmcloud.net/rx-player/API
Instantiate P2pEngineRxPlayer with a video.js player instance and optional P2P configuration. Default options can be overridden by providing a 'p2pConfig' object.
```javascript
var engine = new P2pEngineRxPlayer(player, {p2pConfig: [opts]});
```
--------------------------------
### GET Request to Set TimeZone
Source: https://docs.swarmcloud.net/guides/api
Allows setting the user's timezone by providing the UTC offset. This endpoint uses a GET request but accepts a POST body.
```http
GET /user/user_id/{user_id}/timezone
```
--------------------------------
### Initialize P2pEngineHls
Source: https://docs.swarmcloud.net/web-hls/API
Create a new P2pEngineHls instance. Default options can be overridden by providing a p2pConfig object.
```javascript
var engine = new P2pEngineHls(p2pConfig);
```
--------------------------------
### API Response Example
Source: https://docs.swarmcloud.net/guides/api
This is an example of a successful API response (Status: 200) for a statistics request. It includes return code, name, and data with max values and a list of time-series data.
```json
Status: 200
{
"ret": 0,
"name": "statistic",
"data":
{
"max":
{
"ts": 1591372800,
"value": 109566
},
"list":
[
{"ts":1590854400,"value":66504},
{"ts":1590940800,"value":72373},
{"ts":1591027200,"value":78300}
]
}
}
```
--------------------------------
### P2pEngine Initialization
Source: https://docs.swarmcloud.net/rn/API
Initializes the P2P Engine with a provided token and configuration object. This should be called once.
```APIDOC
## initP2pEngine
### Description
Instantiates the P2P Engine. This function should be called only once with the necessary token and configuration.
### Method
`initP2pEngine(token: string, config: P2pConfig): Promise`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
* **token** (string) - Required - Token assigned by SwarmCloud.
* **config** (P2pConfig) - Required - Custom configuration for the P2P engine.
```
--------------------------------
### P2P Control API Response Example
Source: https://docs.swarmcloud.net/guides/api
This is an example of a successful API response (Status: 200) for the P2P control endpoint. It indicates the return code, name, and data confirming whether P2P is allowed and if the operation succeeded.
```json
Status: 200
{
"ret":0,
"name":"control",
"data":
{
"allow":true,
"succeed":true
}
}
```
--------------------------------
### Enable P2P at Runtime (Swift)
Source: https://docs.swarmcloud.net/ios/API
Enable the P2P engine. This change will only take effect when the next media file is played.
```swift
P2pEngine.shared.enableP2p()
```
--------------------------------
### Get SDK Version
Source: https://docs.swarmcloud.net/web-hls/API
Retrieve the version of the P2pEngineHls SDK.
```javascript
P2pEngineHls.version
```
--------------------------------
### Get MediaProxy Version
Source: https://docs.swarmcloud.net/media/API
Retrieve the version of the MediaProxy library.
```javascript
MediaProxy.version
```
--------------------------------
### Get P2PEngineMedia Version
Source: https://docs.swarmcloud.net/media/API
Retrieve the version of the P2PEngineMedia library.
```javascript
P2PEngineMedia.version
```
--------------------------------
### P2pEngine Initialization
Source: https://docs.swarmcloud.net/android/API
Initializes the P2pEngine singleton with the application context, a CDNBye token, and an optional P2pConfig.
```APIDOC
## P2pEngine Initialization
Instantiate **_P2pEngine_**, which is a singleton:
### Parameters
#### Path Parameters
- **context** (Context) - Yes - The instance of Application Context is recommended.
- **token** (String) - Yes - Token assigned by CDNBye.
- **config** (P2pConfig) - No - Custom configuration.
```kotlin
P2pEngine.init(context, token, config)
```
```java
P2pEngine.init(context, token, config);
```
```
--------------------------------
### Create P2pConfig Instance (Swift)
Source: https://docs.swarmcloud.net/ios/API
Instantiate a P2pConfig object to manage P2P settings. Default values can be overridden.
```swift
let config = P2pConfig()
```
--------------------------------
### Get ServiceWorker Engine Constructor
Source: https://docs.swarmcloud.net/web-hls/API
Access the constructor for the ServiceWorker-based P2pEngine.
```javascript
P2pEngineHls.ServiceWorkerEngine
```
--------------------------------
### Get Hlsjs Engine Constructor
Source: https://docs.swarmcloud.net/web-hls/API
Access the constructor for the Hlsjs-based P2pEngine.
```javascript
P2pEngineHls.HlsjsEngine
```
--------------------------------
### Create P2PEngineMedia Instance
Source: https://docs.swarmcloud.net/media/API
Instantiate P2PEngineMedia with optional configuration. Default options are used if p2pConfig is not provided.
```javascript
var engine = new P2PEngineMedia(p2pConfig);
```
--------------------------------
### Get P2P Protocol Version
Source: https://docs.swarmcloud.net/media/API
Retrieve the version of the P2P protocol.
```javascript
P2PEngineMedia.protocolVersion
```
--------------------------------
### Get P2P Engine Version
Source: https://docs.swarmcloud.net/bitmovin/API
Retrieve the current version of the P2pEngineBitmovin library.
```javascript
P2pEngineBitmovin.version
```
--------------------------------
### Create P2pEngineVHS Instance
Source: https://docs.swarmcloud.net/vhs/API
Instantiate P2pEngineVHS with a video.js player and optional p2p configuration. The player instance is required, and opts can override default settings.
```javascript
var engine = new P2pEngineVHS(player, {p2pConfig: [opts]}, videojs = window.videojs);
```
--------------------------------
### Get All Real-time Statistics
Source: https://docs.swarmcloud.net/guides/super-peer
Retrieves real-time statistics for all active workers in the system.
```APIDOC
## GET /stats
### Description
Retrieves real-time statistics for all active workers.
### Method
GET
### Endpoint
/stats
```
--------------------------------
### Enable P2P at Runtime (Objective-C)
Source: https://docs.swarmcloud.net/ios/API
Enable the P2P engine. This change will only take effect when the next media file is played.
```objective-c
[P2pEngine.sharedInstance enableP2p];
```
--------------------------------
### P2pEngineTheo Instance Methods
Source: https://docs.swarmcloud.net/theoplayer/API
Methods to control the P2P engine's behavior after instantiation.
```APIDOC
## P2pEngineTheo Instance Methods
### **_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.
```
--------------------------------
### Add SwarmCloudKit with CocoaPods
Source: https://docs.swarmcloud.net/ios
Specify the SwarmCloudKit pod in your Podfile to install it using CocoaPods.
```ruby
target 'TargetName' do
# Uncomment the next line if you're using Swift
# use_frameworks!
pod 'SwarmCloudKit', '~> 3.0'
end
```
--------------------------------
### P2pEngineTheo Configuration Options
Source: https://docs.swarmcloud.net/theoplayer/API
Default options for P2pEngineTheo instance creation. These can be overridden during instantiation.
```javascript
p2pConfig: {
logLevel: 'error',
token: undefined,
trackerZone: 'eu',
memoryCacheLimit: {"pc": 400 * 1024 * 1024, "mobile": 100 * 1024 * 1024},
useDiskCache: true,
diskCacheLimit: {"pc": 1500 * 1024 * 1024, "mobile": 1000 * 1024 * 1024},
p2pEnabled: true,
webRTCConfig: {},
useHttpRange: true,
sharePlaylist: false,
strictSegmentId: false,
prefetchOnly: false,
startFromSegmentOffset: 3
}
```
--------------------------------
### Get Current Engine Name
Source: https://docs.swarmcloud.net/web-hls/API
Retrieve the name of the currently operating P2P engine.
```javascript
engine.engineName;
```
--------------------------------
### Initialize P2P Engine
Source: https://docs.swarmcloud.net/flutter/API
Instantiate the P2pEngine singleton with a token and default configuration. The token is assigned by SwarmCloud.
```dart
FlutterP2pEngine.init(
token, /// replace with your token
config: P2pConfig.byDefault()
);
```
--------------------------------
### Get Current Engine Instance
Source: https://docs.swarmcloud.net/web-hls/API
Access the underlying engine instance that is currently active.
```javascript
engine.realEngine;
```
--------------------------------
### Initialize P2pEngine in Objective-C
Source: https://docs.swarmcloud.net/ios
Initialize the P2pEngine with your token and configuration, specifying the tracker zone, within your AppDelegate.
```objective-c
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
P2pConfig* config = [P2pConfig defaultConfiguration];
config.trackerZone = TrackerZoneEurope; // Set HongKong or USA if you changed zone
[P2pEngine setupWithToken:YOUR_TOKEN config:config]; // replace with your own token
return YES;
}
```
--------------------------------
### Get Browser Name
Source: https://docs.swarmcloud.net/web-hls/API
Determine the name of the current browser. Useful for compatibility checks.
```javascript
P2pEngineHls.getBrowser();
```
--------------------------------
### Get p2p information from p2pConfig
Source: https://docs.swarmcloud.net/vhs/API
Configuration object for retrieving P2P statistics and information.
```APIDOC
## Get p2p information from p2pConfig
### Description
This configuration object allows you to receive real-time statistics and information about the P2P connection.
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### `p2pConfig` Object Structure
- **getStats**: `function (totalP2PDownloaded, totalP2PUploaded, totalHTTPDownloaded, p2pDownloadSpeed)` - Callback to get downloading statistics.
- **getPeerId**: `function (peerId)` - Callback to get the peer ID.
- **getPeersInfo**: `function (peers)` - Callback to get information about connected peers.
- **onHttpDownloaded**: `function (traffic)` - Listener for HTTP downloaded traffic (in KB).
- **onP2pDownloaded**: `function (traffic, speed)` - Listener for P2P downloaded traffic (in KB) and speed (in KB/s).
- **onP2pUploaded**: `function (traffic)` - Listener for P2P uploaded traffic (in KB).
*Note: The unit of download and upload is KB. The unit of download speed is KB/s.*
### Request Example
```javascript
const p2pConfig = {
getStats: function (totalP2PDownloaded, totalP2PUploaded, totalHTTPDownloaded, p2pDownloadSpeed) {
console.log('P2P Downloaded:', totalP2PDownloaded, 'KB');
console.log('P2P Uploaded:', totalP2PUploaded, 'KB');
console.log('HTTP Downloaded:', totalHTTPDownloaded, 'KB');
console.log('P2P Download Speed:', p2pDownloadSpeed, 'KB/s');
},
getPeerId: function (peerId) {
console.log('Peer ID:', peerId);
},
getPeersInfo: function (peers) {
console.log('Peers Info:', peers);
},
onHttpDownloaded: function (traffic) {
console.log('HTTP Downloaded Traffic:', traffic, 'KB');
},
onP2pDownloaded: function (traffic, speed) {
console.log('P2P Downloaded Traffic:', traffic, 'KB', 'Speed:', speed, 'KB/s');
},
onP2pUploaded: function (traffic) {
console.log('P2P Uploaded Traffic:', traffic, 'KB');
}
};
const engine = new P2pEngineVHS(player, { p2pConfig: p2pConfig }, window.videojs);
```
### Response
None
```
--------------------------------
### P2pEngine.enableP2p
Source: https://docs.swarmcloud.net/ios/API
Enable the P2P engine at runtime. This change will take effect only when the next media file is played.
```APIDOC
## Enable P2P at Runtime
### Description
Enable the P2P engine at runtime. This change will not take effect until the next media file is played.
### Method
`enableP2p()` (Swift)
`enableP2p` (Objective-C)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```swift
P2pEngine.shared.enableP2p()
```
```objective-c
[P2pEngine.sharedInstance enableP2p];
```
### Response
#### Success Response (200)
Operation completed successfully.
```
--------------------------------
### Create HLS Proxy Instance
Source: https://docs.swarmcloud.net/web-hls/API
Initializes a new HlsProxy instance. Configuration options can be provided to override default settings for media requests and playback.
```javascript
new HlsProxy(config);
```
--------------------------------
### Get Network Configuration
Source: https://docs.swarmcloud.net/bitmovin/API
Retrieve the current network configuration settings for the Bitmovin player integration.
```javascript
engine.getNetworkConfig()
```
--------------------------------
### Get Realtime Information
Source: https://docs.swarmcloud.net/guides/api
Retrieve real-time performance metrics for a specific domain/APP or all domains/APPs for a user.
```APIDOC
## GET /user/user_id/{user_id}/domain/domain_id/{domain_id}
### Description
Get realtime information of a specific or all domain/APP.
### Method
GET
### Endpoint
/user/user_id/{user_id}/domain/domain_id/{domain_id}
### Parameters
#### Path Parameters
- **user_id** (string) - Yes - User ID
- **domain_id** (string) - Yes - Domain ID ("0" means to get the summary data of all domain/APP)
#### HTTP Header
- **MyToken** (string) - Yes - The token of user
### Response
#### Success Response (200)
- **ret** (int) - Return code
- **name** (string) - Response name
- **data** (object) - Real-time statistics
- **num_rt** (int) - Current Online Viewers
- **num_max** (int) - Peak Concurrent Viewers
- **traffic_p2p_day** (int) - P2P Traffic Today (KB)
- **traffic_http_day** (int) - HTTP Traffic Today (KB)
- **api_frequency_day** (int) - Playback Sessions Today
### Response Example
```json
{
"ret": 0,
"name": "domain",
"data": {
"num_rt": 456,
"num_max": 892,
"traffic_p2p_day": 1022794195,
"traffic_http_day": 1022794195,
"api_frequency_day": 14805
}
}
```
```
--------------------------------
### Create P2pConfig Instance (Objective-C)
Source: https://docs.swarmcloud.net/ios/API
Instantiate a P2pConfig object to manage P2P settings. Default values can be overridden.
```objective-c
P2pConfig* config = [P2pConfig defaultConfiguration];
```
--------------------------------
### Get P2PEngineShaka Version
Source: https://docs.swarmcloud.net/shaka/API
Retrieve the current version of the P2PEngineShaka library using its static version method.
```javascript
P2PEngineShaka.version
```
--------------------------------
### Get Proxied Playback URL
Source: https://docs.swarmcloud.net/media/API
Obtain a promise for a proxied playback URL using the P2PEngineMedia instance.
```javascript
engine.getProxiedUrl(originalURL)
```
--------------------------------
### Get Statistics
Source: https://docs.swarmcloud.net/guides/api
Retrieves statistical data for a specific user and domain, with options for time range and granularity.
```APIDOC
## GET /user/user_id/{user_id}/domain/domain_id/{domain_id}/statistic
### Description
Retrieves statistical data for a specific user and domain, with options for time range and granularity.
### Method
GET
### Endpoint
/user/user_id/{user_id}/domain/domain_id/{domain_id}/statistic
### Parameters
#### Path Parameters
- **user_id** (string) - Yes - User ID
- **domain_id** (string) - Yes - Domain ID("0" means to get the summary data of all domain/APP)
#### Query Parameters
- **start_ts** (int) - Yes - The start timestamp(UTC+8)
- **end_ts** (int) - Yes - The end timestamp(UTC+8)
- **gran** (int) - Yes - Must be an integer multiple of 5 minutes
### Response
#### Success Response (200)
- **max** (object) - The max value of all data
- **list** (array) - The array of all data
- **ts** (int) - Timestamp
- **value** (int) - Online viewers
#### Response Example
```json
{
"ret": 0,
"name": "statistic",
"data": {
"max": {
"ts": 1591372800,
"value": 109566
},
"list": [
{"ts":1590854400,"value":66504},
{"ts":1590940800,"value":72373},
{"ts":1591027200,"value":78300}
]
}
}
```
```
--------------------------------
### Get Domain List
Source: https://docs.swarmcloud.net/guides/api
Retrieve a list of all domains or applications associated with a user account. Supports pagination.
```APIDOC
## GET /user/user_id/{user_id}/domain
### Description
Get all domain/APP list of a user.
### Method
GET
### Endpoint
/user/user_id/{user_id}/domain
### Parameters
#### Path Parameters
- **user_id** (string) - Yes - User ID
#### Query Parameters
- **page** (int) - Yes - The specific page number
- **page_size** (int) - Yes - The specific page size
#### HTTP Header
- **MyToken** (string) - Yes - The token of user
### Response
#### Success Response (200)
- **ret** (int) - Return code
- **name** (string) - Response name
- **data** (array) - List of domains/apps
- **id** (int) - Domain/APP ID
- **domain** (string) - Domain name or AppId
- **uid** (int) - User ID
- **native** (bool) - Is native application
- **isValid** (bool) - Is domain verified
### Response Example
```json
{
"ret": 0,
"name": "domain",
"data": [
{
"id": 1,
"domain": "xxx.com",
"uid": 1,
"native": false,
"isValid": false
}
]
}
```
```
--------------------------------
### Initialize P2pEngine in Java Application
Source: https://docs.swarmcloud.net/android
Call P2pEngine.init within your Application class's onCreate method, providing your token and configuration.
```java
class MyApplication extends android.app.Application {
protected void onCreate() {
super.onCreate();
P2pConfig config = new P2pConfig.Builder()
.trackerZone(TrackerZone.Europe) // Set HongKong or USA if you changed zone
.insertTimeOffsetTag(0.0)
.build();
P2pEngine.init(this, YOUR_TOKEN, config);
}
}
```
--------------------------------
### Initialize P2pEngine in Kotlin Application
Source: https://docs.swarmcloud.net/android
Call P2pEngine.init within your Application class's onCreate method, providing your token and configuration.
```kotlin
class MyApplication : Application() {
override fun onCreate() {
super.onCreate()
val config = P2pConfig.Builder()
.trackerZone(TrackerZone.Europe) // Set HongKong or USA if you changed zone
.build()
P2pEngine.init(this, YOUR_TOKEN, config)
}
}
```
--------------------------------
### Get p2p information from p2pConfig
Source: https://docs.swarmcloud.net/theoplayer/API
Callback functions within p2pConfig to receive real-time P2P statistics and information.
```APIDOC
### Get p2p information from p2pConfig
```javascript
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: The unit of download and upload is KB. The unit of download speed is KB/s.
```
--------------------------------
### Get p2p information from p2pConfig
Source: https://docs.swarmcloud.net/media/API
Configuration object for P2PEngineMedia to receive statistics and information about P2P connections and traffic.
```APIDOC
### Get p2p information from p2pConfig
```javascript
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:** The unit of download and upload is KB. The unit of download speed is KB/s.
```
--------------------------------
### P2pEngineRxPlayer Instance Methods
Source: https://docs.swarmcloud.net/rx-player/API
Methods available on an instance of P2pEngineRxPlayer to control P2P functionality and manage resources.
```APIDOC
## P2pEngineRxPlayer Instance Methods
### `engine.enableP2P()`
#### Description
Resumes P2P functionality if it has been previously disabled.
### `engine.disableP2P()`
#### Description
Disables the P2P engine, stopping all P2P activities and freeing up associated resources.
### `engine.destroy()`
#### Description
Stops the P2P engine and releases all resources used by the instance. This should be called when the player is no longer needed.
```
--------------------------------
### Get Statistics for One Worker
Source: https://docs.swarmcloud.net/guides/super-peer
Retrieves real-time statistics for a specific worker identified by its process ID (pid).
```APIDOC
## GET /stats/:pid
### Description
Retrieves real-time statistics for a specific worker using its process ID.
### Method
GET
### Endpoint
/stats/:pid
### Parameters
#### Path Parameters
- **pid** (string) - Required - The process ID of the worker.
```
--------------------------------
### Initialize P2PEngineShaka Instance
Source: https://docs.swarmcloud.net/shaka/API
Create a new P2PEngineShaka instance, passing the Shaka Player instance and an optional configuration object. The configuration allows overriding default P2P settings.
```javascript
var engine = new P2PEngineShaka(player, {p2pConfig: [opts]}, shaka = window.shaka);
```