Purushottam, Author at VdoCipher Blog https://www.vdocipher.com/blog/author/purushottam/ Secure Video Streaming Tue, 09 Jul 2024 14:28:59 +0000 en-US hourly 1 https://wordpress.org/?v=6.4.5 https://www.vdocipher.com/blog/wp-content/uploads/2016/11/cropped-VdoCipher-logo2-32x32.png Purushottam, Author at VdoCipher Blog https://www.vdocipher.com/blog/author/purushottam/ 32 32 How To Implement Shaka Player For DRM playback https://www.vdocipher.com/blog/shaka-player Mon, 25 Dec 2023 07:50:11 +0000 https://www.vdocipher.com/blog/?p=8387 If you are looking to stream your content along with DRM, chances are that you’re bound to come across Shaka player. As an open-source JS library, the Shaka player is widely used for adaptive video streaming. You can play content based on DASH and HLS, without browser plugins, with the help of an Encrypted media […]

The post How To Implement Shaka Player For DRM playback appeared first on VdoCipher Blog.

]]>
If you are looking to stream your content along with DRM, chances are that you’re bound to come across Shaka player. As an open-source JS library, the Shaka player is widely used for adaptive video streaming. You can play content based on DASH and HLS, without browser plugins, with the help of an Encrypted media extension. So, in order to help others out and make it easier for others to learn about using Shaka player for DRM playback, I wrote this article.

So, without further ado, let’s get started.

What is Encrypted Media Extension (EME)

DRM playback is based on the Encrypted Media Extension Technology, which is the standard of W3C to provide DRM playback support in web browsers.

EME can be majorly divided into two parts:

EME API:

These APIs are the part of the browser API as the standard of W3C to securely communicate between the Video Element and CDM (Content Decryption Module) where actual decoding of media happens

Content Decryption Module:

CDM is a proprietary software/hardware of DRM service provider that can be bundled in the browser/OS or added as hardware in the client machine, it’s the main purpose is to decode the video in a secure executing environment without exposing it to the user and rendering media directly on the video element.

Here’s a brief block diagram of EME Tech in Vdophiper Player and Playback.

Shaka player implementation for DRM

Both DRM service providers, Apple Fairplay DRM and Google Widevine DRM provide CDM in Safari and Chrome browsers respectively.

For video playback, Apple expects developers to consume EME API and provide playback on the video element, but google Widevine goes one step ahead and also provides JS video Player name Shaka Player that provides full basic playback using EME API and Video Element.

About Vdocipher Player:

Vdocipher Player is a plug-n -play video player, that expects the VideoID and OTP and handles everything under the hood, like choosing the DRM service based on the user device and provide basic playback,

Also, this player is loaded with tons of features like playlist, video analytics, captions and many more.

VdoCipher empowers course creators, event organizers and broadcasters with expert live video streaming, ensuring smooth playback globally.

What is Shaka Player?

Shaka Player is an open-source js video player mainly used for DRM service maintained by google. Under the hood for DRM service, it actuals bind the Video Element and Widevine CDM by consuming the EME API

Features: 

  • Supports the Adaptive Bitrate Streaming, which means the quality of media adapts to the bandwidth of the user.
  • Can also support offline storage and playback using IndexDB
  • Also, provide option UI Lib for player
  • Easy integration with Chromecast and also supports the Apple Fairplay.
  • Open-source

Steps to implement Shaka Player for Widevine

  • Setup the basic video player
  • Add the DRM configuration
  • Handle License Server Authentication & delivers licenses

Setup The Basic video player

In this setup, we will add the video without DRM using shaka player lib.

<html>
<head>
<!-- Shaka Player compiled library: -->
<script src="dist/shaka-player.compiled.js"></script>
</head>
<body>
<video
id="video"
width="640"
poster="example.com/poster.jpg"
controls
autoplay
></video>
</body>
<script>
// Video Manifest URL
const manifestUri =
"https://storage.googleapis.com/shaka-demo-assets/angel-one/dash.mpd";

// Install all the required Polyfill
shaka.polyfill.installAll();
if (shaka.Player.isBrowserSupported()){
throw new Error("Browser not supported !")
};
const video = document.getElementById("video");
//Shaka Player Reference provides all methods and properties.
const player = new shaka.Player(video);
player.addEventListener("error", onErrorEvent);
player
.load(manifestUri)
.then(() => console.log("Video Load successful"))
.catch((error) =>
console.error("Error code", error.code, "object", error)
);
</script>
</html>

 

Add the DRM configuration.

For DRM playback we need to add the DRM configuration to the player instance we created above ( in between the script tags )

player.configure({
DRM: {
servers: {
'com.widevine.alpha': 'https://YOUR.AUTHENTICATION.SERVER',
}
}
})

Shaka player will request https://your.authentication.server/,to get the License Certificate, 
Shaka Player is a key-system-agnostic, it uses EME to ask the browser what its key-system is supported, and make no assumptions. If your browser supports multiple key systems, the first supported key system in the manifest is used

Handling License Server Authentication

Your application’s license server may require some form of authentication so that it only delivers licenses to paying users, 

but for that you need to add header/token/parameter with each request to identify the user, you can do so by interrupting the request for  License Certificate, and send them the License Certificate only if it passed the authorization criteria. 

To interrupt the License Certificate request we will use the `getNetworkEngine` Method

player
.getNetworkingEngine()
.registerRequestFilter(function (type, request) {
// Only add headers to license requests:
if (type == shaka.net.NetworkingEngine.RequestType.LICENSE) {
// This is the specific header name and value the server wants:
request.headers["user-identify-token"] = "VGhpc0lzQVRlc3QK";
}
});

In the above, we add the parameter in the request header, although there are two more options like Cookie Authentication, Parameter Authentication. To identify the right user on License Server.

Steps to implement Shaka Player for FairPlay

Shaka players also support Apple FairPlay DRM, Implementing the FairPlay the follow same above three-step paradigm as implementing the Widevine.

First step remains the same in both, it just the DRM configuration and handling the request changes while implementing the FairPlay

player.configure({
DRM: {
servers: {
"com.apple.fps.1_0": licenseUri,
},
advanced: {
"com.apple.fps.1_0": {
serverCertificate: fairplayCert,
},
},
initDataTransform: function (initData) {
const skdUri = shaka.util.StringUtils.fromBytesAutoDetect(initData);
console.log("skdUri : " + skdUri);
const contentId = skdUri.substring(skdUri.indexOf("skd://") + 6);
console.log("contentId : ", contentId);
const cert = player.drmInfo().serverCertificate;
return shaka.util.FairPlayUtils.initDataTransform(
initData,
contentId,
cert
);
},
},
});

player.getNetworkingEngine().registerRequestFilter(function (type, request) {
if (type == shaka.net.NetworkingEngine.RequestType.LICENSE) {
const originalPayload = new Uint8Array(request.body);
const base64Payload = shaka.util.Uint8ArrayUtils.toBase64(originalPayload);
const params = "spc=" + encodeURIComponent(base64Payload);

request.body = shaka.util.StringUtils.toUTF8(params);
request.headers["user-identify-token"] = authToken; // Token to identify the user.
}
});

player.getNetworkingEngine().registerResponseFilter(function (type, response) {
// Alias some utilities provided by the library.
if (type == shaka.net.NetworkingEngine.RequestType.LICENSE) {
const responseText = shaka.util.StringUtils.fromUTF8(response.data).trim();
response.data = shaka.util.Uint8ArrayUtils.fromBase64(responseText).buffer;
parsingResponse(response);
}
});

Shaka Player UI

Shaka player also ships the UI controls for the video element, to implement UI, use the shaka-player.ui.js build and add the attribute of data-shaka-player-container of parent div of the video element. It will add the controls in that div.

<div data-shaka-player-container>
<video autoplay data-shaka-player id="video"></video>
</div>

And to access the Player instance and Controls instance 

const video = document.getElementById("video");
const ui = video["ui"];
const controls = ui.getControls();
const player = controls.getPlayer();
player.addEventListener("error", console.error);
controls.addEventListener("error", console.error);

To configure the UI of Player we can use   UI. configure(configure)  method.

const config = {
addSeekBar: false,
controlPanelElements: ["rewind", "fast_forward"],
seekBarColors: {
base: "rgba(255, 255, 255, 0.3)",
buffered: "rgba(255, 255, 255, 0.54)",
played: "rgb(255, 255, 255)",
},
};
ui.configure(config);

Offline Storage and Playback

Shaka player also provides the offline playback of video with DRM solution, it uses the index DB to store the video and Service worker to map the license request.

Conclusion

I hope this article helped you on how to ensure Shaka Player implementation for DRM playback. In this article, I’ve gone through what Shaka player and EME are. Also, how you can set up the player, add DRM configuration, and more.

At Vdocipher, we implement Shaka player for DRM playback on our own. When you use our platform, you won’t have to worry about implementing Shaka player or DRM. We take care of all of it, all you have to do is simply upload your video to our platform and embed it on your website.

The post How To Implement Shaka Player For DRM playback appeared first on VdoCipher Blog.

]]>
MPEG DASH Player: Everything You Need To Know https://www.vdocipher.com/blog/dash-player Fri, 14 Jan 2022 10:37:49 +0000 https://www.vdocipher.com/blog/?p=9577 Table of Contents: What is Dash Playback? Is Dash playback secure for video? Vdocipher provides Dash + Secure Video playback Other Dash Player without secure video playback How to build the Dash player Before we continue we need to understand what is Dash Playback? We already have covered a detailed blog for the “MPEG-DASH: Dynamic […]

The post MPEG DASH Player: Everything You Need To Know appeared first on VdoCipher Blog.

]]>

Before we continue we need to understand what is Dash Playback?

We already have covered a detailed blog for the “MPEG-DASH: Dynamic Adaptive Streaming Over HTTP Explained” so here we just gonna brush up on the core part of Dash Playback Tech

DASH stand for Dynamic Adaptive Streaming over HTTP, as the name suggests it’s it has the “Dynamic” bit rate and is “adaptive” to Network performance, that is it changes the bit rate according to network to keep the video playing. Higher the video bitrate higher the video quality.

Working of Dash Playback contains majorly three steps

  • Segmentation & Encoding

In this step video is divided into many segments of fewer seconds and index file to keep the track of all the segmentation is created, this index file is also known as the manifest file.

Segments are encoded in various encoding and video quality levels for smaller to bigger files size and the manifest file is updated. Dash Support any encoding standards

  • Delivery

When the video starts streaming, the device first fetches the index file (manifest file) and then it fetches the proper segment of video one by one from the server using HTTP/HTTPS  by accounting for the network performance.

  • Decoding and Playback

Device on receiving the segments decoded each segment and provide the data to the player for video playback.

If during the playback the network performance changes then the player also changes the segment request of high/low quality depending on the network performance. This makes the video playback adaptive to network performance.

Is Dash playback secure for video?

Dash playback is not secure by default, it’s just a technology for adaptive media playback, it does not contain any encryption standards to secure your video, what secure the video is the DRM services. If you want to learn more about the DRM we already have a blog for this “What is DRM Technology, its Working & Video Content Protection Types”

Vdocipher provides Dash + Secure Video playback

When dash playback is added with DRM solution it not only provides reliable video playback irrespective of network performance but also the secure video playback.

But here’s a catch you won’t be able to serve all your customer with just Dash cause Dash is not majorly supported by the Apple device. For the apple device, you have another playback technology like Dash called HLS and then you have to choose the DRM service that serves the Apple device, 

So we at vdocipher player provide the complete package in Plug and play, which handles all complexity of secure video playback 

List Other Dash Player without secure video playback?

  • Dash.js

Dash.js is an open-source HTML5 Video player based on MPEG_DASH and built by the own dash industry forum to demonstrate a production-ready framework for Dash Playback.

It is based on the Media Source Extension API by w3c and provides a simple user interface with tons of information to debug the video stream for error. 

Sample code for using Dash.js :

<!doctype html>
<html>
    <head>
        <title>Dash.js Rocks</title>
        <style>
            video {
                width: 640px;
                height: 360px;
            }
        </style>
    </head>
    <body>
        <div>
            <video data-dashjs-player autoplay src="https://dash.akamaized.net/envivio/EnvivioDash3/manifest.mpd" controls>
            </video>
        </div>
        <script src="yourPathToDash/dash.all.min.js"></script>
    </body>
</html>
  • Exoplayer:

Exoplayer video player on application level for android, it  is alternative to Android’s MediaPlayer API for providing better features and customization, it has feature like persistent caching and custom rendered.

Android’s MediaPlayer API is fixed to the android version of the device, whereas Exoplayer can be updated via playstore application update

We’ve also written a blog on how to stream videos on iOS using AVPlayer, do check it out to know more about video streaming in iOS.

How to build the Dash player

Dash player functionality is to fetch the manifest file, parse it and play all segments one by one.

It can be processed in 7 steps: 

  • Get the video element reference
  • Create media source
  • Create ObjectURL from the media source and add to source of video
  • Set the mime type for media source via addSourceBuffer
  • Fetch the manifest file and parse and store all required data in variable
  • Initialize the video with first segment
  • Use event `timeupdate` to continuously update the source with all other segments
// Create media source
const videoEl = document.getElementById("my-video");
const mediaSource = new MediaSource();
const sourceUrl = URL.createObjectURL(mediaSource);
videoEl.src = sourceUrl;
let videoSource;
let segCheck;
let currentSegmentIndex = 0;
let lastTime;

// get mainfest file
const xmlData = await fetch("MANIFEST_URL_FROM_SERVER")
  .then((r) => r.text())
  .then((xml) => parser.parseFromString(xml, "text/xml", 0));

// extract data from manifest file
const file = xmlData.querySelectorAll("BaseURL")[0].textContent.toString();
const rep = xmlData.querySelectorAll("Representation");
const type = rep[0].getAttribute("mimeType");
const codecs = rep[0].getAttribute("codecs");
const width = rep[0].getAttribute("width");
const height = rep[0].getAttribute("height");
const bandwidth = rep[0].getAttribute("bandwidth");
const ini = xmlData.querySelectorAll("Initialization");
const initialization = ini[0].getAttribute("range");
const segments = xmlData.querySelectorAll("SegmentURL");
const segList = xmlData.querySelectorAll("SegmentList");
let segDuration = segList[0].getAttribute("duration");

// wait for media source to ready
mediaSource.addEventListener(
  "sourceopen",
  function (e) {
    try {
      videoSource = mediaSource.addSourceBuffer("video/mp4");
      initVideo(initialization, file);
    } catch (e) {
      log("Exception calling addSourceBuffer for video", e);
      return;
    }
  },
  false
);

// init the video with first segment
async function initVideo(range, url) {
  const segmentVideoBuffer = await fetch(url, {
    header: `Range: "bytes=${range}"`,
  });
  B.appendBuffer(new Uint8Array(segmentVideoBuffer));
  videoEl.addEventListener("timeupdate", playSegment);
}

// play all segment one by one if necessary
function playSegment() {
  if (index < segments.length && videoEl.currentTime - lastTime >= segCheck) {
    const range = segments[index].getAttribute("mediaRange").toString();
    segCheck = (timeToDownload(range) * 0.8).toFixed(3);
    const segmentVideoBuffer = await fetch(url, {
      header: `Range: "bytes=${range}"`,
    });
    videoSource.appendBuffer(new Uint8Array(segmentVideoBuffer));
    segCheck = (timeToDownload(range) * 0.8).toFixed(3);
    lastTime = videoElement.currentTime;
  }
}

// Helper
function timeToDownload(range) {
  const [start, end] = range.split("-");
  return ((end - start) * 8) / bandwidth;
}

The post MPEG DASH Player: Everything You Need To Know appeared first on VdoCipher Blog.

]]>