Embedding the WebTvPlayer (v2)

Welcome! This documentation will guide you to embedding the WebTvPlayer in your website.

Features

The WebTvPlayer provides the same functionalities you would expect from any other video player.

Skins

The WebTvPlayer offers different skins which can be selected with a specific configuration option. You can build your own skin from scratch as explained in the custom skins section.

See how the player looks with the skin

Table of contents

  1. Getting started
  2. Configuration options
  3. Secure playback
  4. Tracking progress
  5. Properties
  6. Methods
  7. Events
  8. Custom skins (classic JS)
  9. Custom skins (ES6+)
  10. Samples
  11. Playground

Getting started

First, you'll need a free API Key from the Halleymedia staff, so contact us at dev@halleymedia.com.

After you got your API Key, initializing the WebTvPlayer user interface in your website is super easy. We provide two different initialization options to suit your needs.

Initialization option #1: using the JavaScript SDK

By using our JavaScript SDK, you can inject the WebTvPlayer user interface right into a container element, such as a div located in your HTML page. The container element can be sized to your liking, since the WebTvPlayer has a responsive layout. However, if the element has no defined height, the WebTvPlayer will adjust it as necessary.

Add this initialization code right before the closing of the body tag. The container element can be placed anywhere on your page.

<div id="player-container" style="width: 640px; height: 360px;"></div>
<script src="https://embed.civicam.it/v2/webtvplayer.js?apiKey=YOUR_API_KEY"></script>
<script>
  var playerContainer = document.getElementById("player-container");
  var videoId = 1;
  var webTvPlayer = new WebTvPlayer(playerContainer, videoId);
</script>

Or, if you're using jQuery, you might prefer a more concise syntax.

<div id="player-container" style="width: 640px; height: 360px;"></div>
<script src="https://embed.civicam.it/v2/webtvplayer.js?apiKey=YOUR_API_KEY"></script>
<script>
var videoId = 1;
var webTvPlayer = $("#player-container").webTvPlayer(videoId);
</script>

In both these examples, an object of type WebTvPlayer is returned. Subscribe to the ready event and then you'll be able interact with its public API that's documented in the properties and methods sections. Here's an example.

webTvPlayer.on('ready', function() {
    //Here it's safe to use the WebTvPlayer public API, e.g.:
    this.speed = 1.5;
    this.volume = 0.8;
});

Initialization option #2: using an iframe tag

This option is expecially needed when executing JavaScript is not allowed for some reason. Just add this iframe element anywhere in the page. Set a proper width and height for the iframe tag.

<iframe src="https://embed.civicam.it/v2/webtvplayer.html?apiKey=YOUR_API_KEY&videoId=videoId" style="width: 640px; height: 360px; border: 0"></iframe>

What to do next?

The WebTvPlayer provides plenty of customization for both initialization options. Jump to the configuration and samples sections for more in-depth customization examples.

If you want to protect your video content from anonymous access, read how to properly initialize the WebTvPlayer in the secure playback section.

Configuration options

When initializing the WebTvPlayer you can provide some configuration options to control its final appearance.

If using the JavaScript SDK, provide a configuration object as an additional argument to the initialization method, like in this sample.

<script>
var playerOptions = {
    skin: null,
    segment: 4.0
};
//Using the global function
var webTvPlayer1 = new WebTvPlayer(playerContainer1, videoIdOrJwt, playerOptions);
//Or, using jQuery
var webTvPlayer2 = $(selector).webTvPlayer(videoIdOrJwt, playerOptions);
</script>

Instead, if you're using the iframe, you can pass configuration options as query string parameters.

<iframe src="https://embed.civicam.it/v2/webtvplayer.html?apiKey=YOUR_API_KEY&videoId=videoId&skin=skinName&segment=4.0" style="width: 640px; height: 360px; border: 0"></iframe>

All available options are listed in the following paragraph.

Option list

Option name Description Default
skin:string|Function Name or constructor function of the UI skin to use. Set to null for a chromeless player. 'WebTvPlayerDefaultSkin'
segment:number Duration of a segment of a video, expressed in seconds. Has a minimum value of 0.5.
When a segment has been completely watched, the progress event is raised.
5.0
from:number Display a time-clipped version of the original video starting from this position, expressed in seconds. null
to:number Display a time-clipped version of the original video ending with this position, expressed in seconds. null
metadata:Array A collection of video-related metadata that must be fetched.
The array can contain any combination of these string values: video, speakers, markers, transcription, notices.
See the properties and events sections to learn how to get these metadata values once they've been fetched.
['video', 'speakers', 'markers', 'notices']
apiUrl:String Base URL of the Civicam REST API. Set to "https://api.civicam.it/test/v1/" if you want to use the player in the test environment. null

Secure playback

If you want to protect content that's only available to paying users, then you need to prevent anonymous access. The WebTvPlayer won't play protected videos if you just provide their ID: instead, you should provide a signed JSON Web Token (JWT) like in the following example:

var jwt = "eyJhbGciOiJIUzI1..."; //JSON Web Token, generated server-side
var webTvPlayer = $("#player-container").webTvPlayer(jwt);

You should generate a JWT with a payload containing the following claims:

Here's an example of a valid payload.

{
  "iss": "https://example.org",
  "sub": "1",
  "exp": 1516239022,
  "name": "3415"
}

You should then sign this payload on the server-side of your application using the HS256 algorithm. The secret key used to sign the payload must be shared with the Halleymedia staff. Contact us via e-mail at dev@halleymedia.com.

The WebTvPlayer will then securely load the video by using Pre-Signed Cookies with the provided expiration, thus granting access for a limited time and exclusively from the IP address of the user. This security mechanism severly discourages any attempt of unauthorized access by malicious users.

Tracking progress

Tracking individual segments

If you're using the JavaScript SDK, then you can track a user's progress on the current video. Just subscribe to the progress event to be notified each time the user has watched a short segment of the video.

webTvPlayer.on('progress', function(index, start, end, percentage) {
    console.log("The user has watched the segment with index " + index + " starting at " + start + "s and ending at " + end + "s. He watched " + Math.round(percentage) + "% of the video.");
    //TODO: send an ajax request to your backend in order to save the user progress, or just push an event to Google Tag Manager dataLayer.
});

Each segment has a default duration of 5 seconds, so the progress event will trigger every 5 seconds. You can change the segment duration by providing a segment property in the configuration options. Here's a comple example.

<div id="player-container" style="width: 640px; height: 360px;"></div>
<script>
var videoId = 1;
var playerOptions = {
    segment: 1.0 //Each segment will have a duration of 1 second
};
var playerContainer = document.getElementById("player-container");
var webTvPlayer = new WebTvPlayer(playerContainer, videoId, playerOptions);
webTvPlayer.on('progress', function(index, start, end) {
    //This will now trigger every second, as long as the video is playing
    console.log("The user has watched the segment with index " + index + " starting at " + start + "s and ending at " + end + "s.");
});

Tracking percentage

If you're just interested in tracking a percentage value, you could subscribe the percentage event instead which will fire only for interger values.

webTvPlayer.on('percentage', function(percentage) {
    console.log("The user has watched " + percentage + "% of the video."); //percentage being an integer value
    //TODO: send an ajax request to your backend in order to save the user progress, or just push an event to Google Tag Manager dataLayer.
});

Tracking with Google Tag Manager

If you wish to use a purely unobtrusive tracking solution, you can rely on Google Tag Manager instead of subscribing the progress or percentage events in the page.

Create a new Custom JavaScript Variable and write code which will do the following:

We prepared a ready-made recipe you can import into your Google Tag Manager Container. All pushed events will be relayed to Google Analytics so just be sure to amend the Google Analytics Settings Variable with your Account ID.

Download the recipe Download just the code

Properties

When a WebTvPlayer is initialized with the JavaScript API, an object of type WebTvPlayer is returned. Here's a list of its public properties.

Player-related properties

These properties can be used after the ready event has occurred.

Property name Description Accessors
id:string Returns the currently selected video id or JWT. Read only
options:Object Returns the flattened configuration options. Read only
container:HTMLElement Returns a reference to the container element of the current WebTvPlayer. Read only
status:string Returns the current status of the player.
Note: Possible values are: ready, loading, buffering, playing, paused, stopped or error.
Read only
segments:number Returns the number of total segments in this video.
Each one has a duration of segment seconds, except the last one which might be shorter.
Read only
qualities:Array Returns the available quality levels for this video. Each object has a label, bitrate, width and height properties. Read only
quality:number Returns or sets the index of the current quality level.
Note: use the index of the array returned by the qualities property. The index 0 is always the 'Auto' quality.
Read, Write
resolution:Object Returns the currently selected video resolution. The object has a width and height property.
Note: you could also use the quality and qualities properties for more details about the currently selected quality level.
Read only
metadata:Object Returns the currently loaded metadata.
Only the metadata set via the metadata configuration option will be fetched.
Read only
speed:number Returns or sets the current playback speed.
Note: set a value in the range 0.5 (inclusive) to 4.0 (inclusive) with increments of 0.25.
Read, Write
volume:number Returns or sets the current volume.
Note: set a value in the range from 0.0 (mute) to 1.0 (maximum volume).
Read, Write
mute:boolean Returns or sets whether the video is muted or not. Read, Write
fullscreen:boolean Returns or sets whether the video is displayed in fullscreen or not. Read, Write

Video-related properties

These properties can be used after the load event has occurred.

Property name Description Accessors
live:number Returns where the current video is live streaming (true) or on-demand (false). Read only
duration:number Returns the total duration of the video, expressed in seconds. Read only
position:number Returns or sets the actual position in the video, expressed in seconds. Read, Write

Constructor properties

These areproperties that are available right away on the WebTvPlayer constructor function.

Property name Description Accessors
instances:Array A list of the currently active instances of WebTvPlayer. Read only
version:string Version of WebTvPlayer. Read only

Methods

When a WebTvPlayer is initialized with the JavaScript API, an object of type WebTvPlayer is returned. Here's a list of its public methods.

Player-related methods

These methods can be used after the ready event has occurred.

Method name Description
load(videoIdOrJwt:string[, from:number[, to:number]]):void Unloads the currently loaded video (if any) and starts loading a new one with the provided video ID or JWT.
The from and to parameters are optional. You should provide them only if you want to display a time-clipped version of the original video.
on(eventName:string, callback:function):void Subscribes to an event by providing the event name and a callback
See the events section for details.
off(eventName:string[, callback:function]):void Removes a previously subscribed callback to an event by providing the event name and the callback itself.
Note: The callback argument is optional. If it's not provided, all subscribed callbacks are removed for that event name.
update():void Forces the update of the UI. You might need to call this method after the container size is changed.
destroy():void Removes all resources created by the WebTvPlayer, including HTML elements from the container.

Video-related methods

These methods can be used after the load event has occurred.

Method name Description
play():void Plays the currently loaded video.
pause():void Pauses the currently loaded video.
stop():void Stops the currently loaded video, resetting its position to zero.

Events

The WebTvPlayer object can raise a few events. Subscribe them by name, using the on method.

webTvPlayer.on('volume', function(arg) { 
    //Your code here
    console.log("New volume value", arg.volume);
});

Or by the event-specific method:

webTvPlayer.onVolume(function(arg) {
    //Your code here
    console.log("New volume value", arg.volume);
});

Conversely, you can stop being notified by invoking the off method. The callback argument is optional: if it's not provided, all registered callbacks are removed for that event name.
Note: if you just pass the special event name all, then any previously registered callback is removed (it doesn't matter what the event name was).

webTvPlayer.off('buffer', myCallback); //Remove just this callback (if it was registered before for the buffer event)
webTvPlayer.off('volume'); //Remove all callbacks previously registered for the volume event
webTvPlayer.off('all'); //Remove any previously registered callback

Each event might provide an object parameter when invoking your callback which defines ore or more properties. Referer to the following paragraph for the specifics.

Instance events

Event name Description Callback arguments
ready The WebTvPlayer intialization has completed and it's ready to load a video. None
loading Loading of a video just started. Methods play(), pause() and other video-related methods and properties are not available during this phase. None
load A video has been loaded, its duration has been determined and it's going to be played. After this event has occurred, it's safe to use the video-related metods and properties. None
error The load or playback of the current video raised an error. An object containing the following properties:
  • reason: string the error text
buffer The buffer has changed. An object containing the following properties:
  • empty: boolean
    whether the buffer is empty or not. If true, the buffer is empty and the player was forced to stop playing the video and wait for more data to be available. If false, the buffer is not empty and the video is playing just fine.
  • bufferedPercentage: number the buffered percentage of the total duration.
play The user has requested the playback of the video either from the start or from an arbitrary position. None
pause The user has paused the video. None
stop The user has stopped the video. None
end The video stopped because it reached the end. None
mute The user has muted or unmuted the video. An object containing the following properties:
  • mute: boolean
    whether the user has muted the video (true) or unmuted it (false).
volume The user has changed the volume. An object containing the following properties:
  • volume: number
    the new volume level, a value between 0.0 (mute) and 1.0 (max volume).
qualities The quality levels for this video have been determined. An object containing the following properties:
  • qualities: Array<{label: string, bitrate: number, width: number, height: number}>
    the collection of quality levels supported by the current video.
quality The user has changed the quality level. An object containing the following properties:
  • qualityIndex: number
    the index of the selected quality level.
speed The user has changed the playback speed. An object containing the following properties:
  • speed: number
    the current playback rate.
progress The user has watched a segment of the video. An object containing the following properties:
  • segmentIndex: number
    the zero-based index of the segment watched;
  • startOffset: number
    the start offset of the segment, expressed in seconds;
  • endOffset: number
    the end offset of the segment, expressed in seconds;
  • watchedPercentage: number
    the percentage watched so far.
percentage The user has watched a certain percentage of the video. Guaranteed to report exactly once each 1% increment. An object containing the following properties:
  • watchedPercentage: number
    the watched percentage, always an integer value ranging from 1 to 100. Each percentage value will only trigger once.
position Position of the video has been updated. An object containing the following properties:
  • position: number
    the current position in seconds;
  • percentage: number
    the current position in percentage (it depends on total duration).
fullscreen The user has entered or exited fullscreen mode. An object containing the following properties:
  • enteredFullscreen: boolean
    whether the user has entered fullscreen mode (true) or exited it (false).
metadata All requested metadata has been fetched. An object containing the following properties:
  • video: Object|undefined
    the fetched video metadata, see the the metadata.video event below for the actual shape of the object.
  • transcription: Array|undefined
    the fetched transcription array, see the the metadata.transcription event below for the actual shape of the objects in this array.
  • markers: Array|undefined
    the fetched markers array, see the the metadata.markers event below for the actual shape of the objects in this array.
  • speakers: Array|undefined
    the fetched speakers array, see the the metadata.speakers event below for the actual shape of the objects in this array.
  • notices: Array|undefined
    the fetched notices array, see the the metadata.notices event below for the actual shape of the objects in this array.
metadata.video Video metadata has been fecthed. An object containing the following properties:
  • video: Array<{id: string, title: string, description: string|undefined, agenda: Array<string>, start: Date|undefined, end: Date|undefined}>
    the fetched metadata object. start and end are UTC dates.
metadata.transcription Transcription metadata has been fecthed. An object containing the following properties:
  • transcription: Array<{id: string, text: string, offset: number, duration: number}>
    the fetched metadata object. offset and duration are expressed as seconds.
metadata.markers Markers metadata has been fecthed. An object containing the following properties:
  • markers: Array<{id: string, type: string, offset: number, ordinal: number, title: string, subtitle: string|undefined, image: string|undefined}|{id: string, offset: number, title: string, subtitle: string|undefined, image: string|undefined, speaker: {id: string, name: string, role: string|undefined, image: string|undefined}|undefined}>
    the fetched metadata object. Offsets are expressed in seconds.
metadata.speakers Speakers metadata has been fecthed. An object containing the following properties:
  • speakers: Array<{id: string, name: string, role: string|undefined, image: string|undefined}>
    the fetched metadata object.
metadata.notices Notices metadata has been fetched. An object containing the following properties:
  • notices: Array<{id: string, name: string, image: string}>
    the fetched metadata object.
resize The WebTvPlayer container has changed size. An object containing the following properties:
  • resolution: {width: number, height: number}
    the new resolution in pixels.
destroy The WebTvPlayer instance is going to be destroyed: the video will stop playing and the container element is going to be emptied. None
all This is a special event which will be raised each time any of the other events is raised. A string representing the event name;
An object containing the event payload. See the other events to know the actual shape of the object.

DOM Events

Event name Description Callback arguments
WebTvPlayer.Create A new instance of WebTvPlayer has been created. Object: the event, containing a detail property which will give you the newly created instance of WebTvPlayer.

Custom skins (ES6+)

You can create skins using ES6 syntax. In this case, you should add the type definitions package to your project to assist you in the development.

npm install @halleymedia/webtvplayer-types
Then, create a JavaScript module like this one:
import WebTvPlayer from '@halleymedia/webtvplayer-types';
import WebTvPlayerSkin from '@halleymedia/webtvplayer-types/skins/WebTvPlayerSkin';

/**
 * @implements {WebTvPlayerSkin}
 */
export default class MySkin {

    /**
     * @param {WebTvPlayer} playerInstance
     * @param {Object.} callbackFunction
     */
    render(playerInstance, callbackFunction) {

        const button = playerInstance.container.ownerDocument.createElement('button');
        button.setAttribute('type', 'button');
        button.innerText = 'Play';
        button.addEventListener('click', function() { playerInstance.play(); }, false);
        playerInstance.container.appendChild(button);

        //You should invoke the callbackFunction with a custom element which will be used as the video container
        callbackFunction({
            'player': playerInstance.container.ownerDocument.createElement('div')
        });
    }

    destroy() {
        //Cleanup here
    }
    
}

Samples

Here's a brief gallery of code samples.

JavaScript SDK iframe tag Result

TODO

Playground

TODO