Theta P2P Javascript SDK

Here are instructions for integrating Theta P2P with any HLS.js compatible video player. Below examples are using video.js and hls.js as a video player solution, and can serve as a guide for integrating into custom players.

To integrate Theta into your video.js powered player, simply include the theta scripts and setup the options for your video.js player as shown below. You can also check here for a full integration example.

1. Include scripts

Enter the following script tags in your head tag. Ensure HLS.js is included before the theta-hls-plugin.

<script src='https://vjs.zencdn.net/7.15.4/video.js'></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
<script src="https://d1ktbyo67sh8fw.cloudfront.net/js/theta.umd.min.js"></script>
<script src="https://d1ktbyo67sh8fw.cloudfront.net/js/theta-hls-plugin.umd.min.js"></script>
<script src="https://d1ktbyo67sh8fw.cloudfront.net/js/videojs-theta-plugin.min.js"></script>

2. Setup video.js options

<body>
   play video boii {{.}}
   <video id="my-player" controls></video>
</body>

<script>
  const optionalHlsOpts = null;
  const optionalThetaOpts = {
    allowRangeRequests: true, // false if cdn does not support range headers  
  };
  const player = window.player = videojs('my-player', {
          techOrder: ["theta_hlsjs", "html5"],
          sources: [{
            src: "YOUR_VIDEO_URL",
            type: "application/vnd.apple.mpegurl",
            label: "1080p"
          }],
          theta_hlsjs: {
              videoId: "YOUR_INTERNAL_VIDEO_ID",
              userId: "YOUR_AUTHED_USER_ID (optional)", 
              onThetaReady: null, // optional listener
              onStreamReady: null, // optional listener
              hlsOpts: optionalHlsOpts,
              thetaOpts: optionalThetaOpts,
          }
      });
</script>

All set! Now your web clients should start to peer with each other and share video streams to offload the CDN bandwidth. For more controls for the Theta lib, e.g. turning off the p2p feature, please refer to the 4. Additional Controls section.

3. Theta Blockchain Micro-Payment Integration (Optional)

TFuel reward pool creation

First a TFuel reward pool needs to be created for your application. Please contact Theta Labs support to create the reward pool wallet. After the wallet is created, you would need to seed it with a sufficient amount of TFuel for your users.

Theta wallet token generator

To allow authenticated users to earn TFUEL from the reward pool, your backend needs to generate a Theta Wallet access token. Please implement a function which will call your backend to generate a new access token for the user's Theta Wallet.

async function getWalletAccessToken() {
    //Check if a user is logged in...
    let isAuthenticated = true;

    if (!isAuthenticated) {
        //No user is logged in, no wallet will be used
        return null;
    }

    //This API should check the user's auth 
    let body = await yourAPIRequestToGenerateThetaWalletAccessTokenForAuthedUser();

    //Return the access token from the request body
    return body.access_token;
}

Your backend may generate a new access token for an authenticated user's Theta Wallet using the following code:

const jwt = require('jsonwebtoken');

const algorithm = { algorithm: "HS256" };

const partnerApiKey = '';
const partnerApiSecret = '';

api.genAccessToken = function(userId) {
    let expiration = new Date().getTime() / 1000;
    expiration += 120;

    let payload = {
        api_key: partnerApiKey,
        user_id: userId, // this is the user id of your own user in your backend
        exp: expiration
    };

    return jwt.sign(payload, partnerApiSecret, algorithm);
};

The above code snippet requires partnerApiKey and partnerApiSecret. You can obtain those from the ThetaVideoAPI dashboard by clicking the "Generate Partner API Key" button on the "App -> Settings" tab.

Setup video.js options

In the video.js options, add the walletUrl and onWalletAccessToken attributes as shown below to configure the TFUEL wallet for the user.

<script>
  const optionalHlsOpts = null;
  const optionalThetaOpts = {
    allowRangeRequests: true, // false if cdn does not support range headers  
  };
  const player = window.player = videojs('my-player', {
          techOrder: ["theta_hlsjs", "html5"],
          sources: [{
            src: "YOUR_VIDEO_URL",
            type: "application/vnd.apple.mpegurl",
            label: "1080p"
          }],
          theta_hlsjs: {
              videoId: "YOUR_INTERNAL_VIDEO_ID",
              userId: "YOUR_AUTHED_USER_ID (optional)", 
              walletUrl: "wss://api-wallet-service.thetatoken.org/theta/ws",
              onWalletAccessToken: getWalletAccessToken,
              onThetaReady: null, // optional listener
              onStreamReady: null, // optional listener
              hlsOpts: optionalHlsOpts,
              thetaOpts: optionalThetaOpts,
          }
      });
</script>

4. Additional Controls (Optional)

Toggle CDN Only

Sometimes you want to only allow CDN (user pref, etc). This code will enable or disable CDN only mode.

player.tech_.trigger('toggleUseCDN');

Did this page help you?