Conviva JavaScript Quick Integration

This page serves as a quick reference for your integration, containing mostly code snippets that you'll need at various stages of integration.

Updated 2026-06-30 quick, integration, sensor developer center, sensor integration, javascript, getting started

This page serves as a quick reference for your integration, containing mostly code snippets that you'll need at various stages of integration. For more information or if you need any help, refer to the details on Conviva JavaScript Sensor Integration page.

This documentation is for JS SDK 4.0.3 and above. If you are using the legacy SDK, we highly recommend you upgrade to the new SDK below. To migrate from the legacy SDK to the new SDK, refer to the migration API mapping document here and a summary of the migration benefits here.

Integration Summary

1. Install Conviva Library

Add Conviva Libraries and Configure Dependencies

Add core SDK

// Production Environment
<script type="text/javascript" src="<PATH>/conviva-core-sdk.js"></script>
// Development/Debug Environment
<script type="text/javascript" src="<PATH>/conviva-core-sdk.debug.js"></script>

Add dependencies for Ad SDKs

If using one of the Ad SDKs Conviva provides a module for, download and add the library explicitly:

https://github.com/Conviva/conviva-js-imasdk

Refer to Integrate Ad Managers for the details of ad manager integration.

Initialize the top level object

Initialize the top level Conviva Analytics object:

Conviva.Analytics.init(/* string / customerKey, / object / callbackFunctions, / object */settings=):

Click the arrow to view the reference implementation:

var callbackFunctions = {};
 
callbackFunctions[Conviva.Constants.CallbackFunctions.CONSOLE_LOG] = function (message, logLevel) {
    if (typeof console === 'undefined') return;
    if (console.log && logLevel === Conviva.Constants.LogLevel.DEBUG ||
        logLevel === Conviva.Constants.LogLevel.INFO) {
        console.log(message);
    } else if (console.warn && logLevel === Conviva.Constants.LogLevel.WARNING) {
        console.warn(message);
    } else if (console.error && logLevel === Conviva.Constants.LogLevel.ERROR) {
        console.error(message);
    }
};
 
callbackFunctions[Conviva.Constants.CallbackFunctions.MAKE_REQUEST] = function (httpMethod, url, data, contentType, timeoutMs, callback) {
    var xmlHttpReq = new XMLHttpRequest();
 
    xmlHttpReq.open(httpMethod, url, true);
 
    if (contentType && xmlHttpReq.overrideMimeType) {
        xmlHttpReq.overrideMimeType = contentType;
    }
    if (contentType && xmlHttpReq.setRequestHeader) {
        xmlHttpReq.setRequestHeader('Content-Type', contentType);
    }
    if (timeoutMs > 0) {
        xmlHttpReq.timeout = timeoutMs;
        xmlHttpReq.ontimeout = function () {
            // Often this callback will be called after onreadystatechange.
            // The first callback called will cleanup the other to prevent duplicate responses.
            xmlHttpReq.ontimeout = xmlHttpReq.onreadystatechange = null;
            if (callback) callback(false, "timeout after " + timeoutMs + " ms");
        };
    }
 
    xmlHttpReq.onreadystatechange = function () {
        if (xmlHttpReq.readyState === 4) {
            xmlHttpReq.ontimeout = xmlHttpReq.onreadystatechange = null;
            if (xmlHttpReq.status == 200) {
                if (callback) callback(true, xmlHttpReq.responseText);
            } else {
                if (callback) callback(false, "http status " + xmlHttpReq.status);
            }
        }
    };
 
    xmlHttpReq.send(data);
};
 
callbackFunctions[Conviva.Constants.CallbackFunctions.SAVE_DATA] = function (storageSpace, storageKey, data, callback) {
    var localStorageKey = storageSpace + "." + storageKey;
    try {
        localStorage.setItem(localStorageKey, data);
        callback(true, null);
    } catch (e) {
        callback(false, e.toString());
    }
};
 
callbackFunctions[Conviva.Constants.CallbackFunctions.LOAD_DATA] = function (storageSpace, storageKey, callback) {
    var localStorageKey = storageSpace + "." + storageKey;
    try {
        var data = localStorage.getItem(localStorageKey);
        callback(true, data);
    } catch (e) {
        callback(false, e.toString());
    }
};
 
callbackFunctions[Conviva.Constants.CallbackFunctions.GET_EPOCH_TIME_IN_MS] = function () {
    var d = new Date();
    return d.getTime();
};
 
callbackFunctions[Conviva.Constants.CallbackFunctions.CREATE_TIMER] = function (timerAction, intervalMs) {
    var timerId = setInterval(timerAction, intervalMs);
    var cancelTimerFunc = (function () {
        if (timerId !== -1) {
            clearInterval(timerId);
            timerId = -1;
        }
    });
    return cancelTimerFunc;
};

Sample code illustrating initialization with/without debug:

if (DEBUG) {
   var settings = {};
   settings[Conviva.Constants.GATEWAY_URL] = "YOUR Touchstone Service URL";
   settings[Conviva.Constants.LOG_LEVEL] = Conviva.Constants.LogLevel.DEBUG;
   Conviva.Analytics.init(TEST_CUSTOMER_KEY, callbackFunctions, settings);
} else {
   // production release
   Conviva.Analytics.init(PRODUCTION_CUSTOMER_KEY, callbackFunctions);
}

IMPORTANT: No need to set GATEWAY_URL and LOG_LEVEL settings for your production release. The Conviva SDK provides the default values for production. Use conviva-core-sdk.js for the production release.

Initialize the video object

Create videoAnalytics object.

var videoAnalytics = Conviva.Analytics.buildVideoAnalytics();

Initialize the ad object

Create adAnalytics object.

var adAnalytics = Conviva.Analytics.buildAdAnalytics(videoAnalytics);

2. Configure Metadata

Pre-defined Video and Content Metadata

Constants for Pre-defined Video and Content Metadata

Key / Constant Type Implementation Note
Conviva.Constants.ASSET_NAME string The unique name for each stream/video asset. Values are up to your choice, but a human-readable text prefixed with the unique video ID works best in most Conviva SDK's.**This provides for clarity in reports and makes most popular content easily identifiable. Pattern: [videoID] Video Title

The following are typical patterns for VOD (movies and episodic content) and Live streams: Movie Pattern: [{contentId}] {Movie Title} Sample Value: [12345] The ABC Movie Episode Pattern: [{contentId}] {Show Title} - S:{Season Number}:E{Episode Number} - {Episode Title} Sample Value: [67890] The XYZ Show - S3:E1 - The Pilot Episode Live Stream Pattern: [{channelNumber}] {Chanel Name} Sample Value: [10] PQRS Bay Area

Conviva.Constants.IS_LIVE string Denotes whether the content is video on-demand or a live stream. Affects the computation and availability of the Conviva metrics.

Conviva.Constants.StreamType.VOD Conviva.Constants.StreamType.LIVE

Conviva.Constants.PLAYER_NAME string A string value used to distinguish video players (applications). Simple values that are unique across all of your integrated platforms work best here. If the same player used across multiple platforms, e.g., Tizen, LG TV, WEB, give separate names for each application / platofrm: e.g., "JS Tizen", "JS LGTV", "JS WEB". Do not include the build or version number in this property. The intention is to have a simple way of differentiating data from different players / platforms.
Conviva.Constants.VIEWER_ID string Required for Viewers Module. A unique identifier to distinguish individual viewers or devices through Conviva's Viewers Module. The value shall be unique abstract user's identifier. If user is anonymous, do not set any value for this tag.
Conviva.Constants.STREAM_URL string

The manifest URL of the video stream. The Conviva backend config server attempts to map a portion of StreamURL into a CDN name. For example: In the URL https://www.akamai.net/avengers.m3u8, akamai.net maps to the AKAMAI label. Conviva VSI users can then retrieve metrics based on the mapped CDN name (AKAMAI, in this case).

The URL values reported in the streamURL are case insensitive. The streamURLs with either all capitals or all lower case are acceptable.
Conviva.Constants.DEFAULT_RESOURCE string

This value specifies the video server or CDN name from where the streaming resource is played. Set this field when the video server resource cannot be inferred from the STREAM_URL.

For example, if the streamURL is https://cbd12348.cdn.cms.somewebsitehostname.com/abc.txt, it is not possible to infer the AKAMAI name from the streamURL, and in such a case, it is necessary to report the DEFAULT_Resource as AKAMAI.

The DEFAULT_Resource value is case sensitive. If the resource name is initially reported as AKAMAI (all caps) and subsequently modified in the app to akamai (small letters), it is necessary to inform Conviva about the change because both need to be mapped in the Conviva backend configuration server to ensure that both point to the same CDN name (AKAMAI).

Conviva.Constants.DURATION

integer Duration of the video content, in seconds.
Conviva.Constants.ENCODED_FRAMERATE integer Encoded frame rate of the video stream in frames per second.
Conviva.Constants.FRAMEWORK_NAME string Video Player Framework Name.

NOTE: Autocollected if Conviva module used for video player integration, required for custom integration. **Otherwise, set using the API videoAnalytics.setPlayerInfo(/object/ playerInfo):

var playerInfo = {};
											playerInfo[Conviva.Constants.FRAMEWORK_NAME] = "YOUR_FRAMEWORK_NAME";
								videoAnalytics.setPlayerInfo(playerInfo);
Conviva.Constants.FRAMEWORK_VERSION string Video Player Framework Version.

NOTE: Autocollected if Conviva module used for video player integration, required for custom integration. **Otherwise, set using the API videoAnalytics.setPlayerInfo(/object/ playerInfo):

var playerInfo = {};
											playerInfo[Conviva.Constants.FRAMEWORK_VERSION] = "1.2.3";
								videoAnalytics.setPlayerInfo(playerInfo);
"c3.app.version" string Application build version. Shall have the same value for both ads and video.
"c3.cm.contentType" string Advanced content delivery methods along with Live and VOD.

Acceptable values: "Live", "Live-Linear", "DVR", "Catchup", "VOD".

"c3.cm.channel" string The channel on which the content is consumed.

Example: "ABC".

"c3.cm.brand" string The name of the brand to which the content belongs.

Examples: "ABC X", "ABC Y".

"c3.cm.affiliate" string Affiliate or MVPD name for TV Everywhere authenticated services.

Examples: "Xfinity", "Comcast".

"c3.cm.categoryType" string Content business categories of interest.

Examples: "Episodic", "Movies", "News", "Sports", "Events", "Informercials", "Shorts", "Promos".

"c3.cm.name" string Name of CMS Provider.

Examples: "CMS", "ROVI", "TMS".

"c3.cm.id" string Unique asset identifier to query CMS system to gather additional asset metadata information for a specific asset.

Example: "003b094d-fc5c-3d5a-8ed0-301bf848291e".

"c3.cm.seriesName" string The name of Series. Set the value only if the metadata cannot be gathered from CMS System. Null if not applicable.

Examples: "Friends", "Null".

"c3.cm.seasonNumber" string The Season number. Set the value only if the details cannot be inferred from Asset Provider Server. Null if not applicable.

Examples: "1", "Null".

"c3.cm.showTitle" string The name of the Episode or Show Title. Set the value only if the details cannot be inferred from Asset Provider Server. Null if not applicable.

Examples: "The One with All the Cheesecakes", "Null".

"c3.cm.episodeNumber" string The Episode number. Set the value only if the details cannot be inferred from Asset Provider Server. Null if not applicable.

Examples: "3", "Null".

"c3.cm.genre" string The Primary content genre. Set the value only if the details cannot be inferred from Asset Provider Server. Null if not applicable.

Examples: "Drama", "Null".

"c3.cm.genreList" string The list of the applicable content genre. Set the values in a comma separated list only if the details cannot be inferred from Asset Provider Server. Null if not applicable.

Examples: "Drama, Crime, Political, Violence", "Null"

"c3.cm.utmTrackingUrl" string The UTM parameters in the URL track the effectiveness of online marketing campaign across traffic sources and publishing media. Autocollected from window.location.search, if not set by the application. Conviva uses CONTAINS logic to parse the individual UTM parameters from the URL provided, so either the full URL or just the UTM parameters is acceptable.

**Example values: http://www.example.com/?utm_source=newsletter1&utm_medium=email&utm_campaign=summer-sale&utm_content=toplink or utm_source=newsletter1&utm_medium=email&utm_campaign=summer-sale&utm_content=toplink

This tag is only applicable for web and mobile devices.

Device Metadata

Any Device metadata such as device brand, manufacturer, model, type, version, operating system name and version, category which are common for all the concurrent playback with in one Analytics instance can be reported using the Conviva.Analytics.setDeviceMetadata(/* object */ deviceMetadata):

Device Metadata Instructions (Click to Expand):

var deviceMetadata = {};
deviceMetadata[Conviva.Constants.DeviceMetadata.CATEGORY] = Conviva.Constants.DeviceCategory.WEB;
// set the rest of the required metadata fields as per the table below
Conviva.Analytics.setDeviceMetadata(deviceMetadata);

Custom Metadata

Refer to App Manager->Setup Metadata page for your account to find the custom tags which shall be implemented.

Set custom tags in a similar way for either video or ads, by adding the tags to the contentInfo / adInfo objects, passed into corresponding methods of videoAnalytics / adAnalytics objects.

Update/Amend Metadata

The device metadata can be immediately set when the values are available.

Example usage:

var contentInfo = {};
contentInfo[Conviva.Constants.ASSET_NAME] = "[channel_id] Live Channel Name";
// set the values for the other pre-defined keys as appropriate
contentInfo["c3.cm.contentType"] = "Live-Linear";
// set the values for custom tags as required per definition for your account
contentInfo["my_custom_tag_key"] = "my_custom_tag_value";
videoAnalytics.setContentInfo(contentInfo);

3. Report Events and Metadata

For each video play, report playback attempt requests

videoAnalytics.reportPlaybackRequested(/* object */ contentInfo):
var contentInfo = {};
contentInfo["key"] = "value";
videoAnalytics.reportPlaybackRequested(contentInfo);

Report Ad Breaks to Video Session

**To handle ads, inform videoAnalytics object that ad break is started:**

videoAnalytics.reportAdBreakStarted(/* Conviva.Constants.AdType / adType, / Conviva.Constants.AdPlayer */ adPlayer):

Client-side Ads

// Ad Break Start for client side ad insertion with separate player instance for ads
videoAnalytics.reportAdBreakStarted(Conviva.Constants.AdType.CLIENT_SIDE, Conviva.Constants.AdPlayer.SEPARATE);
 
// Ad Break Start for client side ad insertion with same player instance for ads
videoAnalytics.reportAdBreakStarted(Conviva.Constants.AdType.CLIENT_SIDE, Conviva.Constants.AdPlayer.CONTENT);

Server-side Ads

// Server-side ads are embedded within the main video content.
// Ad Break Start for server side ad insertion
videoAnalytics.reportAdBreakStarted(Conviva.Constants.AdType.SERVER_SIDE, Conviva.Constants.AdPlayer.CONTENT);

On ad break ended

videoAnalytics.reportAdBreakEnded();

For each video play end, report playback ended

videoAnalytics.reportPlaybackEnded();

4. Integrate Video Players

If instructions for your player are not shown below, please follow the instructions for "Custom Integration", or contact your Conviva representative.

HTML5VideoElement

Add the Conviva HTML5 Video Element module dependency

Refer to this sample code to include the Conviva library and MSE open source:

Via HTML:

<script type="text/javascript" src="<PATH>/hasplayer.js"></script> // Smooth Streaming support
<script type="text/javascript" src="<PATH>/dash.all.min.js"></script> // Dash Support
<script type="text/javascript" src="<PATH>/hls.min.js"></script> // HLS Support
<script type="text/javascript" src="<PATH>/conviva-core-sdk.js"></script>
<script type="text/javascript" src="<PATH>/conviva-html5native-impl.js"></script>

Via import/require:

const Conviva = require('<path>/conviva-js-coresdk');
const ConvivaHtml5Module = require('<path>/ conviva-js-html5');
Conviva.Analytics.init(customerKey, null, settings);

Set player reference to Conviva videoAnalytics

videoAnalytics.setPlayer(HTMLVideoElement);

If Core SDK and html5 module are loaded in private scope instead of global scope, then pass the html5 module object as the second argument in the setPlayer API.

Important: The application sets the player reference immediately after the player instance is available.

var options = {};
options[Conviva.Constants.CONVIVA_MODULE] = ConvivaHtml5Module;
var videoAnalytics = Conviva.Analytics.buildVideoAnalytics();
videoAnalytics.setPlayer(HTMLVideoElement, options);
Key Implementation Note
videoAnalytics.reportPlaybackError() **(VSF/VPF) The module listens for the video errors fired by the player using error event callback.

To report application level errors impacting user experience, call videoAnalytics.reportPlaybackError(/* string */ message) explicitly.

Implement Metadata

Report the device metadata of CATEGORY and TYPE explicitly by the application, as Conviva can autocollect the remaining metadata from the UAS. Refer to the code sample below:

var deviceMetadata = {};
// set the corresponding Conviva.Constants.DeviceType
deviceMetadata[Conviva.Constants.DeviceMetadata.TYPE] = Conviva.Constants.DeviceType.DESKTOP;
deviceMetadata[Conviva.Constants.DeviceMetadata.CATEGORY] = Conviva.Constants.DeviceCategory.WEB;
Conviva.Analytics.setDeviceMetadata(deviceMetadata);

To implement the rest of metadata, refer to the above sections of common pre-defined, pre-defined video, and custom metadata definitions for implementation details.

Custom Integration
For reference, the deprecated legacy JavaScript SDK integration documentation can be found here.

Conviva SDK can be used to integrate video players using explicit metric reporting using the videoAnalytics object. The major steps required are listed below:

Report playback failures

To report fatal playback error AND quit the session: videoAnalytics.reportPlaybackFailed(/* string / errorMessage, / object */ contentInfo=):

Example usage:

// report error and cleanup immediately. The contentInfo provides metadata for the failed video.
videoAnalytics.reportPlaybackFailed(errorMessage, contentInfo);

// report the error but keep the session open
videoAnalytics.reportPlaybackError(errorMessage, Conviva.Constants.ErrorSeverity.FATAL);
// report error and create session when playback starts to report it in the session.
videoAnalytics.reportPlaybackError(errorMessage, Conviva.Constants.ErrorSeverity.FATAL);
videoAnalytics.reportPlaybackRequested(contentInfo);

Report playback metrics

videoAnalytics.reportPlaybackMetric(/* Conviva.Constants.Playback / key, / string | integer | long | Conviva.Constants.PlayerState */ val..):

Example usage:

// integer parameter in kbps for this key Conviva.Constants.Playback.BITRATE
videoAnalytics.reportPlaybackMetric(Conviva.Constants.Playback.BITRATE, 3600);

Implement Callback function for polled metrics

NOTE: Since this API callback is called every 1 sec, it is recommended that no other metrics than the one specified be updated. It must not retain strong references to instances in outer scopes.

// Sample Code Snippet
videoAnalytics.setCallback(function() {
    videoAnalytics.reportPlaybackMetric(Conviva.Constants.Playback.BUFFER_LENGTH, bufferLength);
    videoAnalytics.reportPlaybackMetric(Conviva.Constants.Playback.PLAY_HEAD_TIME, playheadTimeMs);
    videoAnalytics.reportPlaybackMetric(Conviva.Constants.Playback.RENDERED_FRAMERATE, renderedFramerate);
});

Implement Metadata

For Custom Integration, Conviva SDK does not capture any metadata automatically.

To implement the rest of metadata, refer to the above sections of common pre-defined, pre-defined video, and custom metadata metadata definitions for implementation details.

Video.js

Conviva Video.js module autocollects events emitted by Video.js player. Therefore, it's not necessary to report these events explicitly by using "reportPlaybackMetric()" API. It's still required to report application events such as backgrounding, metadata, session close, ad-related events.

Add the Conviva Video.js module dependency

Refer to the following sample code to load Video.js components first followed by Conviva modules:

Via HTML:

<script src="<PATH>/video.min.js"></script>
<script type="text/javascript" src="<PATH>/conviva-core-sdk.js"></script>
<script type="text/javascript" src="<PATH>/conviva-videojs-module.js"></script>

Via import/require:

import Conviva from '@convivainc/conviva-js-coresdk'
import ConvivaVideojsModule from'@convivainc/conviva-js-videojs'
const Conviva = require('<path>/conviva-js-coresdk');
const ConvivaVideojsModule = require('<path>/conviva-js-videojs');

Application doesn't need to implement the system utility functions of Time, Timer, HTTP, Storage Load/Save, Log as Conviva Video.js module uses Conviva's default ones.

Conviva.Analytics.init(customerKey, null, settings);

Set player reference to Conviva videoAnalytics

videoAnalytics.setPlayer(videojs);

If Core SDK and Video.js module are loaded in private scope instead of global scope, then pass the Video.js module object as the second argument in the setPlayer API.

var options = {};
options[Conviva.Constants.CONVIVA_MODULE] = ConvivaVideojsModule;
   
var videoAnalytics = Conviva.Analytics.buildVideoAnalytics();
videoAnalytics.setPlayer(videojs, options);
Key Implementation Note
videoAnalytics.reportPlaybackError() **(VSF/VPF) The module listens for the video errors fired by the player using error, contenterror, and aderror event callbacks. To report application level errors that impact user experience, call videoAnalytics.reportPlaybackError(/* string */ message, /* Conviva.Constants.ErrorSeverity */ severity) explicitly. Application should close the session, only if the player will not recover from the playback failure. For example, when error code is 4, video.js does not provide the option for user to play the video. Hence, the player will never recover from the failure.

Implement Metadata

Report the device metadata of CATEGORY and TYPE explicitly by the application, as Conviva can autocollect the remaining metadata from the UAS. Refer to the code sample below:

var deviceMetadata = {};
// set the corresponding Conviva.Constants.DeviceType
deviceMetadata[Conviva.Constants.DeviceMetadata.TYPE] = Conviva.Constants.DeviceType.DESKTOP;
deviceMetadata[Conviva.Constants.DeviceMetadata.CATEGORY] = Conviva.Constants.DeviceCategory.WEB;
Conviva.Analytics.setDeviceMetadata(deviceMetadata);

To implement the rest of metadata, refer to the above sections of common pre-defined, pre-defined video, and custom metadata metadata definitions for implementation details.

Clean up Conviva objects

Report end of playback when playback ends or when all the ads are completed, whichever occurs last. Conviva objects must be released when the webpage lifecycle ends. Refer to Conviva Cleanup for more details.

Chromecast v2 (Deprecated)

Conviva Chromecast v2 module autocollects events emitted by Player Manager. Therefore, it's not necessary to report these events explicitly by using "reportPlaybackMetric()" API. It's still required to report application events such as backgrounding, metadata, session close, ad-related events.

Add the Conviva Chromecast v2 module dependency

You can add the Conviva Chromecast v2 module dependency by choosing one of the following options:

  • Install using the npm package manager
  • Install using the yarn package manager
  • Download and add the library explicitly from Conviva GitHub

From Chromecast v2 module version 4.0.8 onwards, Conviva supports installation through npm and yarn package managers.

To install using the npm package manager, use:

npm install @convivainc/conviva-js-chromecast-v2 --save

To install using the yarn package manager, use:

yarn add @convivainc/conviva-js-chromecast-v2

To download and add the library explicitly from Conviva GitHub, refer: https://github.com/Conviva/conviva-js-chromecast-v2

Refer to this sample code which includes the Chromecast v2 modules followed by Conviva modules:

<script type="text/javascript" src="//www.gstatic.com/cast/sdk/libs/receiver/2.0.0/cast_receiver.js"></script>
<script type="text/javascript" src="//www.gstatic.com/cast/sdk/libs/mediaplayer/1.0.0/media_player.js"></script>
 
<script type="text/javascript" src="<PATH>/conviva-core-sdk.js"></script>
<script type="text/javascript" src="<PATH>/conviva-chromecast-v2module.js"></script>

Application doesn't need to implement the system utility functions of Time, Timer, HTTP, Storage Load/Save, Log as Conviva Chromecast v2 module uses Conviva's default ones.

Conviva suggest that you initialize Conviva on LOAD_START event from PlayerManager Instance in Chromecast.

Conviva.Analytics.init(customerKey, null, settings);

Set player reference to Conviva videoAnalytics

var extraListeners = {};
extraListeners[Conviva.Constants.MEDIA_ELEMENT] = mediaElement;
 
videoAnalytics.setPlayer(castPlayerManager, extraListeners);

Since that moment, Conviva library will listen for all relevant events automatically.

Metrics monitored by Conviva Chromecast v2 module (if applicable):

Key Implementation Note
videoAnalytics.reportPlaybackError() **(VSF/VPF) The module listens for the video errors fired by the player using error event callback.

To report application level errors impacting user experience, call videoAnalytics.reportPlaybackError(/* string */ message) explicitly.

Conviva.Constants.Playback.PLAYER_STATE Autocollected.
Conviva.Constants.Playback.BITRATE **Autocollected** by default. **Report the bitrate, if the application has information in few scenarios where it is not reported by Chromecast v2.
Conviva.Constants.Playback.SEEK_STARTED **Autocollected**.
Conviva.Constants.Playback.SEEK_ENDED **Autocollected**.
Conviva.Constants.Playback.PLAY_HEAD_TIME **Autocollected**.
Conviva.Constants.Playback.BUFFER_LENGTH **Report** if the application implementation supports collecting buffer length, as Chromecast v2 doesn't support reporting of the buffer length by default.
Conviva.Constants.Playback.RENDERED_FRAMERATE **Report** if the application implementation supports collecting rendered framerate, as Chromecast v2 doesn't support reporting of the rendered framerate by default.
Conviva.Constants.Playback.CDN_IP **Report** CDN IP address in string format. Can be **autocollected**.
Please contact Conviva Support to enable auto collection configuration.
Conviva.Constants.Playback.DROPPED_FRAMES_TOTAL **Autocollected** using the mediaElement.getVideoQuality().droppedVideoFrames.

Implement Metadata

Metadata monitored by Conviva Chromecast v2 module (if applicable):

Key Implementation Note
Conviva.Constants.DURATION **Autocollected** using mediaElement.duration.
Conviva.Constants.FRAMEWORK_NAME **Autocollected** as "Cast Player".
Conviva.Constants.FRAMEWORK_VERSION **Autocollected** using cast.receiver.VERSION.
Device Metadata Implementation Note
Conviva.Constants.DeviceMetadata.BRAND **Autocollected** as "Google".
Conviva.Constants.DeviceMetadata.MANUFACTURER **Autocollected** as "Google".
Conviva.Constants.DeviceMetadata.MODEL **Notapplicable** as Chromecast doesn't have an API to fetch the model.
Conviva.Constants.DeviceMetadata.TYPE **Autocollected** as Conviva.Constants.DeviceType.SETTOP.
Conviva.Constants.DeviceMetadata.OS_NAME **Autocollected** as "Chrome OS".
Conviva.Constants.DeviceMetadata.OS_VERSION **Autocollected** using UAS CrKey/firmwareVersion.
Conviva.Constants.DeviceMetadata.CATEGORY **Autocollected** as Conviva.Constants.DeviceCategory.CHROMECAST.
Conviva.Constants.DeviceMetadata.SCREEN_RESOLUTION_WIDTH **Autocollected** using window.screen.width.
Conviva.Constants.DeviceMetadata.SCREEN_RESOLUTION_HEIGHT **Autocollected** using window.screen.height.
Conviva.Constants.DeviceMetadata.SCREEN_RESOLUTION_SCALE_FACTOR **Autocollected** using window.devicePixelRatio.

To implement the rest of metadata, refer to the above sections of common pre-defined, pre-defined video, and custom metadata metadata definitions for implementation details.

Clean up Conviva objects

Report end of playback where cast framework's MEDIA_FINISHED event is handled and Conviva objects should be released where window.onunload event is handled , refer to Conviva Cleanup for more details.

Chromecast CAF

Conviva Chromecast CAF module autocollects events emitted by Player Manager. Therefore, it's not necessary to report these events explicitly by using "reportPlaybackMetric()" API. It's still required to report application events such as backgrounding, metadata, session close, ad-related events.

Add the Conviva Chromecast CAF module dependency

Refer to this sample code which includes the Chromecast CAF modules followed by Conviva modules.

Via HTML:

<script type="text/javascript" src="//www.gstatic.com/cast/sdk/libs/caf_receiver/v3/cast_receiver_framework.js"></script>
 
<script type="text/javascript" src="<PATH>/conviva-core-sdk.js"></script>
<script type="text/javascript" src="<PATH>/conviva-chromecast-cafmodule.js"></script>

Via Import/Require:

import Conviva from '@convivainc/conviva-js-coresdk'
import ConvivaChromecastCafModule from'@convivainc/conviva-js-chromecast-caf '
const Conviva = require('<path>/conviva-js-coresdk');
const ConvivaChromecastCafModule = require('<path>/conviva-js-chromecast-caf ');

Conviva suggests that you initialize Conviva on LOAD_START event from PlayerManager Instance in Chromecast.

Conviva.Analytics.init(customerKey, null, settings);

Set player reference to Conviva videoAnalytics

The cafPlayerManager argument is the instance of PlayerManager which is common for generic or custom UI.

// Generic UI
<cast-media-player></cast-media-player>
 
// Custom UI
<video class="castMediaElement"></video>
var context = cast.framework.CastReceiverContext.getInstance();
var cafPlayerManager = context.getPlayerManager();
 
videoAnalytics.setPlayer(cafPlayerManager);

If Core SDK and ChromecastCaf module are loaded in private scope instead of global scope, then pass the ChromcastCaf module object as the second argument in the setPlayer API.

// Generic UI
<cast-media-player></cast-media-player>
 
// Custom UI
<video class="castMediaElement"></video>
var context = cast.framework.CastReceiverContext.getInstance();
var cafPlayerManager = context.getPlayerManager();

var options = {};
options[Conviva.Constants.CONVIVA_MODULE] = ConvivaChromecastCafModule;
   
var videoAnalytics = Conviva.Analytics.buildVideoAnalytics();
videoAnalytics.setPlayer(cafPlayerManager, options);
Key Implementation Note
videoAnalytics.reportPlaybackError() **(VSF/VPF) The module listens for the video errors fired by the player using cast.framework.events.EventType.ERROR event callback.

To report application level errors impacting user experience, call videoAnalytics.reportPlaybackError(/* string */ message) explicitly.

Implement Metadata

To implement the rest of metadata, refer to the above sections of common pre-defined, pre-defined video, and custom metadata metadata definitions for implementation details.

Clean up Conviva objects

Report end of playback where cast framework's MEDIA_FINISHED event is handled and Conviva objects should be released where window.onunload event is handled. Refer to Conviva Cleanup for more details.

Samsung TV Tizen Avplay

Conviva Samsung TV Tizen module autocollects events emitted by Tizen avplay. Therefore, it's not necessary to report these events explicitly by using "reportPlaybackMetric()" API. It's still required to report application events such as seek, metadata, session close, ad-related events.

Add the Conviva Samsung TV Tizen module module dependency

Add the below mentioned configurations in the config.xml file in the application to provide the required privileges and the background support:


<widget>
<content src="index.html"/>
<tizen:privilege name=
    "http://developer.samsung.com/privilege/avplay"/>
<tizen:privilege name=
    "http://developer.samsung.com/privilege/productinfo"/>
<tizen:privilege name=
    "http://developer.samsung.com/privilege/network.public"/>
<tizen:profile name="tv-samsung"/>
<tizen:setting background-support="enable"/>
</widget>

Refer to the sample code which loads the Tizen components first and then the Conviva libraries:

<script type="text/javascript" src="$WEBAPIS/webapis/webapis.js">
</script>
 
<script type="text/javascript"src="<PATH>/conviva-core-sdk.js">
</script>
<script type="text/javascript" src="<PATH>/conviva-tizen-module.js">
</script>

Application doesn't need to implement the system utility functions of Time, Timer, HTTP, Storage Load/Save, Log as Conviva Samsung TV Tizen module uses Conviva's default ones.

Conviva suggest that you initialize Conviva on window.onload() in Tizen.

Conviva.Analytics.init(customerKey, null, settings);

Set player reference to Conviva videoAnalytics

IMPORTANT: The application listener should be set prior to reporting of the setPlayer API.

// Sample code snippet
var listener = {
    onbufferingstart: function () {},
    onbufferingprogress: function (percent) {…},
    onbufferingcomplete: function () {…},
    oncurrentplaytime: function (currentTime) {…},
    onevent: function (eventType, eventData) {…},
    onsubtitlechange: function (duration, text, data3, data4) {…},
    ondrmevent: function (drmEvent, drmData) {…},
    onstreamcompleted: function () {
        convivaVideoAnalytics.reportPlaybackEnded();
    },
    onerror: function (eventType) {…}
};
webapis.avplay.setListener(listener);
convivaVideoAnalytics.setPlayer(listener);
convivaVideoAnalytics.reportPlaybackRequested();
 
try {
    webapis.avplay.open(url);
    webapis.avplay.prepareAsync(function () {
       try {
           webapis.avplay.play();
       } catch (e) {
            // error: play
            convivaVideoAnalytics.reportPlaybackFailed("error: play");
       }
    }, function () {
       // prepareAsync failure callback
        convivaVideoAnalytics.reportPlaybackFailed(
        "prepareAsync failure callback");
    });
} catch (e) {
    // error: open or prepareAsync
     convivaVideoAnalytics.reportPlaybackFailed(
     "error: open or prepareAsync");
}
Key Implementation Note
(VSF/VPF)

The module listens for the video errors fired by the player using onerror() listener callback. *To report application level errors impacting user experience, call videoAnalytics.reportPlaybackError(/ string */ message) explicitly.

To report any playback failures triggered due to prepareAync failures call videoAnalytics.reportPlaybackFailed(/* string */ message) explicitly.

Conviva.Constants.Playback. PLAYER_STATE Autocollected.
Conviva.Constants.Playback.**BITRATE Autocollected by default. **Report the bitrate, if the application has information in few scenarios where it is not reported by Tizen.
Conviva.Constants.Playback.**SEEK_STARTED

Report the start of seeking or scrubbing by user. Report seek position as second argument.

Click to view the reference implementation:

// Register the key handler for seek, fast forward and rewind:
// seekStartFlag to prevent multiple clicks from sending multiple 
// pss events.
var seekStartFlag = true; 
 
/**
* Jump forward 3 seconds (3000 ms).
*/
fastforward: function () {
var seekToPos = 3000; //Value of the seek time in milliseconds
try {
    if(seekStartFlag) {
        convivaVideoAnalytics.reportPlaybackMetric(
        Conviva.Constants.Playback.SEEK_STARTED, 
        webapis.avplay.getCurrentTime() + seekToPos); ***
    }
    ffSuccess = function() {
        seekStartFlag = true;
        convivaVideoAnalytics.reportPlaybackMetric(
        Conviva.Constants.Playback.SEEK_ENDED);
    };
    ffError = function(e) {
        seekStartFlag = true;
        convivaVideoAnalytics.reportPlaybackMetric(
        Conviva.Constants.Playback.SEEK_ENDED);
    };
    webapis.avplay.jumpForward(seekToPos, ffSuccess, ffError);
} catch (e) {
}
},
 
/**
* Seek to 3 seconds (3000 ms).
*/
seek : function () {
var seekToPos = 3000; //Value of the seek time in milliseconds
try {
     if(seekStartFlag) {
        seekStartFlag = false;
        convivaVideoAnalytics.reportPlaybackMetric(
        Conviva.Constants.Playback.SEEK_STARTED,
        seekToPos);
     }
     seekSucess = function() {
        seekStartFlag = true;
        convivaVideoAnalytics.reportPlaybackMetric(
        Conviva.Constants.Playback.SEEK_ENDED);
     };
     seekFail = function() {
        seekStartFlag = true;
        convivaVideoAnalytics.reportPlaybackMetric(
        Conviva.Constants.Playback.SEEK_ENDED);
     };
     webapis.avplay.seekTo(seekToPos, seekSucess , seekFail);
} catch (e) {
}
},
 
/**
* Rewind 3 seconds (3000 ms).
*/
rew: function () {
var seekToPos = 3000; //Value of the seek time in milliseconds
try {
    if(seekStartFlag) {
        seekStartFlag = false;
        convivaVideoAnalytics.reportPlaybackMetric(
        Conviva.Constants.Playback.SEEK_STARTED, 
        webapis.avplay.getCurrentTime() - seekToPos);
    }
    rewSuccess = function() {
        seekStartFlag =true;
        convivaVideoAnalytics.reportPlaybackMetric(
        Conviva.Constants.Playback.SEEK_ENDED);
    };
    rewError = function(e) {
        seekStartFlag = true;
        convivaVideoAnalytics.reportPlaybackMetric(
        Conviva.Constants.Playback.SEEK_ENDED);
    };
    webapis.avplay.jumpBackward(seekToPos, rewSuccess, rewError);
} catch (e) {
}
}
Conviva.Constants.Playback.**SEEK_ENDED

Report the end of seeking or scrubbing by user.

Click to view the reference implementation:

// Register the key handler for seek, fast forward and rewind:
// seekStartFlag to prevent multiple clicks from sending multiple
// pss events.
var seekStartFlag = true;
 
/**
* Jump forward 3 seconds (3000 ms).
*/
fastforward: function () {
var seekToPos = 3000; //Value of the seek time in milliseconds
try {
    if(seekStartFlag) {
        convivaVideoAnalytics.reportPlaybackMetric(
        Conviva.Constants.Playback.SEEK_STARTED,
        webapis.avplay.getCurrentTime() + seekToPos); ***
    }
    ffSuccess = function() {
        seekStartFlag = true;
        convivaVideoAnalytics.reportPlaybackMetric(
        Conviva.Constants.Playback.SEEK_ENDED);
    };
    ffError = function(e) {
        seekStartFlag = true;
        convivaVideoAnalytics.reportPlaybackMetric(
        Conviva.Constants.Playback.SEEK_ENDED);
    };
    webapis.avplay.jumpForward(seekToPos, ffSuccess, ffError);
} catch (e) {
}
},
 
/**
* Seek to 3 seconds (3000 ms).
*/
seek : function () {
var seekToPos = 3000; //Value of the seek time in milliseconds
try {
     if(seekStartFlag) {
        seekStartFlag = false;
        convivaVideoAnalytics.reportPlaybackMetric(
        Conviva.Constants.Playback.SEEK_STARTED,
        seekToPos);
     }
     seekSucess = function() {
        seekStartFlag = true;
        convivaVideoAnalytics.reportPlaybackMetric(
        Conviva.Constants.Playback.SEEK_ENDED);
     };
     seekFail = function() {
        seekStartFlag = true;
        convivaVideoAnalytics.reportPlaybackMetric(
        Conviva.Constants.Playback.SEEK_ENDED);
     };
     webapis.avplay.seekTo(seekToPos, seekSucess , seekFail);
} catch (e) {
}
},
 
/**
* Rewind 3 seconds (3000 ms).
*/
rew: function () {
var seekToPos = 3000; //Value of the seek time in milliseconds
try {
    if(seekStartFlag) {
        seekStartFlag = false;
        convivaVideoAnalytics.reportPlaybackMetric(
        Conviva.Constants.Playback.SEEK_STARTED,
        webapis.avplay.getCurrentTime() - seekToPos);
    }
    rewSuccess = function() {
        seekStartFlag =true;
        convivaVideoAnalytics.reportPlaybackMetric(
        Conviva.Constants.Playback.SEEK_ENDED);
    };
    rewError = function(e) {
        seekStartFlag = true;
        convivaVideoAnalytics.reportPlaybackMetric(
        Conviva.Constants.Playback.SEEK_ENDED);
    };
    webapis.avplay.jumpBackward(seekToPos, rewSuccess, rewError);
} catch (e) {
}
}
Conviva.Constants.Playback.**PLAY_HEAD_TIME Autocollected.
Conviva.Constants.Playback.**BUFFER_LENGTH

Not Applicable as Tizen doesn't have an API to detect the Buffer Length.

Conviva.Constants.Playback.**RENDERED_FRAMERATE Report if the application implementation supports collecting rendered framerate, as Tizen doesn't support reporting of the rendered framerate by default.
Conviva.Constants.Playback.**CDN_IP Report CDN IP address in string format. Can be **autocollected **.**
: Please contact Conviva Support to enable auto collection configuration.

Connection Type is autocollected by Tizen module using the webapis.network.getActiveConnectionType():

Raw Value Significance Mapping
0 webapis.network.NetworkActiveConnectionType.DISCONNECTED Offline
1 webapis.network.NetworkActiveConnectionType.WIFI WiFi
2 webapis.network.NetworkActiveConnectionType.CELLULAR OTHER
3 webapis.network.NetworkActiveConnectionType.ETHERNET Ethernet

Implement Metadata

Metadata monitored by Conviva Samsung TV Tizen module (if applicable):

To implement the rest of metadata, refer to the above sections of common pre-defined, pre-defined video, and custom metadata metadata definitions for implementation details.

Clean up Conviva objects

The cleanup should be invoked where Application's tizen.application.getCurrentApplication().exit() is handled, refer to Conviva Cleanup for more details.

Issue: Tizen does not report changes in video resolution during playback. The video width and height values auto-collected initially remains constant during the course of the video playback even when there is a change in video resolution.

PlayStation Trilithium

Conviva PlayStation Trilithium module autocollects events emitted by Video player. Therefore, it's not necessary to report these events explicitly by using "reportPlaybackMetric()" API. It's still required to report application events such as seek, backgrounding, metadata, session close, ad-related events.

Add the Conviva PlayStation Trilithium module dependency

You can add the Conviva PlayStation Trilithium module dependency by choosing one of the following options:

  • Install using the npm package manager
  • Install using the yarn package manager
  • Download and add the library explicitly from Conviva GitHub

From PlayStation Trilithium module version 4.0.2 onwards, Conviva supports installation through npm and yarn package managers.

To install using the npm package manager, use:

npm install @convivainc/conviva-js-playstation-trilithium --save

To install using the yarn package manager, use:

yarn add @convivainc/conviva-js-playstation-trilithium

To download and add the library explicitly from Conviva GitHub, refer: https://github.com/Conviva/conviva-js-playstation-trilithium

Refer to this sample code which includes the Conviva modules:

include ('<PATH>/conviva-core-sdk.js');
include ('<PATH>/conviva-playstation-trilithium-module.js');

Application need to explicitly implement the system utility functions of Timer, HTTP, Storage Load/Save and Log, Time can be used of Conviva's default ones.

Click to view the reference implementation:

var callbackFunctions = {};
 
callbackFunctions[Conviva.Constants.CallbackFunctions.MAKE_REQUEST] = 
function (isPOST, url, data, contentType, timeout, callback)) {
    if (typeof(data) !== "string") {
        data = JSON.stringify(data);
    }
    var _s = this;
    if (!_s._httpClientObject) {
        _s._httpClientObject = engine.createHttpClient();
    }
 
    var httpRequestObject = 
    _s._httpClientObject.request((isPOST ? "POST" : "GET"), url);
    if (isPOST) {
        httpRequestObject.sendBody(data);
    }
    httpRequestObject.onError = 
    function (httpStatusCode, content, size) {
        callback(false, null);
    }
    httpRequestObject.onComplete = function (response) {
        callback(true, response);
    }
    httpRequestObject.start();
    return function () {
        httpRequestObject.cancel();
    };
};
 
callbackFunctions[Conviva.Constants.CallbackFunctions.SAVE_DATA] = 
function (storageSpace, storageKey, data, callback) {
    var localStorageKey = storageSpace + "." + storageKey;
    try {
        engine.storage.local[localStorageKey] = data;
        callback(true, null);
    } catch (e) {
        callback(false, e.toString());
    }
};
 
callbackFunctions[Conviva.Constants.CallbackFunctions.LOAD_DATA] = 
function (storageSpace, storageKey, callback) {
    var localStorageKey = storageSpace + "." + storageKey;
    try {
        var data = engine.storage.local[localStorageKey];
        callback(true, data);
    } catch (e) {
        callback(false, e.toString());
    }
};
 
callbackFunctions[Conviva.Constants.CallbackFunctions.CREATE_TIMER] = 
function (timerAction, intervalMs) {
    var timerId = setInterval(timerAction, intervalMs);
    var cancelTimerFunc = (function () {
        if (timerId !== -1) {
            clearInterval(timerId);
            timerId = -1;
        }
    });
    return cancelTimerFunc;
};
 
var intervals = {};
var intervalsCount = 0;
function setInterval(func, time) {
    var intervalId = 
    intervalsCount ? ++intervalsCount : intervalsCount = 1;
    intervals[intervalId] = function () {
        if (intervals[intervalId]) {
            if (intervals[intervalId].active) {
                func();
                setTimeout(intervals[intervalId], time);
            } else {
                delete intervals[intervalId];
            }
        }
    }
    intervals[intervalId].active = true;
    setTimeout(intervals[intervalId], time);
    return intervalId;
}
 
function clearInterval(intervalId) {
    intervals[intervalId].active = false;
}
 
Conviva.Analytics.init(customerKey, callbackFunctions);

Set player reference to Conviva videoAnalytics

videoAnalytics.setPlayer(videoPlayer); // created using engine.createVideo()
Key Implementation Note
videoAnalytics.reportPlaybackError() **(VSF/VPF) The module listens for the video errors fired by the player using onError event callback.

To report application level errors impacting user experience, call videoAnalytics.reportPlaybackError(/* string */ message) explicitly.

Conviva.Constants.Playback.PLAYER_STATE Autocollected.
Conviva.Constants.Playback.BITRATE **Autocollected** by default. **Report the bitrate, if the application has information in few scenarios where it is not accurtely reported by Trilithium.
Conviva.Constants.Playback.SEEK_STARTED

Report the start of seeking or scrubbing by user. Report seek position as second argument.

Click to view the reference implementation:

var seeking = false;
var seekStartTime;
var seekMultiple;
var seekStartOffset;
 
function SeekRight(video) {
    if (!video) {
        return;
    }
    if (!seeking) {
        seeking = true;
        seekStartTime = (+new Date) / 1000.0;
        seekMultiple = 0;
        seekStartOffset = video.currentTime;
    }
    seekMultiple = seekMultiple + 1;
    seek();
}
 
function SeekLeft(video) {
    if (!video) {
        return;
    }
    if (!seeking) {
        seeking = true;
        seekStartTime = (+new Date) / 1000.0;
        seekMultiple = 0;
        seekStartOffset = video.currentTime;
    }
    seekMultiple = seekMultiple - 1;
    seek();
}
 
function SeekToTime() {
    if (seeking) {
        var nowTime = (+new Date)/1000.0;
        var targetTime =  
        seekStartOffset + (nowTime - seekStartTime) * seekMultiple;
        if (targetTime < 0) {
            targetTime = 0;
        }
        return targetTime;
    } else {
        return -1;
    }
}
 
function seek() {
    if (seeking && SeektoTime() != -1) {
        convivaVideoAnalytics.reportPlaybackMetric(
        Conviva.Constants.Playback.SEEK_STARTED, 
        Math.round(SeekToTime() * 1000));
        // Seeks the video to the set position
        video.currentTime = SeekToTime(); 
        seeking = false;
    }
}
Conviva.Constants.Playback.SEEK_ENDED **Notapplicable** as the video.currentTime is used for seeking or scrubbing by application.
Conviva.Constants.Playback.PLAY_HEAD_TIME **Autocollected** using video.currentTime.
Conviva.Constants.Playback.BUFFER_LENGTH **Not applicable** as Trilithium doesnt have an API to detect the Buffer Length.
Conviva.Constants.Playback.RENDERED_FRAMERATE **Report** if the application implementation supports collecting rendered framerate, as Trilithium doesn't support reporting of the rendered framerate by default.
Conviva.Constants.Playback.CDN_IP **Report** CDN IP address in string format.

Connection Type is autocollected by Trilithium module using the engine.stats.network.type

Internet Connection Type Representation String
wi-fi WiFi
ethernet Ethernet
3G 3G
Unknown OTHER

Implement Metadata

To implement the rest of metadata, refer to the above sections of common pre-defined, pre-defined video, and custom metadata metadata definitions for implementation details.

PlayStation WebMAF

Conviva PlayStation WebMAF module autocollects events emitted by Video player. Therefore, it's not necessary to report these events explicitly by using "reportPlaybackMetric()" API. It's still required to report application events such as metadata, session close, ad-related events.

Add the Conviva PlayStation WebMAF module dependency

You can add the Conviva PlayStation WebMAF module dependency by choosing one of the following options:

  • Install using the npm package manager
  • Install using the yarn package manager
  • Download and add the library explicitly from Conviva GitHub

From PlayStation WebMAF module version 4.0.2 onwards, Conviva supports installation through npm and yarn package managers.

To install using the npm package manager, use:

npm install @convivainc/conviva-js-playstation-webmaf --save

To install using the yarn package manager, use:

yarn add @convivainc/conviva-js-playstation-webmaf

To download and add the library explicitly from Conviva GitHub, refer: https://github.com/Conviva/conviva-js-playstation-webmaf

Refer to this sample code to include the Conviva modules:

<script type="text/javascript" src="<PATH>/conviva-core-sdk.js"></script>
<script type="text/javascript" src="<PATH>/conviva-webmaf-module.js"></script>

Application need to explicitly implement the system utility functions of Storage Load/Save and Timer, HTTP, Log, Time can be used of Conviva's default ones.

Click to view the reference implementation:

var callbackFunctions = {};

callbackFunctions[Conviva.Constants.CallbackFunctions.SAVE_DATA] = 
function (storageSpace, storageKey, data, callback) {
    var localStorageKey = storageSpace + "." + storageKey;
    try {
        var forever = new Date();
        forever.setTime(forever.getTime() + 10 * 365 * 24 * 3600 * 1000); // +10years
        document.cookie = 
        localStorageKey + "=" + data + "; expires=" + 
        forever.toGMTString() + "; path=/";
        callback(true, null);
    } catch (e) {
        callback(false, e.toString());
    }
};

callbackFunctions[Conviva.Constants.CallbackFunctions.LOAD_DATA] = 
function (storageSpace, storageKey, callback) {
    var localStorageKey = storageSpace + "." + storageKey;
    try {
        var cookies = document.cookie;
        var start = cookies.indexOf(" " + localStorageKey + "=");
        if (start == -1) {
            start = cookies.indexOf(localStorageKey + "=");
        }
        if (start != -1) {
            start = cookies.indexOf("=", start) + 1;
            var end = cookies.indexOf(";", start);
            if (end == -1) {
                end = cookies.length;
            }
            var data = cookies.substring(start, end);
            callback(true, data);
        }
    } catch (e) {
        callback(false, e.toString());
    }
};

Conviva.Analytics.init(customerKey, callbackFunctions);

Set player reference to Conviva videoAnalytics

videoAnalytics.setPlayer(videometrics);

Starting that moment, Conviva library will listen for all relevant events automatically.

Metrics monitored by Conviva PlayStation WebMAF module (if applicable):

Key Implementation Note
videoAnalytics.reportPlaybackError() **(VSF/VPF) The module listens for the video errors fired by the player using playerStreamingError, playerError and videometrics.onError event callbacks.

To report application level errors impacting user experience, call videoAnalytics.reportPlaybackError(/* string */ message) explicitly.

Implement Metadata

To implement the rest of metadata, refer to the above sections of common pre-defined, pre-defined video, and custom metadata definitions for implementation details.

Handle Application Background and Foreground

Conviva PlayStation WebMAF module autocollects the AppBackground and AppForeground events by monitoring applicationStatus on the applicationStatusChange event.

Because of PlayStation WebMAF behavior, applicationStatusChange event doesn't comes when application goes to background but comes after it comes to foreground but Conviva still recommend to handle background events.
After integrating the video player, review advanced use cases such as live program and playlist changes, fatal errors, and foreground and background actions that can be applicable for specific goals.

Integrate Ad Managers

Conviva core SDK is universal and player agnostic, therefore it can be used to integrate any Ad SDK using the programming language it's written for.

For ease and speed of integration, Conviva also provides plug-in modules for the most common Ad SDKs.

The modules allow to autocollect events from the particular player / Ad SDK.

If instructions for your Ad SDK are not shown below, please follow the instructions for "Custom Ad Manager" integration, or contact your Conviva representative.

Google IMA

Conviva provides the module to autocollect ad events emitted by IMA SDK. Therefore, it's not necessary to report these events explicitly by using core SDK APIs.

Add the Conviva IMA module dependency

You can add the Conviva IMA module dependency by choosing one of the following options:

  • Install using the npm package manager
  • Install using the yarn package manager
  • Download and add the library explicitly from Conviva GitHub

From Google IMA module version 4.0.3 onwards, Conviva supports installation through npm and yarn package managers.

To install using the npm package manager, use:

npm install @convivainc/conviva-js-imasdk --save

To install using the yarn package manager, use:

yarn add @convivainc/conviva-js-imasdk

To download and add the library explicitly from Conviva GitHub, refer: https://github.com/Conviva/conviva-js-imasdk

Refer to this sample code which includes the Google IMA components first followed by Conviva modules.

Via HTML:

<script type="text/javascript" src="//imasdk.googleapis.com/js/sdkloader/ima3.js"></script>
 
<script type="text/javascript" src="<PATH>/conviva-core-sdk.js"></script>
<script type="text/javascript" src="<PATH>/conviva-googleima-module.js"></script>

Via Import/Require:

import Conviva from '@convivainc/conviva-js-coresdk'
import ConvivaGoogleimaModule from'@convivainc/conviva-js-imasdk'
const Conviva = require('<path>/conviva-js-coresdk');
const ConvivaGoogleimaModule = require('<path>/conviva-js-imasdk');

Set Ad Listener to AdAnalytics

To enable Ad metric & metadata autocollection, pass the adsLoader instance of the IMA SDK along with videoPlayer instance, AD_TAG_URL and preload information to adAnalytics:

var info = {};
 
// if adTagurl is known prior
info[Conviva.Constants.AD_TAG_URL] = "adTagUrl";
 
// if preloading is enabled or disabled
info[Conviva.Constants.AD_PRELOAD_FEATURE] = true;

// if conviva admodule is used
info[Conviva.Constants.CONVIVA_MODULE] = ConvivaGoogleimaModule;
 
// Mandatory as IMA SDK requires videoPlayer object to fetch ad manager by module.
// Player object used to play content
info[Conviva.Constants.IMASDK_CONTENT_PLAYER] = videoPlayer;
 
// This API is used to initialise the IMA module and registers listeners for ad playback
adAnalytics.setAdListener(adsLoader, info);

Metrics monitored by Conviva Google IMA module (if applicable):

Key Implementation Note
adAnalytics.reportAdError() **(ASF/APF) The module listens for the ad errors fired by the player using google.ima.AdErrorEvent.Type.AD_ERROR for adsLoader and google.ima.AdErrorEvent.Type.AD_ERROR, google.ima.AdError.Type.AD_LOAD and google.ima.AdError.Type.AD_PLAY for adsManager event callbacks.

To report application level errors impacting user experience, call adAnalytics.reportAdError(/* string */ message) explicitly.

During application backgrounding while an ad is playing, we recommend pausing the ad until the application is moved to the foreground.

Google IMA DAI Module

Conviva provides the module to autocollect ad events emitted by Google IMA DAI SDK. Therefore, it's not necessary to report these events explicitly by using core SDK APIs.

Add the Conviva IMA DAI module dependency

You can add the Conviva IMA DAI module dependency by choosing one of the following options:

  • Install using the npm package manager
  • Install using the yarn package manager
  • Download and add the library explicitly from Conviva GitHub

From Google IMA DAI module version 4.1.0 onwards, Conviva supports installation through npm and yarn package managers.

To install using the npm package manager, use:

npm install @convivainc/conviva-js-daisdk --save

To install using the yarn package manager, use:

yarn add @convivainc/conviva-js-daisdk

To download and add the library explicitly from Conviva GitHub, refer: https://github.com/Conviva/conviva-js-daisdk

Refer to this sample code which includes the Google DAI components first followed by Conviva modules:

Via HTML:

<script type="text/javascript" src="https://imasdk.googleapis.com/js/sdkloader/ima3_dai.js"></script>
 
<script type="text/javascript" src="<PATH>/conviva-core-sdk.js"></script>
<script type="text/javascript" src="<PATH>/conviva-googledai-module.js"></script>

Via Import/Require:

import Conviva from '@convivainc/conviva-js-coresdk'
import ConvivaGoogledaiModule from'@convivainc/conviva-js-daisdk'
const Conviva = require('<path>/conviva-js-coresdk');
const ConvivaGoogledaiModule = require('<path>/conviva-js-daisdk');

Set Ad Listener to AdAnalytics

To enable Ad metric and metadata autocollection, pass the StreamManager and HTMLVideoElement to adAnalytics:

IMPORTANT: Once the StreamManager is created, follow the below instructions for every content playback as the streamManager events are de-registered internally on playback end.

// Code snippet from the html listing the video tag
<div id="video-player">
    <video id="content"></video>
</div>
 
// Code snippet of stream manager initialisation
var videoPlayer = document.getElementById('content');
 
var streamManager = new google.ima.dai.api.StreamManager(videoPlayer);
 
var extraListeners = {};
// Mandatory: HTMLVideoElement to fetch player level events of player state, pht, buffer length and errors by module.
extraListeners[Conviva.Constants.IMASDK_CONTENT_PLAYER] = videoPlayer;

// if conviva admodule is used
extraListeners[Conviva.Constants.CONVIVA_MODULE] = ConvivaGoogledaiModule;
 
// This API is used to initialise the IMA DAI module and registers listeners for ad playback
adAnalytics.setAdListener(streamManager, extraListeners);
 
// Ensure to register the event listeners after the setAdListener() as the order is important for reporting metrics
streamManager.addEventListener([google.ima.dai.api.StreamEvent.Type.STARTED,
    google.ima.dai.api.StreamEvent.Type.FIRST_QUARTILE,
    google.ima.dai.api.StreamEvent.Type.MIDPOINT,
    google.ima.dai.api.StreamEvent.Type.THIRD_QUARTILE,
    google.ima.dai.api.StreamEvent.Type.COMPLETE], function(event) {
        }, false);

Metrics autocollected by Conviva Google IMA DAI module:

Key Implementation Note
Errors(ASF/APF)

The module listens for the ad errors fired by the player using google.ima.dai.api.StreamEvent.Type.ERROR for daiStreamManager and error for HTMLVideoElement event callbacks. Report any error related to the custom MSE implementations in application such as HLS.js errors (Hls.Events.ERROR) explicitly using adAnalytics.reportAdFailed(/* string */ message).

Click to view the reference implementation:

hls.on(Hls.Events.ERROR, function (event, data) {
    if (data.fatal) {
        if (isAdStarted) {
            adAnalytics.reportAdFailed(data.type + ': ' + data.details);
        }
        videoAnalytics.reportPlaybackFailed(
        data.type + ': ' + data.details);
    }
}
Conviva.Constants.Playback.PLAYER_STATE **Autocollected** using HTMLVideoElement callbacks and StreamManager events.
Conviva.Constants.Playback.BITRATE **Report** the information obtained by custom MSE implementations such as HLS.js errors(Hls.Events.LEVEL_SWITCHING), as Google DAI SDK or the HTMLVideoElement doesn't provide the information of bitrate by default.
Setting the bitrate to videoAnalytics will automatically set the bitrate to adAnalytics as well.
**Click to view the reference implementation:**
hls.on(Hls.Events.LEVEL_SWITCHING, function (event, data) {
        convivaVideoAnalytics.reportPlaybackMetric(
        Conviva.Constants.Playback.BITRATE, 
        parseInt(data.bitrate/1000), 
        10));
}
Conviva.Constants.Playback.SEEK_STARTED **Autocollected** using HTMLVideoElement callbacks if the application implementation supports seek during ads.
Conviva.Constants.Playback.SEEK_ENDED **Autocollected** using HTMLVideoElement callbacks if the application implementation supports seek during ads.
Conviva.Constants.Playback.PLAY_HEAD_TIME **Autocollected** using HTMLVideoElement callbacks.
Conviva.Constants.Playback.BUFFER_LENGTH **Autocollected** using HTMLVideoElement callbacks.
Conviva.Constants.Playback.RENDERED_FRAMERATE **Report** if the application implementation supports collecting rendered framerate, as Google IMA doesn't support API for fetching rendered framerate by default.
Conviva.Constants.Playback.CDN_IP **Report** CDN IP address in string format.

Handling the Slate Sessions

Slate session enables you to monitor slates. It is created when an AD_PERIOD_STARTED event triggers, and is set to NOT_MONITORED state to avoid affecting metrics. This session is closed with the occurrence of the AD_PERIOD_ENDED event.

Conviva tracks the slate playback between the AD_PERIOD_STARTED and AD_PERIOD_ENDED events. The AD_PERIOD_STARTED event is triggered before the AD_BREAK_STARTED event, and the AD_PERIOD_ENDED event is triggered after the AD_BREAK_ENDED event.

Metrics are not calculated for slate session, if an AD break does not include slates. Metrics are calculated only when the slate starts playing after the ADs. Notably, there isn't a specific event for slates, apart from AD_PERIOD_STARTED and AD_PERIOD_ENDED.

For more information about the stream events see the Google DAI documentation.

Known IMA DAI Limitations

During application backgrounding while an ad is playing, we recommend pausing the ad until the application is moved to the foreground.

Custom Ad Manager

Report Ad Lifecycle Events

In case of Custom Ad integration, Conviva does not autocollect any ad metrics or events.

Implement the following ad events from your application to Conviva:

  • adAnalytics.reportAdLoaded(/* object */ adInfo) // invoke on ad load complete

  • adAnalytics.reportAdStarted(/* object */ adInfo) // invoke on ad playback start

  • adAnalytics.reportAdFailed(/* string / errorMessage, / object */ adInfo) // invoke when ad fails to load/play

  • adAnalytics.reportAdSkipped() // user skipped the ad

  • adAnalytics.reportAdEnded() // ad playback completed

In the above methods, the parameter adInfo is a map containing the key - value pairs of metadata tags for ad content.

Implement it with respect to the requirements prescribed in the next step.

Implement Ad Metadata

In case of Custom Ad integration, Conviva does not automatically collect ad metadata, except a few fields for common metadata pulled from the videoAnalytics object automatically. Implement the pre-defined common and ad metadata specified in the table below:

Pre-defined Common Metadata:

Key / Constant Type Implementation Note
Conviva.Constants.STREAM_URL string **Report** the manifest URL of the ad stream.
Conviva.Constants.ASSET_NAME string **Report** "ad title" or "[ad_id] ad_title".
Conviva.Constants.IS_LIVE string **Report** the same value as for videoAnalytics
Conviva.Constants.PLAYER_NAME string **Autocollected** from videoAnalytics object - no need to pass for adAnalytics
Conviva.Constants.VIEWER_ID string **Autocollected** from videoAnalytics object - no need to pass for adAnalytics
Conviva.Constants.DEFAULT_RESOURCE string **Report** Ad server resource the stream is played from. Set this field when the video server resource cannot be inferred from the STREAM_URL
Conviva.Constants.DURATION integer **Report** the duration of the single ad clip, in seconds. For example, in a block of 3 ads each 30 seconds long, report 30 sec for each corresponding ad.
Conviva.Constants.ENCODED_FRAMERATE integer **Report** the encoded frame rate of the ad stream in frames per second.
Conviva.Constants.FRAMEWORK_NAME string

Ad Player Framework Name. Report using the adAnalytics.setAdPlayerInfo(/object/ adPlayerInfo):

var adPlayerInfo = {};
adPlayerInfo[Conviva.Constants.FRAMEWORK_NAME] = "YOUR_FRAMEWORK_NAME";
adAnalytics.setAdPlayerInfo(adPlayerInfo);
Conviva.Constants.FRAMEWORK_VERSION string

Ad Player Framework Version. Report using the adAnalytics.setAdPlayerInfo(/object/ adPlayerInfo):

var adPlayerInfo = {};
adPlayerInfo[Conviva.Constants.FRAMEWORK_VERSION] = "1.2.3";
adAnalytics.setAdPlayerInfo(adPlayerInfo);
Conviva.Constants.APPLICATION_VERSION string **Autocollected** as the same value from videoAnalytics - no need to pass for adAnalytics.

Autocollected as the same value from videoAnalytics - no need to pass for adAnalytics.

Pre-defined Ad Metadata:

Key Type Description
"c3.ad.technology" Conviva.Constants.AdType

Set the technology of the ad belongs to.

Allowed values: Conviva.Constants.AdType.CLIENT_SIDE, Conviva.Constants.AdType.SERVER_SIDE.

"c3.ad.id" string The Ad ID extracted from the Ad Server that actually has the ad creative. For wrapper ads, this is the last Ad ID at the end of the wrapper chain. Example: "411687224".
"c3.ad.system" string The name of the Ad System (i.e. the Ad Server). This Ad System represents the Ad Server that actually has the ad creative. For wrapper ads, this is the last Ad System at the end of the wrapper chain. Set to "NA" if not available. Examples: "Freewheel", "Innovid", "Extreme IO", "NA".
"c3.ad.position" Conviva.Constants.AdPosition The position of the ad. Allowed values: Conviva.Constants.AdPosition.PREROLL, Conviva.Constants.AdPosition.MIDROLL, Conviva.Constants.AdPosition.POSTROLL.
"c3.ad.isSlate" string A boolean value that indicates whether this ad is a slate or not. Set to "true" for slate and "false" for a regular ad. By default, set to "false".
"c3.ad.mediaFileApiFramework" string The name of the creative media framework. Generally used for VPAID ads. Set to "NA" for non-VPAID ads. Examples: "VPAID", "NA".
"c3.ad.adStitcher" string The name of the Ad Stitcher. If not using an Ad Stitcher, set to "NA". Examples: "Uplynk", "Google DAI", "Google Anvato", "YoSpace", "NA".
"c3.ad.firstAdSystem" string Only valid for wrapper VAST responses. This tag must capture the "first" Ad System in the wrapper chain when a Linear creative is available or there is an error at the end of the wrapper chain. Set to "NA" if not available. If there is no wrapper VAST response then the Ad System and First Ad System should be the same. Examples: "GDFP", "NA".
"c3.ad.firstAdId" string Only valid for wrapper VAST responses. This tag must capture the "first" Ad Id in the wrapper chain when a Linear creative is available or there is an error at the end of the wrapper chain. Set to "NA" if not available. If there is no wrapper VAST response then the Ad Id and First Ad Id should be the same. Examples: "709684096", "NA".
"c3.ad.firstCreativeId" string Only valid for wrapper VAST responses. This tag must capture the "first" Creative Id in the wrapper chain when a Linear creative is available or there is an error at the end of the wrapper chain. Set to "NA" if not available. If there is no wrapper VAST response then the Ad Creative Id and First Ad Creative Id should be the same. Examples: "57861167296", "NA".
"c3.ad.creativeId" string The creative id of the ad. This creative id is from the Ad Server that actually has the ad creative. For wrapper ads, this is the last creative id at the end of the wrapper chain. Set to "NA" if not available. Examples: "57861167296", "NA".

Report Ad Metrics

Report Ad-video metrics to adAnalytics by using adAnalytics.reportAdMetric(/* Conviva.Constants.Playback / key, / integer | string | long | Conviva.Constants.PlayerState */ value...):

  • key: Conviva.Constants.Playback type.

  • val: It accepts multiple/zero values for the second argument.

adAnalytics.reportAdMetric(Conviva.Constants.Playback.BITRATE, 1024);

Refer to the list of metric keys to be implememted in the table below:

Key Type Implementation Note
Conviva.Constants.Playback.PLAYER_STATE *Conviva.Constants.PlayerState* **Report** any player state changes such as Playing, Buffering, Paused shall be reported to CONVIVA SDK.
Conviva.Constants.Playback.BITRATE *int (kbps)* **Report** new bitrate value on change event (video + audio, or video only if audio isn't available).
Conviva.Constants.Playback.SEEK_STARTED *Optional: int (ms)* **Report** start of seeking or scrubbing by user. If seek position is known, report as the method argument.
Conviva.Constants.Playback.SEEK_ENDED no argument **Report** end of seeking or scrubbing by user.
Conviva.Constants.Playback.PLAY_HEAD_TIME *long (ms)* **Report** current playback position.
Conviva.Constants.Playback.BUFFER_LENGTH *long (ms)* **Report** current buffer length of the player.
Conviva.Constants.Playback.RENDERED_FRAMERATE *long (fps)* **Report** rendered framerate in fps.
Conviva.Constants.Playback.CDN_IP string (IP address) Report CDN IP address in string format.

API Diagrams for Custom Ad Integration

Conviva Ad modules autocollect most of the metrics and metadata. For more details, contact your Conviva representative.

5. Handle User Actions

Conviva.Analytics.reportAppForegrounded();
Conviva.Analytics.reportAppForegrounded();
videoAnalytics.reportPlaybackEvent(Conviva.Constants.USER_WAIT_STARTED);
videoAnalytics.reportPlaybackEvent(Conviva.Constants.USER_WAIT_ENDED);

Report Network Metrics

Metrics like connection type which is common for all the concurrent playback within one Analytics instance can be reported.

Connection Type can be updated after session creation, before the first video frame is rendered.

Conviva.Analytics.reportDeviceMetric(/* Conviva.Constants.Network / metricKey, / string */ metricValue):

  • metricKey: Conviva.Constants.Network type key for reporting Network Metrics.

  • metricValue: Value of the reported network metric.

Refer to the sample code mentioned below:

Conviva.Analytics.reportDeviceMetric(Conviva.Constants.Network.CONNECTION_TYPE, "WiFi");

Data Collection and User Preferences

By default, Conviva does not collect any sets of data and relies on the customer application to pass relevant data for better user analytics. However, the appropriate legal agreement with Conviva is required in order for Conviva to begin collecting data that would be considered PII, personal information, personal data or the like under applicable data privacy laws such as the General Data Protection Regulation (GDPR) and the California Consumer Privacy Act (CCPA). Further below in this document, there is a description of the user-preference APIs that control data collection, including opt-out and deletion of data, in compliance with data privacy laws. These APIs are in addition to existing, offline processes for opt-out and data deletion requests.

Use these APIs to set the unique user identifiers, however actual collection of identifiers are contingent upon the customer's legal department providing written instructions to Conviva to begin collection. At the discretion of the customer's legal department, some or all of these identifiers may be collected. Conviva provides this flexibility to allow the customer to determine the precise identifiers to be collected.

Send unique identifier's data such as unique identifier for a device or user, for example deviceId, Mac address, advertisingIdentifier and other identifiers, use the Conviva.Analytics.setUniqueIdentifier(/* object / identifiers, / function */ callback=):

  • identifiers: JSON object with key value pairs of identifiers and values.

  • callback: Optional callback function that needs to be notified if the identifiers were honored or collected by Conviva.
    Below mentioned are the sample result messages from Conviva:
    "Data collection successful"*
    *"End-user chose to opt-out of personal data collection"

    "End-user used privacy settings and chose to opt-out of personal data collection"

Control Data Collection and Delete Collected Data

var identifiers = {};
identifiers["androidId"] = "xyzabd123cvqn";
Conviva.Analytics.setUniqueIdentifier(identifiers, function (msg) {
    console.log("Result of the setUniqueIdentifier API:" + msg);
});

Set the user preference to collect or stop collecting PII data items using Conviva.Analytics.setUserPreferenceForDataCollection(/* object / identifiers, / boolean */forAllApps):

  • identifiers:string key/value pair, where key indicates a probable data name and value is false/true. A value of false causes the SDK to stop collecting that specific data item.

  • forAllApps:boolean value indicates if the preference applies to current app or all apps on the device. A value of true indicates all apps; false indicates only the current app.

Control the data collection

var identifiers = {};
identifiers["androidId"] = "false";
Conviva.Analytics.setUserPreferenceForDataCollection(identifiers, false);

Set the user preference to delete and stop collecting specific data items using Conviva.Analytics.setUserPreferenceForDataDeletion(/* object */ identifiers):

identifiers: string key/value pair, where key indicates a probable data name and value is false/true. A value of false causes the SDK to stop collecting that specific data item.

Delete collected data

var identifiers = {};
identifiers["androidId"] = "true";
Conviva.Analytics.setUserPreferenceForDataCollection(identifiers);

Report Custom Events

Player Insight is an advanced feature which allows you to track custom events that are not related to video rendering, but rather specific to your player's functionality. These events and their attributes are then tabulated in the Player Insight dashboard at Conviva VSI (Pulse). Contact your Conviva representative to enable Player Insights in Pulse.

You may send a custom Player Insight event that can be associated with a video playback using the following method:

Report video-related events by the method videoAnalytics.reportPlaybackEvent(/* string / eventType, / object */ eventDetail=):

  • eventType: Mandatory argument of event type of the video player event of string type.

  • eventDetail: Optional argument of event details of the video player event of object type.

Report video-related events

// Sample code snippet illustrating event on explicit change of video quality in the player
var eventType = "fullscreen";
var attr = {};
attr["old_quality"] = "SD";
attr["new_quality"] = "HD";
attr["player"] = "WEB player";
videoAnalytics.reportPlaybackEvent(eventType, attr);

Report app-level events by the method Conviva.Analytics.reportAppEvent(/* string / eventType, / object */ eventDetail=):

  • eventType: Mandatory argument of event type of the app event of string type.

  • eventDetail: Optional argument of event details of the app event of object type.

Report app-level events

// Sample for "share-click" event with 3 attributes
var eventType = "share-click";
var attr = {};
attr["location"] =  "Toolbar";
attr["assetName"] = "Sample Video";
attr["shareService"] = "Facebook";
Conviva.Analytics.reportAppEvent(eventType, attr);

6. Cleanup

At video playback end, call

videoAnalytics.reportPlaybackEnded();

For Ad content, call

// Only applicable for custom ad integration, don't call for modules
adAnalytics.reportAdEnded();

On application exit, or when the Conviva object is destroyed, release the objects

adAnalytics.release(); // if initialized
videoAnalytics.release();
Conviva.Analytics.release();

To know about the advanced use cases and the self-validation process, refer to the Conviva JavaScript Sensor Integration page.