Roku SDK Developer Guide

In this topic, you will learn how to set the Brightcove Roku SDK.

Overview

The Brightcove Roku SDK is a Roku ComponentLibrary package that can be imported and loaded into a Roku channel, allowing easy access to Brightcove’s Playback services in a Roku channel through a set of Brightscript components.

Index

Features

The Brightcove Roku SDK package has the following features:

Future additions

  • TVe support
  • Google IMA DAI support
  • Custom trickplay UI/UX support

Sources Refresh

Brightcove video sources have a Time To Live (TTL) timestamp associated with it which, once expired, video playback will not be possible through that source. The bcPlayer automatically checks for sources TTL expiration in the following situations:

  • When starting a video playback for the first time.
  • When switching to a previous or next video in a playlist.

If a Brightcove video source is detected to be expired, it’ll be automatically refreshed by:

  1. Retrieving updated source URL from the Playback API.
  2. Reset the video url ContentNode field. Keep in mind this step may trigger any bcPlayer.content observing functions.

Once the video sources are updated, bcPlayer will resume the requested action (next/previous, play the requested video, load CSAI/SSAI handlers, complete the ongoing metadata loading process) with the updated sources in place.

Voice Controls

Allows users to control the video playback through voice commands. These voice commands are captured by a supported Roku Remote Control as well as the Roku mobile app and sent to the Roku app. With the OOTB Roku UI most of these commands are handled natively. With a custom UI experience the Brightcove SDK will automatically handle the commands. Learn more.

OOTB UI/UX

  • Basic Commands.
    • play - Start playback if paused or stopped / resume playback if paused.
    • pause - Pause playback.
    • ok - Pause / resume playback.
    • replay - Rewind playback 10 to 25 seconds (time depends on application's implementation).
    • rewind - Rewind playback until another command is received and processed.
    • forward - Fast forward playback until another command is received and processed.
  • Enhanced commands.
    • start over - Start playback from the beginning.
    • seek - Skip playback forwards or backwards by the specified time.
    • next - Play next video when having a playlist.

Brightcove Generic Stream Concurrency

The Generic Stream Concurrency allow users to limit stream concurrency using a heartbeat mechanism without the need for DRM. Generic Stream Concurrency allows you to specify the maximum number of video streams a particular user can watch simultaneously. Limiting stream concurrency will help the user to prevent their content being stolen or illegally watched through the theft or inappropriate sharing of credentials.

In order for the Generic Stream Concurrency feature to work, a JWT must be provided in the bcPlayer.credentials.auth_token property and the bcPlayer.enableGsc flag must be enabled.

Brightcove Analytics

The following events and their respective fields will be sent automatically to Brightcove by the SDK. The end user can provide the information for most of the fields in each event. Alternatively, the SDK will attempt to build it and include it in the events. Otherwise, some fields won't be sent. Learn more.

Events

  • player_init: Sent when the player is initialized.
  • player_load: Sent when the player is initialized.
  • video_impression: Sent when the metadata for a video added to the player finishes loading and the player is ready to start video playback, either via auto-play or user interaction.
  • play_request: Sent when the user presses to play the asset. (once per session per media stream).
  • video_view: Sent when the first frame of the video starts (applies to the video content. If a pre-roll is present, the video_view is triggered as soon as the pre-roll ends).
  • video_engagement: Sent periodically every 10 seconds while video content is playing, or sooner if playback is interrupted for any reason.
  • ad_mode_begin: Sent when an ad break starts.
  • ad_mode_complete: Sent when an ad break finishes.
  • error: Sent when a playback error occurs.
  • catalog_request: Sent when a request to the Playback API is triggered (through bcPlayer only).
  • catalog_response: Sent on a successful Playback API response.
  • catalog_request_error: Sent on an error Playback API response.

Metrics

  • sesion: random UUID representing the unique session ID.
  • domain: videocloudvideocloud for Brightcove sources, external for other sources.
  • account: Brightcove Account ID. Uses bcPlayer.credentials.account_id value by default but it can be overridden through the bcPlayer.analytics.accountId field.
  • time: event timestamp.
  • device_os: hardcoded to roku.
  • device_manufacturer: specifies the Roku device vendor name (as per GetModelDetails()).
  • device_os_version: specifies the Roku OS version (as per GetOSVersion()).
  • seq: specifies the sequence of events per session, in the following format: <#-of-events>_<#-of-streams>.
  • device_type: hardcoded to tv.
  • user: OPTIONAL specifies the user identification for Viewer Analytics purposes. The user is also required to use Brightcove’s Cross-Device Resume feature. This value should be provided through the bcPlayer.analytics.user field.
  • destination: OPTIONAL value of bcPlayer.analytics.destination, if provided.
  • source: OPTIONAL value of bcPlayer.analytics.source, if provided.
  • player: player identification. Defaults to: players.brightcove.com/<bc_account_id>/player. Some analytics configurations may be used to customize this parameter, as follows:
    • if bcPlayer.analytics.playerID is provided: players.brightcove.com/<bc_account_id>/<playerID>
    • if bcPlayer.analytics.applicationID is provided: players.brightcove.com/<bc_account_id>/<playerID><applicationID>
  • player_name: OPTIONAL depends on the analytics configurations provided:
    • if only bcPlayer.analytics.playerName is provided: uses the value provided.
    • if only bcPlayer.analytics.applicationID is provided: uses the value provided.
    • if both are provided: uses playerName-applicationID.
  • platform_version: specifies the bcPlayer.sdkVersion value.
  • video: specifies the video ID (this value is retrieved from the video ContentNode.id field).
  • video_name: specifies the video name (this value is retrieved from the video ContentNode.title field).
  • video_duration: specifies the video duration (this value is retrieved from the video ContentNode.length field).
  • rendition_url: specifies the video URL (this value is retrieved from the video ContentNode.url in case of HLS/DASH playback or from bcPlayer.streamingSegment in case of MP4 playback).
  • rendition_indicated_bps: specifies the stream bitrate (this value is retrieved from bcPlayer.streamingSegment and bcPlayer.downloadedSegment).
  • rendition_mime_type: specifies the stream mime-type based on the video ContentNode.streamFormat field.
  • rendition_height: specifies the rendition height (this value is retrieved from bcPlayer.streamingSegment and bcPlayer.downloadedSegment).
  • rendition_width: specifies the rendition width (this value is retrieved from bcPlayer.streamingSegment and bcPlayer.downloadedSegment).
  • rebuffering_seconds: specifies the rebuffering duration measured during the buffering state of bcPlayer.
  • rebuffering_count: specifies the number of rebufferings in a playback session.
  • forward_buffer_seconds: specifies the start time of the segment from the start of the video (this value is retrieved from bcPlayer.downloadedSegment).
  • measured_bps: specifies the ratio of the number of bits included in the most recently downloaded segment to the time spend downloading that segment, in bits per second. Calculated from the data provided by bcPlayer.downloadedSegment.
  • player_width: specifies the player width as per the bcPlayer.width field.
  • player_height: specifies the player height as per the bcPlayer.height field.
  • dropped_frames: specifies the number of frames that have been dropped since playback was started (this value is retrieved from bcPlayer.decoderStats).
  • remote_ip: specifies the Roku device external IP address.
  • user_agent: specifies Roku's user-agent value as per roUrlTransfer.GetUserAgent().
  • platform: hardcoded to "roku-sdk".
  • media_type: hardcoded to "video".
  • delivery_type: "ondemand" for VOD, "live" for live streams.
  • start_time_ms: specifies the video playback start time.
  • load_time_ms: specifies the video load time.

Ad Insights

Ad insights helps understand the impact of ad monetization on audience's engagement by showing the relationships between ad frequency/intensity and session length/frequency to help understand the most effective ad loads.

The following events and metrics are supported in the Roku SDK. Since some of the metric values are retrieved from the VAST/VMAP file provided, it’s possible that some metrics are not sent if their values can’t be found. Learn more

Events

  • ad_mode_begin: Sent when the ad pod begin.
  • ad_error: Sent when there was an error during ad mode.
  • ad_begin: Sent when an ad within the pod has begun.
  • ad_viewable_impression: Sent per the MRC Viewability Standards. (The ad must be at least 50% visible on the screen for two consecutive seconds. These do not have to be the first two seconds, but can be any two seconds during the ad’s playback).
  • ad_complete: Sent when an ad within the pod has ended.
  • ad_mode_complete: Sent when the ad pod has ended.
  • video_resumed: Sent when the content playback has resumed. (This is only send following mid-rolls).

Metrics

  • ads_pod_index: Specifies the index of the pod relative to the content.
  • ads_pod_ad_count: Specifies the number of ads in the current pod.
  • ads_pod_duration: Specifies the total number of seconds the ad pod is expected to run.
  • ads_pod_host: Host name from the ad server URL called to return the ad pod.
  • ads_pod_type: Specifies the type of the pod (pre, mid, post).
  • ads_pod_request_ms: Milliseconds from ad request sent to ad request received.
  • ads_pod_request_mode: Specifies how ads were requested.
  • ads_pod_time_offset: Specifies the content time offset at which the current ad pod was scheduled.
  • ads_ad_index: Specifies the position of the ad relative to the pod.
  • ads_ad_system: Specifies source ad server information included in the ad response.
  • ads_ad_advertiser: Specifies the advertiser name as defined by the serving party.
  • ads_ad_isci: Specifies the CI (Industry Standard Commercial Identifier) code for an ad. Currently we are attributing the adId.
  • ads_ad_creative_id: Specifies the ID of the selected creative for the ad.
  • ads_ad_duration: Specifies the duration in seconds of the selected ad.
  • ads_ad_title: Specifies the ad title from the VAST response.
  • ads_ad_audible_duration: Specifies the number of seconds of ad playback where volume was >= 1% and not muted.
  • ads_ad_play_duration: Specifies the number of seconds of ad media played.
  • ads_ad_skipped: Specifies if the ad was skipped.
  • ads_ad_interaction: Specifies if the ad was interacted.

Sample App

The Roku SDK Sample App provides a set of Roku SDK application examples to help you learn about the Roku SDK components and features in a practical environment.

The README.md file provides all the details on how to set it up, configure, customize and launch

Setup

To setup Brightcove Roku SDK in a Roku channel you first need to request access to the SDK package file. Since Roku’s ComponentLibrary allows packages to be imported and loaded both locally and remotely into a Roku channel, Brightcove provides two different ways for developers to gain access to the SDK package file.

Package Sources

The Roku SDK library package sources can be obtained from https://players.brightcove.net/roku-sdk. Since Roku SDK releases use Semantic Versioning, the URL endpoint will vary depending on what release version of interest. It’s possible to obtain specific versions of the Roku SDK package like so:

        
    https://players.brightcove.net/roku-sdk/{MAJOR-VERSION}.{MINOR-VERSION}.{BUILD-VERSION}/roku-sdk.pkg
        
      

Where MINOR-VERSION and BUILD-VERSION are optional, but MAYOR-VERSION is always required.

A full list of available Roku SDK versions is included in the changelog.

Brightcove always recommends the latest Roku SDK version, but if you have specific need of a version, you can specify version numbers in the URL.

For example, if we assume that these versions were available:

  • 1.0.0
  • 1.0.1
  • 1.2.0
  • 1.2.1
  • 1.2.2
  • 1.2.3
  • 2.0.0

The following examples specify how the Roku SDK packages could be retrieved based on the requested version:

  • https://players.brightcove.net/roku-sdk/1/roku-sdk.pkg - refers to the most recent version in the v1 major release. In this example, it would refer to the v1.2.3 release.
    • Keep in mind that if the v1.2.4 or v1.3.0 versions were released, this endpoint would retrieve those packages instead.
  • https://players.brightcove.net/roku-sdk/1.0/roku-sdk.pkg - refers to the most recent version in the v1.0 minor release. In this example, it refers to the v1.0.1 release.
  • https://players.brightcove.net/roku-sdk/1.2.3/roku-sdk.pkg - in this case, refers to the v1.2.3 release.

It’s also possible to retrieve the most recent version of the Roku SDK library package from the following endpoint:

Changelog

The changelog can be retrieved from the following endpoint. A full list of available Roku SDK versions is included.

Loading the library directly from the source

In this case the Roku SDK package URL can be set directly into the ComponentLibrary uri field. The ComponentLibrary node will handle the package file download and loading process automatically. For example, to load the latest v1 major release into a Roku channel, you can follow these steps:

  1. In the scene XML component, create the ComponentLibrary node and set its id and uri fields.

    • The uri field contains the SDK package URL.

    • The id field is used during the library components initialization.

                    <?xml version="1.0" encoding="utf-8" ?> 
                        <component name="MainScene" extends="Scene">
                            <interface>
                                <!-- your mainscene fields here -->
                            </interface>
                            <script type="text/brightscript" uri="MainScene.brs"/>
                            <children>
                                <ComponentLibrary id="bcLib" uri="https://players.brightcove.net/roku-sdk/1/roku-sdk.pkg" />
                            </children>
                        </component>
                    
  2. In the init() function of the Scene's brightscript file, set up the ComponentLibrary reference and an observer for the loadStatus field so you can detect when the SDK library is successfully downloaded and ready to be referenced.
                    sub init()
                        m.bcLib = m.top.findNode("bcLib")
                        m.bcLib.observeField("loadStatus", "onLoadStatus")
                    end sub
                    
                    sub onLoadStatus(ev)
                        status = ev.getData()
                        if status = "ready" then
                        
                            ' bcLib was successfully downloaded and all its components are now accessible
                        
                        else if status = "loading" then
                        
                            ' bcLib package is currently being downloaded
                        
                        else if status = "failed" then
                        
                            ' Something went wrong with the bcLib download/load process. 
                            ' Please check if the package URL was properly set.
                        
                        end if
                    end sub
                    

Loading the library locally

In this case, you should manually download the Roku SDK package file from Brightcove sources and embed it into a Roku channel. In this process the library is simply loaded from the internal channel’s file structure at runtime. This is the recommended approach as it’s much faster and efficient than letting ComponentLibrary download and load the SDK package. For this approach, the following steps can be taken:

  1. Download the SDK package manually.
  2. Place the SDK package in the Roku channel file structure (feel free to rename the file, in this case we named it bcLib.pkg). The exact location doesn't matter. In the following example, it was placed in the lib directory.
    Loading the roku library locally
  3. In the scene XML component, create the ComponentLibrary node and set the id and uri fields.
    • The uri field contains the bcLib.pkg file local path.
    • The id field is used during the library components initialization.
                    <?xml version="1.0" encoding="utf-8" ?> 
                        <component name="MainScene" extends="Scene">
                            <interface>
                                <!-- your mainscene fields here -->
                            </interface>
                            <script type="text/brightscript" uri="MainScene.brs"/>
                            <children>
                                <ComponentLibrary id="bcLib" uri="pkg:/lib/bcLib.pkg" />
                            </children>
                        </component>
                    
  4. In the scene's init() function of the Scene's brightscript file, set up the ComponentLibrary reference and an observer for the loadStatus field so you can detect when the SDK library is successfully loaded.
                    sub init()
                        m.bcLib = m.top.findNode("bcLib")
                        m.bcLib.observeField("loadStatus", "onLoadStatus")
                    end sub
                    
                    sub onLoadStatus(ev)
                        status = ev.getData()
                        if status = "ready" then
                        
                            ' bcLib was successfully downloaded and all its components are now accessible
                        
                        else if status = "loading" then
                        
                            ' bcLib package is currently being downloaded
                        
                        else if status = "failed" then
                        
                            ' Something went wrong with the bcLib download/load process. 
                            ' Please check if the package URL was properly set.
                        
                        end if
                    end sub
                    

Loading the library dynamically

It’s recommended to set the ComponentLibrary in the scene’s children section with the proper package URL so that the library loading process starts immediately during the Scene initialization, but depending on the use case, it could also be useful to be able to dynamically load the library anywhere in the channel. This can be done by initializing the ComponentLibrary node in the brightscript code as such:

        sub init()
            ' this can be placed anywhere in the Scene node code, 
            ' although usually we want it to load as soon as possible so we can immediately access its components

            m.bcLib = createObject("roSGNode", "ComponentLibrary")
            m.bcLib.observeField("loadStatus", "onLoadStatus")
            m.bcLib.id = "bcLib"
            m.bcLib.uri = "<path_or_url_to_the_pkg_file>"
        end sub
        

This allows you to control where and when exactly they want to load the Roku SDK library package into their Roku channel.


Accessing Roku SDK components

Once the SDK library is successfully loaded (ie, the ComponentLibrary loadStatus field is ready), an instance of any of its components can be created like so:

        ' creating an instance of the bcPlayer component from the bcLib library

 ' 1 - create an instance of the bcPlayer node
 ' This won't make the bcPlayer node visible in the app, it still needs to be added to the node tree list after this step 
 m.bcPlayer = createObject("roSGNode", "bcLib:bcPlayer") 

 ' 2 - create an instance of the bcPlayer node and append it to the parentNode node.
 ' If parentNode is already in the node tree list and is visible, this will also make the bcPlayer node visible in the app 
 m.bcPlayer = parentNode.createChild("bcLib:bcPlayer")
         

In place of the usual SGNode component name (in the createObject and createChild functions), an external library component must be referred as: “ <ComponentLibrary-id> : <component-name> ".

bcPlayer component

The bcPlayer component is the main SDK node as it enables both Brightcove sources and external sources video playback in Roku channels. This node essentially extends Roku’s native Video node, allowing all its fields to be easily accessed for further customization options. It is possible to configure the appearance of some elements in the node as well as some behaviors and flows by customizing the node fields values.

An instance of this node can be created like so:

    
        m.bcPlayer = createObject("roSGNode", "bcLib:bcPlayer")
    

Once an instance of the node is available, it’s possible to customize it by setting up its fields. All the fields default values are listed below.

        m.bcPlayer = createObject("roSGNode", "bcLib:bcPlayer")
 m.bcPlayer.observeField("on", "onEvent") ' read-only field
 m.bcPlayer.observeField("adPlaying", "onAdPlaying") ' read-only field
 m.bcPlayer.setFields({
   streamPreference: ["hls", "dash", "mp4"],
   drmPreference: ["widevine", "playready", "none"],
   width: 1920, ' current UI width
   height: 1080, ' current UI height
   logLevel: 0,
   credentials: invalid,           
   env: "production",
   watermarkToken: "",
   spinnerConfig: {},
   closeOnBack: "hard",
   closeOnFinished: "hard",
   retryOnError: true,
   retryOnBufferTimeout: false,
   enableDialogs: true,
   enableGsc: false,
   bufferTimeout: 0,
   dialogTheme: {
     DialogBackgroundColor: "#00000000",
     DialogSecondaryItemColor: "#00000000"
   }
 }) 

 playback = m.bcPlayer.playback
 playback.observeField("index", "onIndex") ' read-only field
 playback.setFields({
   loop: false,
   autoPlayNext: false
 }) 

 analytics = m.bcPlayer.analytics
 analytics.observeField("eventOut", "onAnalyticsEvent") ' read-only field
 analytics.setFields({
   accountId: ""
   url: ""
   applicationID: ""
   env: ""
   playerId: ""
   playerName: ""
   accountId: ""
   user: ""
   destination: ""
   source: ""
 }) 

 ssai = m.bcPlayer.ssai
 ssai.observeField("event", "onSSAIEvent") ' read-only field
 ssai.setFields({
   enabled: false
   enableDiscontinuities: true
   adMeasurements: {}
   bcovToken: ""
   macros: {}
 }) 

 csai = m.bcPlayer.csai
 csai.observeField("event", "onCSAIEvent") ' read-only field
 csai.setFields({
  enabled: false
   maxRequests: 5
   adMeasurements: {}
   adConstraints: {}
 })
         

Fields

The bcPlayer node is configured through a set of fields. Since it extends the native Video node, all native fields are also accessible; these can be checked out in Roku documentation.

The following tags are used in this section to make the identification of the different types of fields easier.

  • <VALUE_TYPE> Specifies the expected type of a field value or ASSOCIATIVE ARRAY key value (e.g., string, float, integer…).

  • OPTIONAL Specifies an optional field or ASSOCIATIVE ARRAY key. If an optional field isn’t specifically set, the DEFAULT value is be used.

  • REQUIRED Specifies that a field or ASSOCIATIVE ARRAY key is required (write-only properties) or is always present (read-only properties). If a required field is not set, an error message will be presented in the built-in logger.

  • DEFAULT Specifies the default value of a field or ASSOCIATIVE ARRAY key.

  • NATIVE Identifies a native field. These fields are aliases or references of a native Roku node fields. Roku documentation should be consulted for a more detailed description of these fields.

  • CONTROL Identifies fields that can control the video playback in any way.


Credentials

ASSOCIATIVE ARRAY OPTIONAL

Configures Brightcove API credentials. It should contain the account ID as well as the policy key. These are used to retrieve video metadata from the Brightcove Playback or EPA API.

If the credentials aren’t provided, the bcPlayer node will only be able to playback videos from external sources through the bcPlayer.loadCustom function.

Possible Values:

An ASSOCIATIVE ARRAY containing the following keys:

  • account_id STRING REQUIRED

    • Specifies Brightcove API user account ID.

  • policy_key STRING OPTIONAL

    • Specifies the user policy key required to access the Playback API.

  • auth_token STRING OPTIONAL

    • Specifies the JSON Web Token required to:

      • Provide Playback Restriction rules (Playback Rights) through Edge Playback Authorization (EPA).
      • Specify License Keys Protection for HLSe content playback.
      • Enable the Generic Stream Concurrency feature.

Code Snippet

                m.bcPlayer = createObject("roSGNode", "bcLib:bcPlayer")
 m.bcPlayer.credentials = {
   account_id: "<brightcove_user_account_id>"
   policy_key: "<brightcove_user_policy_key>"
   auth_token: "<brightcove_user_auth_token>"
 }
 
 ' or
 
 m.bcPlayer.setFields({
   ' ...other fields here...
   credentials: {
     account_id: "<brightcove_user_account_id>"
     policy_key: "<brightcove_user_policy_key>"
     auth_token: "<brightcove_user_auth_token>"
   }
 })
                

watermarkToken

STRING OPTIONAL

Configures the Forensic Watermarking token, which is required when playing watermarked encoded Brightcove sources.

Playing a watermarked video without the watermarkToken field properly set will result in a playback error.

Please check Videocloud documentation for more information on Forensic Watermark.

Possible Values:

  • A string containing the Forensic Watermarking token.

  • "" DEFAULT

Code Snippet

                m.bcPlayer = createObject("roSGNode", "bcLib:bcPlayer")
 m.bcPlayer.watermarkToken = "<forensic_watermarking_token>"
 
 ' or
 
 m.bcPlayer.setFields({
   ' ...other fields here...
   watermarkToken: "<forensic_watermarking_token>"
 })
                

streamPreference

ARRAY OPTIONAL

Configures sources types/containers preferences ordered by the priority each type/container will have when filtering the available video sources.

This allows you to setup the bcPlayer so that only certain stream types/containers are used or ignored, and the order in those sources will be filtered.

Playing a video in which no sources are listed in the streamPreference field will result in an error.

Find more information on how the sources are parsed and filtered in the Sources Selection section.

Possible Values:

An array containing any combination of the following values:

  • hls

  • dash

  • mp4

  • DEFAULT ["hls", "dash", "mp4"]

Code Snippet

                m.bcPlayer = createObject("roSGNode", "bcLib:bcPlayer")
 m.bcPlayer.streamPreference = ["dash"]  ' will only playback DASH sources
 
 ' or
 
 m.bcPlayer.setFields({
   ' ...other fields here...
   streamPreference: ["dash", "mp4"] ' will play DASH sources. If no DASH source is availble, will play MP4 sources
 })
                

drmPreference

ARRAY OPTIONAL

Configures DRM encryption systems preferences ordered by the priority each DRM system will have when filtering the available video sources.

This allows developers to setup the bcPlayer so that only certain DRM encrypted sources are used or ignored and the order in which the sources will be filtered through.

Playing a video in which no DRM encrypted sources are listed in the drmPreference field will result in an error. The none value forces the selection of sources with no DRM encryption.

Find more information on how the sources are parsed and filtered in the Sources Selection section.

Roku DRM reference

Videocloud DRM reference

Possible Values:

An array containing any combination of the following values:

  • widevine Supported on HLS and DASH sources only.

  • playready Supported on DASH sources only, ignored on HLS sources.

  • none

  • DEFAULT ["widevine", "playready", "none"]

Code Snippet

                m.bcPlayer = createObject("roSGNode", "bcLib:bcPlayer")
 m.bcPlayer.streamPreference = ["none"]  ' play sources with no DRM encryption only
 
 ' or
 
 m.bcPlayer.setFields({
   ' ...other fields here...
   streamPreference: ["playready", "widevine"] ' play a DASH source encrypted with Playready DRM and, if not available, play a Widevine encrypted source instead
 })
                

logLevel

INTEGER OPTIONAL

Configures the logging level on the bcPlayer node. Only the specified messages will be triggered.

If set to -1 no logging messages will be triggered. In a production environment it's recommended to set it to -1 to avoid the execution of the logging internal functions.

Possible Values:

  • -1 disable all the logging.

  • 0 DEFAULT log error messages only.

  • 1 log error and warning messages.

  • 2 log error, warning and info messages.

  • 3 log error, warning, info and debug messages.

  • 4 log error, warning, info, debug and verbose messages.

Code Snippet

                m.bcPlayer = createObject("roSGNode", "bcLib:bcPlayer")
 m.bcPlayer.logLevel = 3
 
 ' or
 
 m.bcPlayer.setFields({
   ' ...other fields here...
   logLevel: 3
 })
                

spinnerConfig

ASSOCIATIVE ARRAY OPTIONAL

Configures the custom loading spinner appearance.

When using Roku’s native Video node UI/UX, this spinner is only visible during the execution of API requests, as the native Video node contains its non-customizable loading spinner, which is visible during buffering operations.

Possible Values:

An Asociantive Array with the following optional keys:

  • URL STRING OPTIONAL

    • Specifies the spinner image path

    • DEFAULT Internal PNG image path which looks like so:

      Loading the roku library locally
  • size INTEGER/FLOAT OPTIONAL

    • Specifies the size (width and height values) of the spinner image.

    • DEFAULT 120

  • color STRING OPTIONAL

    • Specifies the color of the spinner image, which is set through the blendColor Poster field.

    • DEFAULT ""

  • clockwise BOOLEAN OPTIONAL

    • Specifies the image spinning direction, true for clockwise rotation and false for counter-clockwise rotation.

    • DEFAULT true

  • interval INTEGER/FLOAT OPTIONAL

    • Specifies the number of seconds to complete a 360-degree rotation of the spinner image. A value of 0 will cause the spinner to remain stationary and not spin.

    • DEFAULT 1

  • opacity INTEGER/FLOAT OPTIONAL

    • Specifies the spinner image opacity with a value between 0 and 1.

    • DEFAULT 1

Code Snippet

                m.bcPlayer = createObject("roSGNode", "bcLib:bcPlayer")
 m.bcPlayer.spinnerConfig = {
   url: "pkg:/my/spinner/image.png"
   size: 200
   color: "#d32228"
   clockwise: false  ' counterclockwise rotation
   interval: 0.8     ' completes a 360 rotation in 800 miliseconds
   opacity: 0.8      ' sets an opacity of 80%
 }
 
 ' or
 
 m.bcPlayer.setFields({
   ' ...other fields here...
   spinnerConfig: {
     url: "pkg:/my/spinner/image.png"
     size: 200
     color: "#d32228"
     clockwise: false  ' counterclockwise rotation
     interval: 0.8     ' completes a 360 rotation in 800 miliseconds
     opacity: 0.8      ' sets an opacity of 80%
   }
 })
                

loading

BOOLEAN OPTIONAL

Controls the custom loading spinner visibility. This field is used by internal functions but it also allows the custom spinner to be controller externally if needed.

Keep in mind that

  • The OOTB UI has its own loading spinner. This field is independent from the OOTB UI built in loading spinner.
  • Internal bcPlayer functions will automatically toggle the loading field value depending on what operations are being executed.

The appearance of the loading spinner can be customized through the spinnerConfig field.

Possible Values:

  • false DEFAULT Hide the custom loading spinner.

  • true Show the custom loading spinner.

Code Snippet

                m.bcPlayer = createObject("roSGNode", "bcLib:bcPlayer")
 m.bcPlayer.loading = true
 
 ' or
 
 m.bcPlayer.setFields({
   ' ...other fields here...
   loading: true
 })
                

retryOnError

BOOLEAN OPTIONAL

Toggles the retry on error feature which, when enabled, allows bcPlayer to automatically retry video playback with a different video source if a playback error is triggered during the initial video buffering process.

If all the available video sources fail to play an error will be triggered.

The retry on error flow follows the sources type and DRM encryption preferences/priorities set in the bcPlayer.streamPreference and bcPlayer.drmPreference fields.

This flow is only relevant at the initial source loading, ie, a playback error triggered mid-playback will not trigger the retry on error flow.

This feature is not applicable to CSAI videos.

Possible Values:

  • false Disables the retry on error flow.

  • true DEFAULT Enables the retry on error flow.

Code Snippet

                m.bcPlayer = createObject("roSGNode", "bcLib:bcPlayer")
 m.bcPlayer.retryOnError = false
 
 ' or
 
 m.bcPlayer.setFields({
   ' ...other fields here...
   retryOnError: false
 })
                

retryOnBufferTimeout

BOOLEAN OPTIONAL

Configures the retry on buffer timeout feature which, when enabled, allows bcPlayer to automatically retry video playback with a different video source when a buffering timeout error occurs.

If the bcPlayer.bufferTimeout configuration is disabled (ie, is set to 0), this feature is ignored.

The bcPlayer.on.timeout event data contains a retry flag which indicates if bcPlayer is going to retry the playback with a different source.

Possible Values:

  • false DEFAULT Disables the retry on buffer timeout feature.

  • true Enables the retry on buffer timeout feature, if bcPlayer.bufferTimeout is enabled.

Code Snippet

                m.bcPlayer = createObject("roSGNode", "bcLib:bcPlayer")
 m.bcPlayer.on.observeField("timeout", "onTimeout")
 m.bcPlayer.retryOnBufferTimeout = true

 ' or

 m.bcPlayer.setFields({
   ' ...other fields here...
   retryOnBufferTimeout: true
 })

 ...

 sub onTimeout(ev)
   ' ev.getData() -> {contentIndex: Integer, bufferingStatus: AssociativeArray, retry: Boolean}
 end sub

closeOnBack

STRING OPTIONAL

Configures the back key press action.

It’s set to hard by default, which means that when the user presses the back key, it’ll completely terminate/kill the bcPlayer instance.

Setting it to soft causes the bcPlayer to do a soft close, which means that the current playback session is stopped and terminated but the bcPlayer node instance is kept alive and ready to receive other commands.

This behavior can be disabled (by setting this field to off), in which case developers could capture the back key press through the bcPlayer.on.keyEvent event listener and handle it manually. This also means that the bcPlayer node will let the back key event bubble up, so the app should be prepared to capture and handle it in a onKeyEvent function.

If an invalid value is set, it’ll automatically be reset back to hard.

Possible Values:

  • off Disables the close on back action.

  • soft Soft closes the bcPlayer when the user presses the back key.

  • hard DEFAULT Hard closes the bcPlayer when the user presses the back key.

Code Snippet

                m.bcPlayer = createObject("roSGNode", "bcLib:bcPlayer")
 m.bcPlayer.closeOnBack = "off" ' disable the close on back action

 ' or

 m.bcPlayer.setFields({
   ' ...other fields here...
   closeOnBack: "off"
 })

 ...
 
 ' somewhere in a bcPlayer parent node...
 function onKeyEvent(key as string, press as boolean) as boolean
   handled = false
   if key = "back" then
     closePlayer() ' developers should handle the back key press here since the closeOnBack action was disabled
     handled = true
   end if
   return handled
 end function
                

closeOnFinished

BOOLEAN OPTIONAL

Configures the bcPlayer behavior at the end of video playback.

When enabled (i.e., set to soft or hard), the bcPlayer will automatically close once the video playback reaches the end. In a playlist, this behavior depends on the following playback configurations:

  • bcPlayer.playback.autoPlayNext - if the autoPlayNext flag is enabled, once a video reaches the end, it'll play the next video in the playlist, if available.
  • bcPlayer.playback.loop - if the loop flag is enabled, once the last video in the playlist finishes, it'll loop the playlist and play the first video.

When disabled (i.e., set to off), developers should handle the finished event manually through the bcPlayer.on.finished or the bcPlayer.csai close event.

If an invalid value is set, it'll automatically be reset back to hard.

Keep in mind that the close action will trigger a bcPlayer.on.close event, where the close type (soft or hard) can be checked.

Possible Values:

  • off: Disables the close on finish action.

  • soft: Soft closes the bcPlayer when video playback finishes (depending on whether it’s playing a playlist or not and on the autoPlayNext and loop configuration values).

  • hard DEFAULT: Hard closes the bcPlayer when video playback finishes (depending on whether it’s playing a playlist or not and on the autoPlayNext and loop configuration values).

Code Snippet

                m.bcPlayer = createObject("roSGNode", "bcLib:bcPlayer")
 m.bcPlayer.closeOnFinished = "off"

 ' or

 m.bcPlayer.setFields({
   ' ...other fields here...
   closeOnFinished: "off"
 })
                

enableDialogs

BOOLEAN OPTIONAL

Configures bcPlayer to show error dialogs when an error occurs.

It’s enabled by default; you can disable it and capture the errors through the bcPlayer.on.error event.

These dialogs appearance can be customized through the dialogTheme field.

Possible Values:

  • false Disables error dialogs.

  • true DEFAULT Enables error dialogs.

Code Snippet

                m.bcPlayer = createObject("roSGNode", "bcLib:bcPlayer")
 m.bcPlayer.enableDialogs = false
 
 ' or
 
 m.bcPlayer.setFields({
   ' ...other fields here...
   enableDialogs: false
 })
                

enableGSC

BOOLEAN OPTIONAL

Toggles Brightcove Generic Stream Concurrency (GSC) feature on and off in bcPlayer.

Generic Stream Concurrency allows developers to define the number of video streams that a specific user can watch concurrently. Limiting stream concurrency helps preventing content being stolen or illegally watched through the theft or inappropriate sharing of credentials. Learn more.

Possible Values:

  • false DEFAULT Disables the GSC feature.

  • true Enables the the GSC feature if a valid bcPlayer.credentials.auth_token is also provided.

Code Snippet

                m.bcPlayer = createObject("roSGNode", "bcLib:bcPlayer")
 m.bcPlayer.credentials = {
   ...
   auth_token: ""
   ...
 }
 m.bcPlayer.enableGSC = true

 ' or

 m.bcPlayer.setFields({
   ' ...other fields here...
   credentials: {
     ...
     auth_token: ""
     ...
   }
   enableGSC: true
 })

dialogTheme

ASSOCIATIVE ARRAY OPTIONAL

Configures error dialogs appearance when enableDialogs is enabled.

The expected properties are the same as the native StandardDialog palette field properties, except for DialogItemColor, DialogInputFieldColor, DialogSecondaryTextColor, and DialogKeyboardColor properties, which do not apply.

Check below how the error dialogs look like in the default configuration.

error image example

Possible Values:

An ASSOCIATIVE ARRAY with the following optional keys:

  • DialogBackgroundColor STRING OPTIONAL

    • Specifies the blend color for dialog's background bitmap.

    • DEFAULT "#00000000"

  • DialogTextColor STRING OPTIONAL

    • Specifies the title and content text color.

    • DEFAULT Default Roku native color.

  • DialogFocusColor STRING OPTIONAL

    • Specifies the focused button and scrollbar thumb colors.

    • DEFAULT Default Roku native color.

  • DialogFocusItemColor STRING OPTIONAL

    • Specifies the focused button text color.

    • DEFAULT Default Roku native color.

  • DialogSecondaryItemColor STRING OPTIONAL

    • Specifies the title divider color.

    • DEFAULT "#00000000"

  • DialogFootprintColor STRING OPTIONAL

    • Specifies the button focus footprint color as well as the unfocused scrollbar thumb and track color.

    • DEFAULT Default Roku native color.

Code Snippet

                m.bcPlayer = createObject("roSGNode", "bcLib:bcPlayer")
 m.bcPlayer.dialogTheme = {
   DialogBackgroundColor: "#00000000"
   DialogTextColor: "#dbdbdb"
   DialogFocusColor: "#d32228"
   DialogFocusItemColor: "#ab2125"
   DialogSecondaryItemColor: "#dbdbdb"
   DialogFootprintColor: "#dbdbdb"
 }
 
 ' or
 
 m.bcPlayer.setFields({
   ' ...other fields here...
   dialogTheme: {
     DialogBackgroundColor: "#00000000"
     DialogTextColor: "#dbdbdb"
     DialogFocusColor: "#d32228"
     DialogFocusItemColor: "#ab2125"
     DialogSecondaryItemColor: "#dbdbdb"
     DialogFootprintColor: "#dbdbdb"
   }
 })
                

bufferTimeout

INTEGER OPTIONAL

Configures the buffering timeout period, in seconds. This configuration allows developers to setup a timer which is initiated once the initial video buffering begins and at the end of which a timeout error will be triggered if the video playback hasn’t yet initiated.

Setting it to 0 disables the buffering timeout timer.

When the video buffering times out, a bcPlayer.on.timeout event is triggered. Additionally, if the bcPlayer.retryOnBufferTimeout configuration flag is enabled, the bcPlayer will retry the playback with a different source, if available. Otherwise, a dialog window is shown (if bcPlayer.enableDialogs is enabled).

Possible Values:

  • A positive integer value (seconds).
  • DEFAULT 0 buffering timeout disabled.

Code Snippet

                m.bcPlayer = createObject("roSGNode", "bcLib:bcPlayer")
 m.bcPlayer.bufferTimeout = 20
 
 ' or
 
 m.bcPlayer.setFields({
   ' ...other fields here...
   bufferTimeout: 20
 })
                

sdkVersion

STRING READ-ONLY

Provides the Roku SDK version.

Possible Values:

  • The version number in the following format: <major-version>.<minor-version>.<build-version>

Code Snippet

                m.bcPlayer = createObject("roSGNode", "bcLib:bcPlayer")
                sdkVersion = m.bcPlayer.sdkVersion
                

adPlaying

BOOLEAN READ-ONLY

Indicates if a SSAI or CSAI ad is currently playing.

Possible Values:

  • true An ad is currently playing.
  • false No ad is currently playing.

Code Snippet

                sub init()
                  m.bcPlayer = createObject("roSGNode", "bcLib:bcPlayer")
                  m.bcPlayer.observeField("adPlaying", "onAdPlaying")
                end sub
                
                ...
                
                sub onAdPlaying(ev)
                  ? "is it playing ads? " ev.getData()
                end sub
                

relativePosition

FLOAT READ-ONLY

Specifies the relative playback position on SSAI enabled videos. The relative position is the video content playback position when all the ads are ignored.

When playing a video without SSAI, the relativePosition value reflects the native Video.position field.

Code Snippet

                sub init()
   m.bcPlayer = createObject("roSGNode", "bcLib:bcPlayer")
   m.bcPlayer.observeField("relativePosition", "onRelativePosition")
 end sub
 
 ...
 
 sub onRelativePosition(ev)
   ? "Relative position: " ev.getData()
 end sub
                

visibleOnScreen

BOOLEAN READ-ONLY

Specifies if the bcPlayer node is at least 50% of its size visible on the screen based on its size, position and visible and opacity field.

Please be aware that this field does not have into account the app node tree list so, for example, it ignores situations where another component is positioned over the bcPlayer node and covers it partially or completely.

Possible Values:

  • true The bcPlayer node is at least 50% visible on the screen.
  • false The bcPlayer node is completely hidden or less than 50% visible on the screen.

Code Snippet

                sub init()
   m.bcPlayer = createObject("roSGNode", "bcLib:bcPlayer")
   m.bcPlayer.observeField("visibleOnScreen", "onVisibleOnScreen")
 end sub
 
 ...
 
 sub onVisibleOnScreen(ev)
  ? "Is bcPlayer visible on screen? " ev.getData()
 end sub
                

playback

NODE

Allows for a deeper level of control over video playback and content management in the bcPlayer.

Fields

Field Description
index

INTEGER READ-ONLY

Specifies the index of the video playing in a playlist. It's set to 0 when a single video is playing. It's set to -1 when no video is playing.

loop

BOOLEAN OPTIONAL

Specifies if video playback should automatically loop in a playlist when executing the playNext and playPrevious playback functions.

  • DEFAULT false
autoPlayNext

BOOLEAN OPTIONAL

Specifies if bcPlayer should automatically play the next video in a playlist when video playback finishes.

  • DEFAULT false

Functions

Name Parameters Description
load
  • content

    NODE REQUIRED

  • position

    STRING OPTIONAL

    Supported values:

    • DEFAULT replace
    • append
    • prepend

Loads new content into bcPlayer for playback.

This function is used internally by the bcPlayer loadCustom, load, getVideo, getVideos, getPlaylist and getRelated functions so, generally, there should be no reason to use it directly, although it does provide more flexibility for custom use-cases.

content specifies the ContentNode to be loaded, this can represent either a single video or a playlist.

If content is Invalid, the existing content is removed (keep in mind that if a video is playing at this time, the playback is not interrupted).

position specifies where the content should be loaded if any content is already present. The options are:

  • replace → replaces the existing content with the new one. This is the default behavior.
  • append → adds the new content at the end of the existing content. If the existing content is not a playlist, it creates a playlist containing the previous content and the new content.
  • prepend → adds the new content at the start of the existing content. If the existing content is not a playlist, it creates a playlist containing the new content and the previous content.

Returns a BOOLEAN value specifying if content was successfully added.

preload
  • index

    INTEGER OPTIONAL

    • DEFAULT -1

Preloads a video for playback at a later time. It does not start video playback.

Preloading a video means to process and initialize the SSAI and CSAI components as well as validate the video stream TTL, when applicable. As such, please keep in mind that this is an asynchronous process.

This process is useful when there’s a need to get everything ready to start playing a specific video at a later time (through the play function, for example).

The index parameter specifies the index of the video in the playlist to be preloaded. If index is not provided, it'll preload the first video in the playlist or the loaded video if there’s no playlist.

If there’s a video playback session currently ongoing when preload is executed, this session is terminated prior to the preload process, unless index represents the current video, in which case no action is taken.

Triggers a bcPlayer.on.loadItem event once the video is successfully loaded.

Returns a BOOLEAN value specifying if the preload action was successfully initiated.

play
  • index

    INTEGER OPTIONAL

    • DEFAULT -1

Preloads a video and initiates or resumes playback.

The index parameter specifies the index of the video to play in the playlist.

If index is not provided it defaults to the first video in the playlist or the single video loaded. If index refers to the current playback session, the play action will be applied to the active video, depending on its playback state, as such:

  • if video is paused → resumes playback
  • if video is already playing or buffering → action is ignored
  • if video is CSAI and is ready to start → starts CSAI video playback
  • otherwise → sets bcPlayer control field to play

Just like preload and prebuffer functions, the play function loads the specified video, when applicable, and starts playback immediately. As such, please keep in mind that this might be an asynchronous process.

Triggers a bcPlayer.on.loadItem event once the video is successfully loaded.

Returns a BOOLEAN value specifying if the play action was successfully initiated.

prebuffer
  • index

    INTEGER REQUIRED

Preloads a video and starts prebuffering it.

The prebuffer function behaves just like the play function but instead of initiating video playback, it starts prebuffering the video stream. As such, please keep in mind that this might be an asynchronous process.

If index is lower than 0, it resets to the first video in the playlist if applicable or to the current video session if applicable, in which case video playback is interrupted and prebuffer is initiated on the same video.

Prebuffering does not apply to CSAI videos.

Triggers a bcPlayer.on.loadItem event once the video is successfully loaded.

Returns a BOOLEAN value specifying if the prebuffer action was successfully initiated.

pause -

Pauses video playback.

Applies to CSAI and non-CSAI videos.

Returns a BOOLEAN value specifying if the pause command was successfully set.

terminate -

Stops video playback. Essentially, the terminate function applies the stop control command to bcPlayer.

Applies to CSAI and non-CSAI videos.

Returns a BOOLEAN value specifying if the stop command was successfully set.

playNext -

Plays the next video in the playlist.

Applies to playlists only.

Essentially, this function executes the play function passing along the next video index in the index parameter.

When the playNext function is called on the last video of the playlist, the behavior depends on the loop field value:

  • if loop is true → plays the first video in the playlist
  • if loop is false → nothing happens

Triggers a bcPlayer.on.next event if the next action was successfully executed.

Returns a BOOLEAN value specifying if the next action was successfully executed.

playPrevious -

Plays the previous video in the playlist.

Applies to playlists only.

Essentially, this function executes the play function passing along the previous video index in the index parameter.

When the playPrevious function is called on the first video of the playlist, the behavior depends on the loop field value:

  • if loop is true → plays the last video in the playlist
  • if loop is false → nothing happens

Triggers a bcPlayer.on.previous event if the previous action was successfully executed.

Returns a BOOLEAN value specifying if the previous action was successfully executed.

seek
  • position

    FLOAT REQUIRED

Seeks to the specified position. Essentially, the seek function sets the seek Video field value.

Applies to CSAI and non-CSAI videos.

Returns a BOOLEAN value specifying if the seek value was successfully set.

replay -

Seeks back 10 seconds in the current playback session. Essentially, the replay function applies the replay control command.

Applies to CSAI and non-CSAI videos.

Returns a BOOLEAN value specifying if the replay command was successfully set.

clear
  • hard

    BOOLEAN OPTIONAL

    • DEFAULT true

Clears the current playback session.

It essentially stops the current playback, clears the bcPlayer content and internal flags.

The hard parameter allows the index read-only bcPlayer.playback field to be reset back to -1 if true (the default behavior).

removeItem
  • index

    INTEGER REQUIRED

  • force

    BOOLEAN OPTIONAL

    • DEFAULT false

Removes the video specified by the index parameter.

Only applicable to playlists.

[TBI] The force parameter allows to customize the function behavior when removing the video that is currently playing:

  • if true → stops video playback
  • if false → nothing happens

Returns a BOOLEAN value specifying if the video was successfully removed.

getContent -

Retrieves the current bcPlayer content.

If the current content is a playlist, it returns a ContentNode containing child ContentNodes representing the videos in the playlist.

Returns a NODE value or Invalid if no content is set.

getItemCount -

Returns the number of videos currently loaded into the bcPlayer.

Returns 1 if content is not a playlist.

Returns 0 if no content is set.

Returns a INTEGER value.

getItem
  • index

    INTEGER OPTIONAL

    • DEFAULT -1

Retrieves a single video ContentNode through its index specified by the index parameter.

If the content is not a playlist, index can be omitted.

If index is lower than 0, returns the video that is currently playing, if applicable, otherwise returns Invalid.

Returns Invalid if no content is set.

Returns a NODE value.

getActiveItem -

Retrieves the video that is currently playing, similar to calling getItem with no parameters.

Returns Invalid if no video is playing.

Returns a NODE value.

getFirstItem -

Retrieves the first video in the playlist.

Returns Invalid if no content is set or content is not a playlist.

Returns a NODE value.

getLastItem -

Retrieves the last video in the playlist.

Returns Invalid if no content is set or content is not a playlist.

Returns a NODE value.

getTrickplay -

Retrieves the native UI TrickplayBar node.

When CSAI video playback is ongoing, returns the RAFContentRenderer TrickplayBar node instead.

Returns Invalid if the bcPlayer.enableUI field is false.

Returns a NODE value.

isActiveItem
  • node

    NODE REQUIRED

Checks if the provided node is currently active/playing.

Returns a BOOLEAN value.

is
  • option

    STRING REQUIRED

    Supported values:

    • Any Video state supported value (playing, buffering, paused, stopping, stopped, finished, error)
    • prebuffering
    • active
    • ssai
    • csai
    • csaiactive
    • dvr
    • live
    • playingads

Allows to check the state of the ongoing playback session. Returns a BOOLEAN value specifying the state of the option provided, as follows:

  • Any Video state supported value
    • Specifies if the current playback state reflects option.
  • prebuffering
    • specifies if bcPlayer is prebuffering a video (ie, control = "prebuffer"). Always returns false when playing CSAI videos.
  • active
    • specifies if there’s a video playing or ready for playback in bcPlayer.
  • ssai
    • specifies if the current video is properly configured to setup SSAI (ie, the video adsData ContentNode property is properly set).
  • csai
    • specifies if the current video is properly configured to setup CSAI (ie, the video adsData ContentNode property is properly set).
  • csaiactive
    • specifies if CSAI video playing is currently ongoing.
  • dvr [TBI]
    • specifies if DVR video is currently playing.
  • live
    • specifies if the current video is a live stream (ie, the video live ContentNode property is set to true).
  • playingads
    • specifies if bcPlayer is currently playing ads.

Code snippet

                m.bcPlayer = createObject("roSGNode", "bcLib:bcPlayer")

 ' setup the main bcPlayer configurations
 m.bcPlayer.setFields({
   credentials: {...}
   ...
 })

 ' setup the playback configurations, if needed
 m.bcPlayer.playback.setFields({
   loop: true, ' enable the playlist loop behavior
   autoPlayNext: true  ' enable the autoPlayNext behavior
 })

 ' -------------------------------------------------
 ' Use-case 1 - add a custom video ContentNode and start playback
 ' -------------------------------------------------
 videoLoaded = m.bcPlayer.playback.callFunc("load", MyVideoContentNode)
 if videoLoaded then
   m.bcPlayer.playback.callFunc("play")
 else
   ' handle the load process failure
 end if
 ' -------------------------------------------------

 ' -------------------------------------------------
 ' Use-case 2 - add custom video metadata and start prebuffering it
 ' -------------------------------------------------
 m.bcPlayer.on.observeField("load", "onLoad") ' since the loadCustom fucntion is asynchronous, we need to wait for the process to complete before handling its playback
 m.bcPlayer.callFunc("loadCustom", {<my-video>}, {autoplay: -1}) ' load the custom video metadata and disable autoplay

 ...

 sub onLoad(ev)
   data = ev.getData()
   if data.error <> invalid then
     ' handle the load error
     return
   end if

   ' the video content has been loaded successfully, initiate the prebuffer process
   m.bcPlayer.playback.callFunc("prebuffer", 0)
 end sub
 ' -------------------------------------------------

 ' -------------------------------------------------
 ' Use-case 3 - retrieve a Brightcove playlist and prebuffer the 3rd video in the playlist
 ' -------------------------------------------------
 m.bcPlayer.on.observeField("load", "onLoad")
 m.bcPlayer.on.observeField("error", "onError")
 m.bcPlayer.callFunc("getPlaylist", "my-playlist-id", {autoplay: -1}) ' load the playlist and disable the autoplay behavior

 ...

 sub onError(ev)
   data = ev.getData()
   if data.source = "getPlaylist" then
     ' handle an eventual getPlaylist error
   end if
 end sub

 sub onLoad(ev)
   data = ev.getData()
   if data.error <> invalid then
     ' handle the load error
     return
   end if
   ' the playlist content has been loaded successfully, initiate the prebuffer process
   m.bcPlayer.playback.callFunc("prebuffer", 2)
 end sub
 ' -------------------------------------------------
 
 ' -------------------------------------------------
 ' Use-case 4 - update the active video title
 ' -------------------------------------------------
 activeVideo = m.bcPlayer.playback.callFunc("getActiveItem")
 if activeVideo <> invalid then
   activeVideo.title = "A Brand New Fancy Title"
 end if
 ' -------------------------------------------------

analytics

NODE

Configures Brightcove’s Data Collection API support. This node allows for some of the Analytics metrics to be customized thus allowing for some flexibility and account for different use cases.

It also provides a read-only field where all the triggered events data can be accessed for further processing or logging.

All the available fields are listed in the table below.

analytics fields description
Field Description
accountID STRING OPTIONAL
  • Specifies the Video Cloud Account ID for the Analytics events specifically.
  • Applies to the account, player and player_name metrics.
  • DEFAULT ""
    • if not set, the bcPlayer.credentials.account_id field value is used.
url STRING OPTIONAL
  • Allows to redirect the Analytics events to a specify endpoint.
  • This can be useful for test and debugging purposes to validate if all the events and metrics are properly set.
  • DEFAULT ""
    • If not set, events are sent to through Brightcove’s Data Collection API v2.
applicationID STRING OPTIONAL
  • Can be used to specify an ID for the application.
  • Applies to the following metrics:
    • player - applicationID is appended to the default value of player as such: <player>/<applicationID>
    • player_name - if the playerName is provided, applicationID is appended to its value as such: <playerName>/<applicationID>. Otherwise player_name takes the value of applicationID
  • DEFAULT ""
env STRING OPTIONAL
  • Specifies the Data Collection API environment to use.
  • The possible values are:
    • DEFAULT production
    • staging
    • qa
  • If not set (or set to ""), the production environment endpoint will be used.
playerID STRING OPTIONAL
  • Allows to specify an ID for the player.
  • If not set, uses the value of player.
  • Applies to the player metric which takes the following format: players.brightcove.com/<accountID>/<playerID>[/<applicationID>]
  • DEFAULT ""
playerName STRING OPTIONAL
  • Allows to specify a name for the player.
  • Applies to the player_name metric which takes the following format: <playerName>[ - <applicationID>] or <applicationID> if playerName is not set.
  • DEFAULT ""
user STRING OPTIONAL
  • Specifies the user identification.
  • Applies to the user metric.
  • DEFAULT ""
    • If not set, the user metric will not be added to the request.
destination STRING OPTIONAL
  • Allows to specify the destination metric.
  • DEFAULT ""
    • If not set, the destination metric will not be added to the request.
source STRING OPTIONAL
  • Allows to specify the source metric.
  • DEFAULT ""
    • If not set, the source metric will not be added to the request.
eventOut associative array READ-ONLY
  • Allows for all the Analytics event metrics to be accessed as soon as they trigger. The AssociativeArray contains all the event metrics and their values.
  • This field can be observed to access the event data.

Code Snippet

                m.bcPlayer = createObject("roSGNode", "bcLib:bcPlayer")
                m.bcPlayer.analytics.accountID = "my account ID" ' setting a different accountID
                m.bcPlayer.analytics.user = "123456" ' setting the user identification
                m.bcPlayer.analytics.observeField("eventOut", "onAnalyticsEvent") ' observing the eventOut field
                
                ...
                
                sub onAnalyticsEvent(ev)
                  data = ev.getData()
                  eventName = data.event
                  ? "Analytics " + eventName + " event data: " data
                end sub
                

on

NODE READ-ONLY

Allows access to all the bcPlayer events. Developers should setup event listeners to capture the events data through the observeField() or observeFieldScoped() functions. Check the table below for all the available events and the data they provide.

Event List

Events
Event Data Description
sdkReady

BOOLEAN

  • true bcPlayer internal components have been loaded and are ready to use.

  • false bcPlayer features are not available.

Indicates if the bcPlayer internal components have been completely initiated. If the sdkReady value is false, the bcPlayer features are not available to use.

load

ASSOCOATIVE ARRAY

Provides an ASSOCIATIVE ARRAY object with the following properties:

  • type STRING REQUIRED

    Metadata type. Available in start and end events. Possible values:

    • video: specifies that a single video metadata is being loaded.

    • playlist: specifies that a playlist metadata is being loaded (applies to Brightcove playlists as well as search results and related videos metadata).

    • unknown: the metadata type couldn’t be identified.

  • data DYNAMIC REQUIRED

    Provides the processed ContentNode which is being loaded into the bcPlayer if the loading process is successful. On the other hand, if an error occurs, data provides the original metadata object.

  • error STRING OPTIONAL

    Specifies the error message. Only available when an error occurs during the loading process.

  • autoplay INTEGER OPTIONAL

    Specifies the autoplay video index as provided to the load or loadCustom functions. Defaults to 0. Only available when the loading process is successful.

  • prebuffer BOOLEAN OPTIONAL

    Specifies the prebuffer value as provided to the load or loadCustom functions. Defaults to false. Only available when the loading process is successful.

  • position STRING OPTIONAL

    Specifies the position value as provided to the load or loadCustom functions. Defaults to replace. Only available when the loading process is successful.

Allows for a better tracking of the load and loadCustom progress. The load event is triggered when metadata load process starts, when it ends and when an error occurs during the loading process. It also triggers during the custom metadata loading process initiated through the loadCustom function.

loadItem

ASSOCIATIVEARRAY

Provides an AssociativeArray object with the following properties:

  • index INTEGER REQUIRED

    Specifies the index of the video that was just loaded.

  • node INTEGER REQUIRED

    Specifies the loaded video ContentNode.

  • ads STRING REQUIRED

    Specifies what ad system was set up during the video load. The possible values are:

    • none → no ads were setup for the video
    • csai → CSAI was setup for the video
    • ssai → SSAI was setup for the video
  • duration FLOAT REQUIRED

    Specifies the duration of the load operation.

  • operation STRING REQUIRED

    Specifies what action triggered the load operation. The possible values are:

    • preload
    • prebuffer
    • play
  • error ASSOCIATIVE ARRAY OPTIONAL

    Specifies the error data if the load operation failed. The possible values are:

    • message STRING REQUIRED

      Specifies the error message.

    • data ASSOCIATIVE ARRAY OPTIONAL

      Provides additional data on the error. This data varies depending on the error and operation.

Triggers when a new video is loaded in the bcPlayer for playback. This event is triggered by the play, prebuffer and preload bcPlayer.playback functions. In a playlist, it's also triggered when triggering the next and previous actions, either manually by the app user or automatically when video playback reaches the end.

start

ASSOCOATIVE ARRAY

Provides an ASSOCIATIVE ARRAY object with the following properties:

  • contentIndex INTEGER REQUIRED

    Specifies the index of the video that is currently playing in the playlist. It’s set to 0 when playing a single video.

  • downloadedSegment ASSOCIATIVE ARRAY NATIVE REQUIRED

    Reference to the native Video.downloadedSegment field.

  • timeToStartStreaming INTEGER/FLOAT NATIVE REQUIRED

    Reference to the native Video.timeToStartStreaming field. Specifies the time in seconds from playback being started until the video actually began playing.

  • playStartInfo ASSOCIATIVE ARRAY NATIVE REQUIRED

    Reference to the native Video.playStartInfo field. Provides timing measurements related to the start of video playback. All measurements are in seconds. Provides the following keys:

    • total_dur FLOAT REQUIRED

      Total video start duration.

    • manifest_dur FLOAT REQUIRED

      Manifest download and parsing.

    • drm_load_dur FLOAT REQUIRED

      DRM system initialization.

    • drm_lic_acq_dur FLOAT REQUIRED

      License acquisition. This typically includes interactions with the license server.

    • prebuf_dur FLOAT REQUIRED

      Prebuffer content.

    • manifest_start FLOAT REQUIRED

      Point at which manifest download and parsing begins.

    • drm_load_start FLOAT REQUIRED

      Point at which DRM system initialization begins.

    • drm_lic_acq_start FLOAT REQUIRED

      Point at which license acquisition begins.

    • prebuf_start FLOAT REQUIRED

      Point at which content pre-buffering begins.

  • videoFormat STRING NATIVE REQUIRED

    Reference to the native Video.videoFormat field. Contains the format of the currently playing video stream. Possible values:

    • "" No stream playing.

    • none Stream contains no playable video.

    • unknown Stream contains unknown video.

    • hevc ISO/IEC 23008-2, H.265, HEVC.

    • hevc_b ISO/IEC 23008-2 Annex-B, H.265, HEVC.

    • mpeg1 ISO/IEC 11172-2, MPEG-1 part 2, H.261.

    • mpeg2 ISO/IEC 13818-2, MPEG-2 part 2, H.262.

    • mpeg4_2 ISO/IEC 14496-2, MPEG-4 part 2, H.263.

    • mpeg4_10b ISO/IEC 14496-10, MPEG-4 part 10 Annex-B, H.264, vc-1.

    • mpeg4_15 ISO/IEC 14496-15, MPEG-4 part 15, H.264, vc-1.

    • AVC vc1 vc-1.

    • wmv Microsoft Windows Media Video.

    • vp8 VP8 codec.

    • vp9 VP9 codec.

  • audioFormat STRING NATIVE REQUIRED

    Reference to the native Video.audioFormat field. Contains the format of the currently playing audio. Possible values:

    • "" No stream playing.

    • none Stream contains no playable audio.

    • unknown Stream contains unknown audio.

    • acc ISO/IEC 14496-3, Advanced Audio Coding.

    • acc_adif ISO/IEC 14496-3, Advanced Audio Coding, ADIF container.

    • acc_adts ISO/IEC 14496-3, Advanced Audio Coding, ADTS container.

    • acc_latm ISO/IEC 14496-3, Advanced Audio Coding, LATM container.

    • ac3 Dolby Digital.

    • ac4 Dolby Audio - AC-4.

    • eac3 Dolby Digital Plus.

    • alac Apple Lossless.

    • dts DTS Coherent Acoustics.

    • flac Free Lossless Audio Codec.

    • mat Dolby Audio - TrueHD.

    • mp3 ISO/IEC 11172-3, MPEG Audio Layer III.

    • pcm linear PCM.

    • vorbis Ogg Vorbis.

  • currentAudioTrack STRING NATIVE REQUIRED

    Reference to the native Video.currentAudioTrack field. Specifies the track identifier of the audio being played. Reading this field returns the track that is being played, which may be different than the track being selected (for example, when the Roku media player cannot play a certain format). Roku automatically selects a track based on the preferred audio language setting if no audio track is specifically selected.

  • availableAudioTracks ARRAY NATIVE REQUIRED

    Reference to the native Video.availableAudioTracks field. Lists all the available audio tracks on the currently playing stream. Every array element consists of an ASSOCIATIVE ARRAY containing the following keys:

    • Language STRING REQUIRED

      ISO 639-2 three-letter language code.

    • Name STRING REQUIRED

      Descriptive name of the audio track.

    • Track STRING REQUIRED

      The track identifier. The value of this field may be used to select the audio track through the bcPlayer.video.audioTrack field.

  • currentSubtitleTrack STRING NATIVE REQUIRED

    Reference to the native Video.currentSubtitleTrack field. Specifies the identifier of the selected subtitle track that is currently playing. Subtitles may or may not be visible on the screen, depending upon the user's caption mode setting. When the user has not selected a track, the Roku media player will select a track based on the preferred caption language system setting.

  • availableSubtitleTracks ARRAY NATIVE REQUIRED

    Reference to the native Video.availableSubtitleTracks field. Specifies the list of subtitle tracks available in the video stream. Every array element consists on an ASSOCIATIVE ARRAY containing the following keys:

    • Description STRING REQUIRED

      Descriptive name of the subtitle track.

    • Language STRING REQUIRED

      ISO 639-2 three-letter language code.

    • TrackName STRING REQUIRED

      The track identifier. The value of this field may be used to select the subtitle track through the bcPlayer.video.subtitleTrack field.

  • retries INTEGER REQUIRED

    Available when playing Brightcove sources only. Specifies the number of playback retries when retryOnError is enabled. If it’s disabled, this property is set to 1.

The start event is triggered as soon as video playback starts, ie. the first time that the player status is set to playing. It triggers only once per playback session and provides a set of useful information about the video that just started playing. Most of the information provided is retrieved from the native Video, but when playing a CSAI video, this information is retrieved from RAF’s own renderer component. Please refer to the Roku documentation for more specific details on those fields.

Keep in mind that if the user rewinds or seeks to a specific position after the video playback has finished, this event is triggered once again for the same video.

playing

ASSOCIATIVEARRAY

Provides an AssociativeArray object with the following properties:

  • contentIndex INTEGER REQUIRED

    Specifies the index of the video that is currently playing in a playlist. Defaults to 0 when playing a single video.

  • position FLOAT NATIVE REQUIRED

    Specifies the current playback position.

Reflects the playing value of the Video.state field and specifies that the stream playback has started, either for the first time, after rebuffering or a resume action. When playing a CSAI video, this event reflects the playing state of RAF’s renderer node.

pause

ASSOCIATIVEARRAY

Provides an AssociativeArray object with the following properties:

  • contentIndex INTEGER REQUIRED

    Specifies the index of the video that is currently playing in a playlist. Defaults to 0 when playing a single video.

  • position FLOAT NATIVE REQUIRED

    Specifies the current playback position.

Reflects the paused value of the Video.state field and specifies that the stream playback has been paused. When playing a CSAI video, this event reflects RAF’s paused event.

resume To be implemented
replay To be implemented
previous

ASSOCIATIVE ARRAY

Provides an ASSOCIATIVE ARRAY object with the following properties:

  • fromIndex INTEGER REQUIRED

    The index of the currently playing video in the playlist.

  • toIndex INTEGER REQUIRED

    The index of the previous video in the playlist that will start playing.

The play previous video action has been triggered. This event is only available when playing a playlist structure.

next

ASSOCIATIVE ARRAY

Provides an ASSOCIATIVE ARRAY object with the following properties:

  • fromIndex INTEGER REQUIRED

    The index of the currently playing video in the playlist.

  • toIndex INTEGER REQUIRED

    The index of the next video in the playlist that will start playing.

The play next video action has been triggered. This event is only available when playing a playlist structure.

finished

ASSOCIATIVE ARRAY

Provides an ASSOCIATIVE ARRAY object with the following properties:

  • reason STRING REQUIRED

    Specifies the reason for the finished event. The possible values for this property are:

    • finished: the playback reached the end of the stream or it was interrupted by an error.
    • stopped: the playback was stopped by an external action.

  • completedStreamInfo ASSOCIATIVE ARRAY NATIVE REQUIRED

    Reference to the native Video.completedStreamInfo field. Provides information about the video stream that most recently completed playing, due to an error, user action, or end of the stream. The following keys are available through this property:

    • isUnderrun BOOLEAN REQUIRED

      If true, the stream was downloaded due to an underrun.

    • isResume BOOLEAN REQUIRED

      If true, playback was resumed after a trickplay seek action.

    • measureBitrate INTEGER REQUIRED

      The measured bitrate (bps) of the network when the stream was selected.

    • streamBitrate INTEGER REQUIRED

      The bitrate of the stream.

    • streamUrl STRING REQUIRED

      The URL of the stream.

    • isFullResult BOOLEAN REQUIRED

      If true indicates the stream played to completion, if false, the stream was interrupted by an error or user action.

  • contentIndex INTEGER NATIVE REQUIRED

    Reference to the native Video.contentIndex field. Specifies the index of the video that is currently playing in the playlist. It’s set to 0 if only a single video is playing.

  • errorCode INTEGER NATIVE REQUIRED

    Reference to the native Video.errorCode field. Specifies the error code if the stream has ended due to an error. Further details on the error can be retrieved through the errorerror event. Possible values:

    • 0 no error
    • -1 network error (server down or unresponsive, server is unreachable, network setup problem on the client).
    • -2 connection timed out.
    • -3 unknown/unspecified or generic Error.
    • -4 empty list; no streams were specified to play.
    • -5 media error; the media format is unknown or unsupported.
    • -6 DRM error.

Triggered at the end of a video playback. The following situations will trigger a finished event:

  • The video has played until the end of the stream.

  • A playback error occurs, either while loading the stream or mid-stream. Keep in mind that an errorerror event will trigger before the finished event in this case.

  • A retrial error occurs, when it’s not possible to play any of the video available sources. Valid when retryOnError is enabled.

  • The video playback is stopped by an external action.

playlistIndex

INTEGER

  • -1 DEFAULT

    Integer number

Triggered when loading up a video for playback. Specifies the index of the video that was loaded.

When playing a single video this event sends 0.

disconnect

BOOLEAN

  • true Network connection was lost.

  • false Network connection resumed.

Triggered when loss of internet connection is detected.

This specific situation is handled by the native Video node. A native message triggered by RokuOS is presented to the app user informing that the network connection was lost.

An error is eventually triggered but it’s not immediate as the player waits for the conditions to resume video playback.

We provide this event in case developers need to implement custom behaviors/workflows to handle this situation.

error

ASSOCIATIVE ARRAY

Provides an ASSOCIATIVE ARRAY object with the following keys:

  • source STRING REQUIRED

    Provides an indication of the source of the error. This allows errors to be filtered and individually handled depending on their source. Possible values:

    • playback an error occurred during video playback. This error is triggered when the native Video.state field value is set to error. More info on the error can be found in the data key object.

    • playback-retrial triggered when retryOnError is enabled. Lets developers know that there are no more valid video sources to retry.

    • playback-buffering triggered when bufferTimeout is enabled (ie, set to a value higher than 0) and indicates that the buffering timeout has been reached. Keep in mind that if retryOnError is enabled, it’ll still try to playback another source, otherwise the playback will stop.

    • load triggered when an error occurs within the load function.

    • getVideo triggered when an error occurs within the getVideo function.

    • getVideos triggered when an error occurs within the getVideos function.

    • getPlaylist triggered when an error occurs within the getPlaylist function.

    • getRelated triggered when an error occurs within the getRelated function.

    • refreshSources triggered when an error occurs within the execution of the sources refresh feature.

  • path STRING REQUIRED

    Provides a more detailed indication on where exactly the error occurred. For example:

    • bcPlayer/bcPlayerTask the error occurred in the bcPlayer internal task.

    • bcPlayer/bcPlayerTask/playPlaylist the error occurred in the bcPlayer task playPlaylist function.

  • message STRING REQUIRED

    Provides the error message. The exact value of this property depends on the error source:

    • playback: contains the value of the native Video.errorMsg field.

    • playback-retrial/playback-buffering: provides a description of the error.

    • getVideo/getVideos/getPlaylist/getRelated:

      • In case of a Playback API request failure this property contains either the error message provided in the response body or, if that’s not available, the associated roUrlEvent GetFailureReason value.
      • In all other cases (validation errors), provides a description of the error.
  • data ASSOCIATIVE ARRAY OPTIONAL

    Provides more details about the error. This property is available in the playback, playback-retrial, playback-buffering and some of the other errors that might contain data on a failed API request. Provides the following properties:

    • errorCode INTEGER NATIVE REQUIRED

      The value of this property depends on the error source:

      • playback: contains the value of the native Video.errorCode field. Check the Roku documentation for all the possible values in this field.

      • playback-retrial: contains the value of the native Video.errorCode field set by the latest source playback retry error.

      • playback-buffering: contains the value of the native Video.errorCode field. It should be 0 in this case as the buffering timeout usually triggers before the Video playback error.

      • playVideo/playVideos/playPlaylist/playRelated/refreshSources: contains the Playback API request response code.

    • contentIndex INTEGER NATIVE OPTIONAL

      Value of the native Video.contentIndex field. It’s set to 0 when playing a single video. Only present on playback, playback-retrial and playback-buffering error sources.

    • completedStreamInfo ASSOCIATIVE ARRAY NATIVE OPTIONAL

      Value of the native Video.completedStreamInfo field. Useful on playback errors. Only present on playback, playback-retrial and playback-buffering error sources.

    • errorMsg STRING NATIVE OPTIONAL

      The value of this property depends on the error source:

      • playback/playback-retrial/playback-buffering: contains the value of the native Video.errorMsg field. Only present if errorCode is not 0.

      • getVideo/getVideos/getPlaylist/getRelated/refreshSources: contains the return value of the Playback API request associated roUrlEvent GetFailureReason function.

    • errorStr STRING NATIVE OPTIONAL

      Value of the native Video.errorStr field. Only present if errorCode is not 0 on playback, playback-retrial and playback-buffering error sources.

    • errorInfo ASSOCIATIVE ARRAY NATIVE OPTIONAL

      The value of this property depends on the error source:

      • playback/playback-retrial/playback-buffering: contains the value of the native Video.errorInfo field. Only present if errorCode is not 0.

      • getVideo/getVideos/getPlaylist/getRelated/refreshSources: contains the Playback API request error response body. The expected value is an ASSOCIATIVE ARRAY object containing the following properties (for more detailed information on these please check the Playback API documentation page):

        • error_code STRING REQUIRED

        • message STRING REQUIRED

    • retry BOOLEAN OPTIONAL

      If true specifies that it wasn't possible to playback a specific video source and the player will retry with a different source. If all the available video sources fail to play, a playback-retrial error will be triggered (and in that case, retry value is reset to false). Only present if retryOnError is enabled on playback, playback-retrial and playback-buffering error sources.

    • retries INTEGER OPTIONAL

      Specifies the number of source playback retries that were executed. Only present if retryOnError is enabled on playback, playback-retrial and playback-buffering error sources.

    • source ASSOCIATIVE OPTIONAL

      Specifies an invalid video source which bcPlayer wasn’t able to properly parse into the expected Video ContentNode fields. Only present in a specific playback-retrial error.

Triggered when an error occurs within bcPlayer. The possible errors include video playback errors as well as data parsing, API request errors and other validation related errors.

buffering

ASSOCIATIVE ARRAY

Provides an ASSOCIATIVE ARRAY object with the following keys:

  • contentIndex INTEGER REQUIRED

    Reflects the value of the native Video.contentIndex field.

  • position FLOAT NATIVE REQUIRED

    Reflects the value of the native Video.position field.

  • bufferingStatus ASSOCIATIVE ARRAY NATIVE REQUIRED

    Reflects the value of the native Video.bufferingStatus field. The following properties are available:

    • percentage FLOAT REQUIRED

      Percent buffering complete as an integer.

    • isUnderrun BOOLEAN REQUIRED

      Indicates if a stream underrun occurred.

    • prebufferDone BOOLEAN REQUIRED

      Indicates whether the player has buffered enough data to allow the player to begin playing immediately should "control" be set to "play."

    • actualStart FLOAT REQUIRED

      A time value that is automatically set when prebufferDone becomes true, specifying the actual time from which playback will resume. This may vary from the time requested in the content node's playStart field, depending on the capabilities of the player and the seekMode setting.

Reflects the buffering value of the Video.state field and specifies that stream buffering is in progress. To capture the buffering progress in real-time, an event listener should be set into the Video.bufferingStatus

duration To be implemented
timedMetaData To be implemented
timeout

ASSOCIATIVEARRAY

  • contentIndex INTEGER REQUIRED

    Specifies the video index.

  • bufferingStatus ASSOCIATIVEARRAY NATIVE REQUIRED

    Provides the native Video.bufferingStatus field value.

  • retry BOOLEAN REQUIRED

    Specifies if bcPlayer will retry video playback with a different source. This depends on the bcPlayer.retryOnBufferTimeout flag value.

Triggered when video buffering times out. This event is only applicable if the bcPlayer.bufferTimeout field is set to a value higher than 0.

dialogClose

BOOLEAN

  • true an error dialog has been closed by a user action.

  • false not used.

Triggered when an error dialog is closed by a user action, usually pressing the Dialog Close button.

mute To be implemented
size

ASSOCIATIVE ARRAY

  • width

  • height

Triggered when the width or height bcPlayer native fields change, although it will only trigger if both values are higher than zero.

isHidden

BOOLEAN

  • true → bcPlayer is partially or completely hidden.

  • false → bcPlayer is completely visible in the screen.

Triggered when the bcPlayer node visibility changes. This event is controlled by a renderTracking field value, which means that it’s set to true when the renderTracking field is set to none and false otherwise.

Be aware that this event might not be 100% accurate in certain situations due to the way the Roku OS handles the native Video node, preventing the native renderTracking function from working properly within the Video node.

close

ASSOCIATIVE ARRAY

  • type STRING REQUIRED

    • soft → Specifies that a soft close was requested.
    • hard → Specifies that a hard close was requested.

Triggered when bcPlayer close action is called. This action can be called by developers themselves through the bcPlayer.callFunc("close", true/false) function or automatically by the closeOnAuto or closeOnFinished configurations (when enabled).

The type property specifies what type of close action was requested, soft or hard.

  • soft → the current playback session, if set, is terminated and the content is cleared. bcPlayer internal components remain on standby.
  • hard → bcPlayer is completely terminated/killed. Once a hard close is requested, it’s not possible to use the same bcPlayer instance anymore.

Keep in mind that the hard close process is asynchronous. If, for example, there are any HTTP requests ongoing, it’ll wait for those requests to complete and only then end the close process. At that point, the bcPlayer.on.closed event is triggered specifying that the bcPlayer was completely terminated.

closed

BOOLEAN

  • true the bcPlayer node has been completely terminated.

  • false not used.

Triggered when bcPlayer and it’s internal components were completely terminated by a hard close. At this point, the bcPlayer node reference cannot be used as it’s internal functions are no longer available.

Typically, this is where all bcPlayer references and field observers in the app are removed / unobserved.

logOutput

ASSOCIATIVE ARRAY

Provides an ASSOCIATIVE ARRAY object with the following keys:

  • level INTEGER REQUIRED

    Specifies the log level:

    • 0: error.

    • 1: warning.

    • 2: info.

    • 3: verbose.

    • 4: debug.

  • time INTEGER REQUIRED

    Provides the date/time as the number of seconds from the Unix epoch (00:00:00 1/1/1970 GMT).

  • message STRING REQUIRED

    Provides the log message.

  • params ANY REQUIRED

    Provides other helpful data. This can be any value, including invalid when no data is set.

Allows access to the internal bcPlayer logs, which are triggered by an internal Logger node.

The log level can be configured through the logLevel field, allowing to control the amount of logs coming through the logOutput event.

keyEvent

ASSOCIATIVE ARRAY

Provides an ASSOCIATIVE ARRAY object with the following keys:

  • key STRING REQUIRED

    Specifies the button that was pressed/released.

  • press BOOLEAN REQUIRED

    • true: the button was pressed.

    • false: the button was released.

  • handled BOOLEAN REQUIRED

    Indicates if the event was handled internally by bcPlayer.

Triggered when the user presses and releases a remote control button and the button event is captured in the bcPlayer node.

Keep in mind that some button events are captured by the native Video node, in which case bcPlayer won’t be able to capture it and make it available in this event.

voiceCommand

[TBI]

Code Snippet

                sub init()

   m.bcPlayer = createObject("roSGNode", "bcLib:bcPlayer")
 
   ' setup an event listener specifically for the "finished" event
   m.bcPlayer.on.observeField("finished", "onFinished")
   
   ' its also possible to handle all the events in a single event listener function
   m.bcPlayer.on.observeField("finished", "onPlayerEvent")
   m.bcPlayer.on.observeField("error", "onPlayerEvent")
 
 end sub
 
 ' create the event listener function where the event data can be accessed
 sub onFinished(ev)
   
   data = ev.getData()   ' data contains the "finished" event data
   
   ' handle the "finished" event here...
   
 end sub
 
 ' create a universal event listener function where all the events can be handled
 sub onPlayerEvent(ev)
   
   ' "data" contains the event data
   data = ev.getData()

   ' "event" contains the event name ("finished" or "error" in this example)
   event = ev.getField()
   
   ' handle the event here... 
   ' typically there should be an if or switch structure to filter the events
   
 end sub
                

ssai

NODE

Allows to configure SSAI support in the bcPlayer.

Live video streams only support SSAI service provided by Brightcove.

When setting up SSAI in a Brightcove video, the bcPlayer will automatically set the adsData field in the video ContentNode node. This field stores all the SSAI details, including the parsed VAST/VMAP data and it’s required to initialize RAF. Currently Brightcove SSAI sources will automatically create the adsData field, but it should also be possible to adapt it to work with custom metadata and other SSAI providers (VOD sources only), like so:

                m.bcPlayer = createObject("roSGNode", "bcLib:bcPlayer") 

                ' enable SSAI handling
                m.bcPlayer.ssai.enabled = true
                
                ' setup the custom metadata you wish to load through the loadCustom function and add the adsData property
                ' this function should start video playback automatically
                m.bcPlayer.callFunc("loadCustom", {
                  ...                                 ' add the custom metadata properties
                  Url: "https://my.ssai.video.url"    ' make sure to set the video URL. This should be a stitched video, containing both the ads and the content
                  StreamFormat: "hls/dash"            ' set the stream format
                  adsData: {                          ' adsData should be an AssociativeArray object
                    type: "ssai",                     ' specifies that this is a SSAI enabled video
                    adBreaks: < adBreaks-ad-structure>  ' provide the Ad Structure array as requested by Roku. This information is usually parsed from a VAST/VMAP document
                  }
                })
                

Through the bcPlayer.ssai.macros field it’s possible to specify a set of macros that will get replaced in the ad tag (please check the bcPlayer.ssai.macros field description in the table below for more details), but it’s also possible to add custom macros into the ad tag as well, by setting up the vmapMacros field in the video ContentNode node. vmapMacros should be an Associative Array object and all the key-value pairs provided will be added into the ad tag (please be aware that it doesn’t check if the macro is already present in the ad tag, if it is, it’ll add it anyway).

                    sub init()
  
                        m.bcPlayer = createObject("roSGNode", "bcLib:bcPlayer")
                      
                        ' enable SSAI handling
                        m.bcPlayer.ssai.enabled = true
                      
                        ' request the SSAI ready video metadata through PAPI and disable the autoload flag so that the metadata can be adjusted before loading it into bcPlayer
                        ' if you already have the metadata, you can skip this step and move on to the onVideoResponse() logic where the vmapMacros property is added.
                        rNode = m.bcPlayer.callFunc("getVideo", SSAIVideoID, { autoload: false })
                        if rNode <> invalid then rNode.observeField("response", "onVideoResponse")
                        
                      end sub
                      
                      sub onVideoResponse(ev)
                        
                        data = ev.getData()
                        if data.code <> 200 then
                          
                          ' handle the error
                          return
                          
                        end if
                        
                        metadata = data.body
                        
                        ' setup the vmapMacros property. 
                        ' List all the custom macros you wish to add into the ad tag
                        ' Make sure that these macros are not repeated in the bcPlayer.ssai.macros field, otherwise the ad tag might end up with duplicated macros
                        metadata.vmapMacros = {
                          myCustomMacro: "hello-world"
                        }
                        
                        ' load the metadata into bcPlayer
                        m.bcPlayer.callFunc("load", metadata)
                        
                      end sub
                    

Fields

Field Description
enabled

BOOLEAN OPTIONAL

Toggles SSAI support on and off. If set to false (the default value), SSAI will be disabled on all videos.

    Possible values:
  • false DEFAULT disables SSAI in the bcPlayer.

  • true enables SSAI in the bcPlayer.

enableDiscontinuities

BOOLEAN OPTIONAL

Toggles discontinuities/multiperiods in Brightcove sources. More info here.

    Possible values:
  • true DEFAULT enables playback with Discontinuities in HLS & MultiPeriods in Dash. Sets the rule query parameter in the video source URL to discos-enabled.

  • false sets the rule query parameter in the video source URL to discos-disabled.

adMeasurements

ASSOCIATIVE ARRAY OPTIONAL

Allows to specify custom ad measurement properties. These properties are usually retrieved for the video ContentNode, but their values can be overridden through this setting.

Be aware that these properties have to be set and/or reset for each video individually.

    Possible values:
  • invalid Disables all the ad measurement properties. Please keep in mind this will also affect some of the Roku macros that get their values from this setting. This essentially means that ad measurements will be disabled through RAF’s enableAdMeasurements() function.

  • {} DEFAULT initializes all properties with their default values.

  • Supported properties in the AssociativeArray object:
    • childDirected STRING OPTIONAL

      Specifies if the video contains child directed content. This value is used to set RAF’s setContentGenre() function parameter. It’s also used to set the ROKU_ADS_KIDS_CONTENT Roku macro value.

      • DEFAULT false

    • contentid STRING OPTIONAL

      Specifies the video ID. If not provided, the id field of the video ContentNode is used. This property is used to set RAF’s setContentId() function parameter. It’s also used to set the ROKU_ADS_CONTENT_ID Roku macro value.

      • DEFAULT ContentNode.id

    • contentGenre STRING OPTIONAL

      Specifies the video genre. If not provided, the Categories or tags fields of the video ContentNode are used, in that order specifically. This property is used to set RAF’s setContentGenre() function parameter. It’s also used to set the ROKU_ADS_CONTENT_GENRE Roku macro value.

      • DEFAULT the first applicable option:

        • If ContentNode.Categories is set, joins all items in the array, separated by a comma.
        • if ContentNode.tags is set, joins all items in the array, separated by a comma.
        • ""
    • contentLength NUMBER OPTIONAL

      Specifies the video content length. If not provided, the Length field of the video ContentNode is used. This property is used to set RAF’s setContentLength() function parameter. It’s also used to set the ROKU_ADS_CONTENT_LENGTH Roku macro value. On live streams, this value is set to 999999.

      • DEFAULT the first applicable option:

        • if it’s a live stream: 999999
        • ContentNode.Length
        • 0
bcovToken

STRING OPTIONAL

Specifies a Brightcove authentication JWT. This allows SSAI videos to use a different token than the one provided through the bcPlayer.credentials.auth_token property. If not provided, it’ll use the bcPlayer.credentials.auth_token token, if available. Essentially, this property adds the bcov_auth query parameter to the source URL.

    Possible values:
  • "" DEFAULT uses bcPlayer.credentials.auth_token token if available, otherwise ignores it.

  • "<JWT>" sets the bcov_auth query parameter with the token provided.

macros

ASSOCIATIVE ARRAY OPTIONAL

Specifies a list of macros that will get replaced in the video ad tag source URL (VMAP). These only apply to the query parameters identified with {{url.<macro>}}.

For example, if the VMAP ad tag URL contains the following query parameter: ...&foobar=..., setting bcPlayer.ssai.macros to {foo: "bar"} would replace with bar and in the end it would look like so: ...&foobar=bar...

Roku macros can also be used as a macro value. Using the same ad tag example, setting bcPlayer.ssai.macros to {foo: "{ROKU_ADS_DISPLAY_WIDTH}"} would replace {{url.foo}} with the display width value and in the end it would look like so: ...&foobar=1080.... The list of supported macros can be found here.

Be aware that the ROKU_ADS_CONTENT_ID, ROKU_ADS_CONTENT_GENRE, ROKU_ADS_CONTENT_LENGTH and ROKU_ADS_KIDS_CONTENT macros value depend on their respective bcPlayer.ssai.adMeasurements values, so if ad measurements are disabled, these macros won’t be available. More info here.

    Possible values:
  • {} DEFAULT No query parameters are replaced.

  • {<key-value-pairs-of-macros>}

event

ASSOCIATIVE ARRAY READ-ONLY

Read-only property that allows access to ad related events triggered by RAF through the setTrackingCallback() function as well as other custom events. Check below the list of all the possible events. Keep in mind that other RAF specific events not listed here might also be available in some specific situations.

Possible values:

An Associative Array object with the following properties:

  • event STRING REQUIRED

    Specifies the event name. The supported values include:

    • Custom events
      • error - an error occurred while processing the ads (the VMAP download or parsing failed)

      • vmap-request - VMAP download has started. The data property contains the VMAP URL.

      • vmap-parse - VMAP parse complete. The data property contains the parsed data.

      • vmap-response - VMAP download complete. The data property contains the response object. If the download fails, an errorevent is triggered instead.

      • raf-init - RAF lib was initialized and all configs were set (except for the adBreaks).

      • raf-pods - The adBreaks were loaded into RAF through the stitchedAdsInit function. The data property contains the list of adBreaks structured as required by Roku (reference).

    • RAF events
      • raf-podstart - An adPod started playing. data contains the adPod details.

      • raf-impression - An ad started playing. data contains the ad details.

      • raf-pause - The user paused the video during ad playback.

      • raf-resume - The user resumed the video during ad playback.

      • raf-complete - An ad finished playing.

      • raf-podcomplete - An adPod finished playing.

      • raf-close - Playback was terminated by the user (usually when the back button is pressed in the remote control).

    • data ASSOCIATIVE ARRAY OPTIONAL

      Provides the data related to the event. This property might not be available in some events.

    • index INTEGER REQUIRED

      Specifies the index of the currently playing asset in a playlist or 0 if a single video is playing.

    • live BOOLEAN REQUIRED

      Specifies if the currently playing asset is a live stream.

Code snippet

                            m.bcPlayer = createObject("roSGNode", "bcLib:bcPlayer")
                            m.bcPlayer.ssai.enabled = true ' enable SSAI
                            m.bcPlayer.ssai.adMeasurements = { childDirected: true } ' specify that child directed videos will play. Make sure to reset this property when playing non-child directed videos
                            m.bcPlayer.ssai.observeField("event", "onSSAIEvent")
                            
                            ...
                            
                            sub onSSAIEvent(ev)
                              ? "SSAI Event: " ev.getData()
                            end sub
                            

csai

Allows to configure CSAI support in the bcPlayer.

bcPlayer employs Roku's Client-Side Ad Stitching (CSAS) solution for CSAI handling.

When playing videos with CSAS, RAF creates its own internal Video nodes to seamlessly stitch video content and ad content together. This means that the bcPlayer native Video fields won't be able to control video playback or get the usual playback events. Alternatively, while playing CSAS videos, the following options are available:

  • RAFContentRenderer

    This node is created and handled by RAF and replaces bcPlayer as the playback controller. It contains most of the Video node fields so they can be observed and updated as required (such as the Video control, state and position fields). This node is added as a child of bcPlayer and its reference can be obtained through the start CSAI event (available in bcPlayer.csai.event).

  • bcPlayer.playback

    The playback function should automatically detect CSAS video playback and is able to control the video playback (if RAF allows it).

  • bcPlayer.csai.event

    The playback The event property is specially important for CSAS video playback because this is where all the video content and ads playback events can be accessed. Check the table below for this list of all the supported events.

To setup CSAS in a video, the adsData property should be manually added into the metadata before loading it into the bcPlayer, like so:

  • Brightcove sources

                            sub playVideoWithCSAI(videoID as String, adURL as String)
    
    ' videoID - Brightcove's VideoCloud video ID
    ' adURL - the CSAI VAST/VMAP document url
    
    ' initialize the bcPlayer (if not initialized yet)
      m.bcPlayer = createObject("roSGNode", "bcLib:bcPlayer")
                            
      ' enable CSAI video playback + set any other CSAI required configs
      m.bcPlayer.csai.enabled = true
      m.bcPlayer.csai.observeField("event", "onCSAIEvent") ' setup the event observer
                            
      ' retrieve the video metadata through the getVideo function
      ' disable autoload so that we can customize the metadata before loading it into bcPlayer
      ' pass the adURL along with the options so we can then retrieve it back in the response handler
      responseNode = m.bcPlayer.callFunc("getVideo", videoID, { autoload: false, adURL: adURL })
      if responseNode <> invalid then responseNode.observeField("response", "onResponse")
                            
    end sub
    
    sub onResponse(ev)
      
      response = ev.getData()
    
      if response.code <> 200 then
        ' handle the error
        return
      end if
    
      metadata = response.body
      adURL = response.options.adURL
      
      ' setup the adsData property in the video metadata
      metadata.adsData = {        ' adsData should be an AssociativeArray object
        type: "csai",             ' specifies that this is a CSAI enabled video
        vmap: adURL,              ' provide the VAST/VMAP document URL
        adBreakTimes: []          ' [optional] provide a set of adBreak times if applicable. This property is used in RAF's setAdBreaks() function
      }
      
      ' load the updated video metadata into bcPlayer and start video playback with CSAI
      m.bcPlayer.callFunc("load", metadata)
      
    end sub
                            

  • Custom sources
                                    sub playVideoWithCSAI(videoMetadata as Object, adURL as String)
      
       ' videoMetadata - custom video metadata
       ' adURL - the CSAI VAST/VMAP document url
       
       ' initialize the bcPlayer (if not initialized yet)
       m.bcPlayer = createObject("roSGNode", "bcLib:bcPlayer")
       
       ' enable CSAI video playback + set any other CSAI required configs
       m.bcPlayer.csai.enabled = true
       m.bcPlayer.csai.observeField("event", "onCSAIEvent") ' setup the event observer
       
       ' setup the adsData property in the video metadata
       videoMetadata.adsData = {   ' adsData should be an AssociativeArray object
         type: "csai",             ' specifies that this is a CSAI enabled video
         vmap: adURL               ' provide the VAST/VMAP document URL
         adBreakTimes: []          ' [optional] provide a set of adBreak times if applicable. This property is used in RAF's setAdBreaks() function
       }
       
       ' load video metadata into bcPlayer and start video playback with CSAS
       m.bcPlayer.callFunc("loadCustom", videoMetadata)
       
     end sub
                                    

Fields

Field Description
enabled

BOOLEAN OPTIONAL

Toggles CSAI support on and off. If set to false (the default value), CSAI will be disabled on all videos.

Possible values:

  • false DEFAULT - disables CSAI support in the bcPlayer.

  • true - enables CSAI support in the bcPlayer.

maxRequests

INTEGER OPTIONAL

Specifies the maximum number of attempts the getAds() function is allowed to make. This property allows RAF's setAdPrefs() function parameter to be customized.

DEFAULT 5

adMeasurements

ASSOCIATIVE ARRAY OPTIONAL

Allows to specify custom ad measurement properties. These properties are usually retrieved for the video ContentNode, but their values can be overridden through this setting.

Be aware that these properties have to be set and/or reset for each video individually.

Possible values:

  • invalid - Disables all the ad measurement properties. Please keep in mind this will also affect some of the Roku macros that get their values from this setting. This essentially means that ad measurements. will be disabled through RAF’s enableAdMeasurements() function.
  • {} DEFAULT - initializes all properties with their default values.
  • Supported properties in the AssociativeArray object:

    • childDirected STRING OPTIONAL

      Specifies if the video contains child directed content. This value is used to set RAF’s setContentGenre() function parameter. It’s also used to set the ROKU_ADS_KIDS_CONTENT Roku macro value.

      DEFAULT false

    • contentid STRING OPTIONAL

      Specifies the video ID. If not provided, the id field of the video ContentNode is used. This property is used to set RAF’s setContentId() function parameter. It’s also used to set the ROKU_ADS_CONTENT_ID Roku macro value.

      DEFAULT ContentNode.id

    • contentGenre STRING OPTIONAL

      Specifies the video genre. If not provided, the Categories or tags fields of the video ContentNode are used, in that order specifically. This property is used to set RAF’s setContentGenre() function parameter. It’s also used to set the ROKU_ADS_CONTENT_GENRE Roku macro value.

      DEFAULT the first applicable option:

      • If ContentNode.Categories is set, joins all items in the array, separated by a comma.

      • If ContentNode.tags is set, joins all items in the array, separated by a comma.

      • ""

    • contentLength NUMBER OPTIONAL

      Specifies the video content length. If not provided, the Length field of the video ContentNode is used. This property is used to set RAF’s setContentLength() function parameter. It’s also used to set the ROKU_ADS_CONTENT_LENGTH Roku macro value. On live streams, this value is set to 999999.

      DEFAULT the first applicable option:

      • if it’s a live stream: 999999.

      • ContentNode.Length

      • 0

adConstraints

ASSOCIATIVE ARRAY OPTIONAL

Specifies RAF’s setAdConstraints() function parameters.

Possible values

  • {} DEFAULT - Ignores the setAdConstraints() function.
  • Supported properties in the AssociativeArray object:
    • maxHeight INTEGER REQUIRED

      Maximum vertical dimension of renderable ad (in pixels).

    • maxWidth INTEGER REQUIRED

      Maximum horizontal dimension of renderable ad (in pixels).

    • maxBitrate INTEGER REQUIRED

      Maximum allowable bitrate for renderable ad streams (in Kbps).

    • supportedMimeTypes ASSOCIATIVE ARRAY OPTIONAL

      Associative array with entries of the form:

      {“mimeType”: “stream- Format”}

      If not provided, by default, the MIME types are configured for video/mp4, video/mp4-h264, video/x-mp4, application/x-mpegurl, and application/json.

event

ASSOCIATIVE ARRAY OPTIONAL

Read-only property that allows access to video content and ad related events triggered by RAF through the setTrackingCallback() function as well as other custom events. Check below the list of all the possible events. Keep in mind that other RAF specific events not listed here might also be available in some specific situations.

Possible values

An Associative Array object with the following properties:

  • event STRING REQUIRED

    Specifies the event name. The supported values include:

    • Custom events
      • raf-init - RAF lib was initialized and all configs were set (except for the adBreaks).

      • raf-pods - the adPods were retrieved through RAF’s getAds() function. The data property contains the list of adPods structured as required by Roku (reference).

      • start - the adPods have been loaded into RAF and video playback will now start. The RAFContentRenderer node reference is provided in the event data property. If no adPods are found, this event will not be triggered.

      • close - playback has finished or was interrupted.

    • RAF events
      • raf-state - equivalent to bcPlayer.state. Reports the video state (playing, paused, buffering, stopped, error and finished).

      • raf-position - equivalent to bcPlayer.position. Reports the current playback position.

      • raf-adrequest - reports all the ad requests executed by RAF’s getAds() function.

      • raf-podstart - An adPod started playing. data contains the adPod details.

      • raf-impression - An ad started playing. data contains the ad details.

      • raf-pause - video playback was paused.

      • raf-resume - video playback resumed.

      • raf-complete - An ad finished playing.

      • raf-podcomplete - An adPod finished playing.

      • raf-contentcomplete - video playback has reached the end.

      • raf-close - Playback was terminated by the user (usually when the back button is pressed in the remote control).

  • data ASSOCIATIVE ARRAY OPTIONAL

    Provides the data related to the event. This property might not be available in some events.

  • index INTEGER REQUIRED

    Specifies the index of the currently playing asset in a playlist or 0 if a single video is playing.

  • live BOOLEAN REQUIRED

    Specifies if the currently playing asset is a live stream.

Code snippet

                    m.bcPlayer = createObject("roSGNode", "bcLib:bcPlayer")
m.bcPlayer.csai.enabled = true ' enable CSAI
m.bcPlayer.csai.adMeasurements = { childDirected: true } ' specify that child directed videos will play. Make sure to reset this property when playing non-child directed videos
m.bcPlayer.csai.observeField("event", "onCSAIEvent")

...

sub onCSAIEvent(ev)
  ? "CSAI Event: " ev.getData()
end sub
                    

Functions

The bcPlayer node also provides some functions to interact with the Video content and playback.


Load

Loads Brightcove Playback API video or playlist metadata into the bcPlayer asynchronously. Usually the data entered in the load function comes from the bcAPI component available in the Brightcove SDK which retrieves videos data from the Playback API, but it’s also used internally by the getVideo, getVideos, getPlaylist and getRelated functions.

The load function triggers a bcPlayer.on.load event reporting on the success or failure of the load process.

Parameters:

  • data DYNAMIC REQUIRED Brightcove videos data to load into the bcPlayer for playback. This data can represent a single video or multiple videos. The possible values are:

    • A single video object ASSOCIATIVE ARRAY Video by ID/Reference

      • Expected metadata object structure:

                                                {
                                                    account_id: "<papi-video-account_id>"
                                                    sources: [<papi-video-sources>],
                                                    <...>
                                                  },
                                                
      • Any other properties in this object (besides account_id and sources) are automatically set as fields of the bcPlayer.content ContentNode, taking into account the following custom specifications:

        • If the title property isn't provided and a name property is, title is set to name. title is a native field of a ContentNode and it defines the title text shown in the top left corner of the player when using Roku's OOTB UI/UX.

        • If the length property isn’t provided and a duration property is, length is set to duration / 1000. length is a native field of a ContentNode and it specifies the length of a video in seconds. The duration property should contain the length of the video in milliseconds, if provided.

        • If the SDPosterUrl, HDPosterUrl and FHDPosterUrl properties aren’t provided and a poster property is, these three properties are set to the poster property value. poster should provide the video poster image URL. SDPosterUrl, HDPosterUrl and FHDPosterUrl are native fields of a ContentNode and, although not required in the bcPlayer node, they might be useful in a MarkupGrid, RowList or similar Roku components.

        • If the live property isn't provided, live is set based on the value of the duration property. live is a native field of a ContentNode and it identifies a live video, which may impact the behavior of Roku’s OOTB UI/UX.

          • If duration is not provided or its value is 0 or below: live is set to true.

          • If duration value is above 0: live is set to false.

        • If the video is considered a live stream (live = true) and the playstart property isn't provided, playstart is set to 2147483647. This forces the player to start playback from the live stream position.

    • A playlist object ASSOCIATIVE ARRAY Playlist by ID/Reference

      • Expected metadata object structure:

                                                {
                                                    videos: [
                                                      {
                                                        account_id: "<papi-video-account_id>"
                                                        sources: [<papi-video-sources>],
                                                        <...<
                                                      },
                                                      <...<
                                                    ],
                                                    <...<
                                                  }
                                                
      • This metadata is loaded into a Video playlist ContentNode structure.

      • Any other properties in this object (besides videos) are automatically set as fields of the parent ContentNode in the bcPlayer.content field.

    • An array containing a set of videos ARRAY Related Videos or Video Search

      • Expected metadata object structure:

                                                
                                                    [
                                                      {
                                                        account_id: "<papi-video-account_id>"
                                                        sources: [<papi-video-sources>],
                                                        <...<
                                                      },
                                                      <...<
                                                    ]
                                                
      • This metadata is loaded into a Video playlist ContentNode structure.

  • options ASSOCIATIVE ARRAY OPTIONAL

    Additional options that allow some behavior to be customized. The following properties can be set in this object:

    • autoplay INTEGER OPTIONAL Specifies the index of the video that should start playing when the load process ends (in case of a playlist). A value of -1 will prevent the video from auto playing when the load process ends. By default autoplay is set to 0.

    • prebuffer BOOLEAN OPTIONAL

      Specifies if it should start prebuffering the video stream indicated in the autoplay option.

      • false DEFAULT

        if autoplay is set (ie, >= 0), video playback will start when the loading process finishes

      • true

        if autoplay is set (ie, >= 0), video prebuffering will be initiated when the loading process finishes

    • position STRING OPTIONAL Specifies where the new data should be loaded if bcPlayer already has content. Ie, should the data replace the old content, should it be added to the end or start of the current content. Possible values:

      • replace DEFAULT

        Replace previous contents with the new content. If position isn't specified, replace is used by default. If the current content is a single video, the new content will always replace it.

      • append

        Add the new content at the end of the current content. Only applicable if the current content is a playlist.

      • prepend

        Add the new content at the start of the current content. Only applicable if the current content is a playlist.

Return Value

BOOLEAN Indicates if the load process was properly initiated.

Code snippet

                    sub init()
                        m.bcPlayer = createObject("roSGNode", "bcLib:bcPlayer")
                
                        ' load video data returned by the Playback API
                        m.bcPlayer.callFunc("load", videoMetadata)
                
                        ' OR
                
                        ' Set some options to customize the playlist loading behavior
                        m.bcPlayer.callFunc("load", playlistMetadata, {
                          autoplay: 3 ' start playing the video in the index 3 of the playlist
                          position: "end" ' append the playlist to the current contents
                          })
                
                        ' OR
                
                        ' it's also possible to manually customize Playback API metadata before loading it into bcPlayer
                        ' start by requesting a specific video metadata from the Playback API, specifying the "autoload" config property as false so it returns back a response node
                        rNode = m.bcPlayer.callFunc("getVideo", videoID, { autoload: false })
                
                        ' make sure the response Node is available so it can be used to retrieve the response metadata
                        if rNode <> invalid then
                
                          ' set up an observer function for the "response" field
                          rNode.observeField("response", "onVideoResponse")
                
                        end if
                
                      end sub
                
                      sub onVideoResponse(ev)
                
                        ' ev.getData() returns the Playback API response properties
                        response = ev.getData()
                
                        ' if the request failed for any reason, handle the error
                        if response.code <> 200 then
                          ' handle the failed request here
                          return
                        end if
                
                        ' the "body" property contains the Video metadata
                        videoMetadata = response.body
                
                        ' if needed, "videoMetadata" can be customized here before feeding it into the "load" function (keep in mind some properties shouldn't be changed)
                
                        ' load the customized video metadata into bcPlayer for playback
                        m.bcPlayer.callFunc("load", videoMetadata)
                
                      end sub
                    

loadCustom

Asynchronously loads custom metadata (a video or set of videos) into the bcPlayer. This function should be used to load non-Brightcove videos metadata.

Developers should provide the required playback properties as specified by Roku in their documentation page.

The loadCustom function triggers a bcPlayer.on.load event reporting on the success or failure of the load process.

Parameters:

  • metadata ASSOCIATIVE ARRAY REQUIRED

    The video or playlist metadata to load into the bcPlayer for playback. All data is loaded as is into a ContentNode. The possible values are:

    • A single video ASSOCIATIVE ARRAY

      If an Associative Array object is provided, a single ContentNode is created and all key-value pairs are set as its fields.

    • A set of videos ARRAY

      If an Array of Associative Arrays is provided, the ContentNode is structured as a playlist where the videos ContentNodes are added into the parent playlist ContentNode.

  • options ASSOCIATIVE ARRAY OPTIONAL

    Additional options allow some behaviors to be customized. The following properties can be set in this object:

    • autoplay INTEGER OPTIONAL

      Specifies the index of the video that should start playing when the load process ends (in case of a playlist).

      • 0DEFAULT

        Plays the first video in the playlist or the loaded video if not a playlist.

      • -1

        Disables auto playback. This might be useful to preload / prebuffer the video.

    • prebuffer BOOLEAN OPTIONAL

      Specifies if it should start prebuffering the video stream indicated in the autoplay option.

      • false DEFAULT

        if autoplay is set (ie, >= 0), video playback will start when the loading process finishes

      • true

        if autoplay is set (ie, >= 0), video prebuffering will be initiated when the loading process finishes

    • position STRING OPTIONAL

      Specify the position the new metadata should be load into if bcPlayer already contains previous contents. The possible string values are:

      • replaceDEFAULT

        Replace previous contents with the new content. If position isn't specified, replace is used by default. If the current content is a single video, the new content will always replace it.

      • append

        Add the new content at the end of the current content. If the current content is not a playlist, a new playlist is created and both the current and new content are added to the playlist.

      • prepend

        Add the new content at the start of the current content. If the current content is not a playlist, a new playlist is created and both the current and new content are added to the playlist.

Return value

BOOLEAN Indicates if the load process was properly initiated.

Code snippet

                        sub init()
                          m.bcPlayer = createObject("roSGNode", "bcLib:bcPlayer")
                    
                          ' load custom video metadata
                          m.bcPlayer.callFunc("loadCustom", {
                            Url: "https://my.video.url",  ' make sure the required playback fields are set, like Url, Streams or StreamUrls
                            StreamFormat: "hls",          ' specify the StreamFormat when using the Url field
                            PlayStart: 40,                ' start playback at 40 seconds
                            myCustomField: "hello world"  ' custom fields can also be set, all properties are added as is
                          })
                    
                        end sub
                        

getVideo

Retrieves a specific Brightcove video through Playback API, if configured to do so, loads its metadata into bcPlayer, and starts playback.

Playback API reference.

Parameters:

  • id STRING REQUIRED

    Brightcove video ID or video reference ID to be retrieved. To get a video using a video reference ID, id must be formatted like so: ref: <reference_id>.

  • options ASSOCIATIVE ARRAY OPTIONAL

    Additional options to allow for some behaviors to be customized. The following properties can be set in this object:

    • params ASSOCIATIVE ARRAY OPTIONAL

      Playback API request parameters as specified in the Playback API Reference. The following properties are supported:

      • ad_config_id STRING OPTIONAL

        Include server-side ad insertion.

      • config_id STRING OPTIONAL

        Include and set equal to the delivery rules id in order to have the delivery rules applied.

    • autoload BOOLEAN OPTIONAL

      Specifies if the video metadata should be loaded into bcPlayer once the request response is available.

      • true DEFAULT

        Video metadata will automatically be loaded into bcPlayer. The load behavior can be customized through the autoplay and position options.

      • false

        When autoload is disabled, getVideo will only retrieve Brightcove video metadata. In this case, getVideo immediately returns a Node object which contains a response field that can be used to setup an observer function to capture the request response data.

    • autoplay INTEGER OPTIONAL

      [To be implemented] Specifies the index of the video that should start playing when the load process ends (in case of a playlist). A value of -1 will prevent auto playback when the load process ends. By default autoplay is set to 0. this property is passed along to the load function, which is responsible for the metadata load process. Ignored if autoload is disabled.

    • position STRING OPTIONAL

      Specify the position the new metadata should be load into if bcPlayer already contains previous contents. Internally. this property is passed along to the load function, which is responsible for the metadata load process. Ignored if autoload is disabled. The possible string values are:

      • replace DEFAULT

        Replace previous contents with the new content. If position isn't specified, replace is used by default.

      • append

        Add the new content at the end of the current content.

      • prepend

        Add the new content at the start of the current content.

    • <custom-prop> DYNAMIC OPTIONAL

      It’s also possible to specify custom properties to be passed along to the response object. These are especially useful when the autoload option is disabled. On the other hand, if the autoload option is enabled, these properties are ignored.

Return Value

  • invalid

    Returns invalid if autoload is enabled.

  • Node

    Returns a Node object if autoload is disabled. This Node contains a response field which can be used to setup an observer function where the request response can be captured.

Code Snippet

                        sub init()
 ' autoload enabled
 m.bcPlayer.callFunc("getVideo", videoID, {
   params: {ad_config_id: adConfigID},
   autoplay: -1
 })

 ' OR

 ' autoload disabled
 responseNode = m.bcPlayer.callFunc("getVideo", videoID, {
   params: {ad_config_id: adConfigID},
   autoload: false,
   myCustomOption: "hello world"
 })

 ' make sure the response Node is available so it can be used to retrieve the response metadata
 if responseNode <> invalid then

 ' set up an observer function for the "response" field
 responseNode.observeField("response", "onVideoResponse")

 end if

 end sub

 sub onVideoResponse(ev)

 ' ev.getData() returns the Playback API response properties
 response = ev.getData()

 ' if the request failed for any reason, handle the error
 if response.code <> 200 then
   ' handle the failed request here
   return
 end if

 options = response.options 

 ' retrieve the custom properties from the response object
  myCustomOption = options.myCustomOption

 ' the "body" property contains the Video metadata
 videoMetadata = response.body

 ' if needed, "videoMetadata" can be customized here before feeding it into the "load" function (keep in mind some properties shouldn't be changed)

 ' load the customized video metadata into bcPlayer for playback
 m.bcPlayer.callFunc("load", videoMetadata, {
   autoplay: -1
 })

 end sub
                        

getVideos

Retrieves a set of Brightcove videos through Playback API and, if configured to do so, loads its metadata into bcPlayer and starts playback.

This option is commonly used to programmatically search for Brightcove videos.

Playback API reference.

Parameters:

  • query STRING REQUIRED

    Search query used to retrieved a set of Brightcove videos. More details about the search query format, CMS/Playback API.

  • options ASSOCIATIVE ARRAY OPTIONAL

    Additional options to allow for some behaviors to be customized. The following properties can be set in this object:

    • params ASSOCIATIVE ARRAY OPTIONAL

      Playback API request parameters as specified in the Playback API Reference. The following properties are supported:

      • limit INTEGER OPTIONAL

        The number of videos to return.

      • offset INTEGER OPTIONAL

        The number of videos to skip - used to page multiple sets of videos.

      • sort STRING OPTIONAL

        Field to sort results by. Check the Playback API Reference for all the possible values.

      • ad_config_id STRING OPTIONAL

        Include server-side ad insertion.

      • config_id STRING OPTIONAL

        Include and set equal to the delivery rules id in order to have the delivery rules applied.

    • autoload BOOLEAN OPTIONAL

      Specifies if the videos metadata should be loaded into bcPlayer once the request response is available.

      • true DEFAULT

        Videos metadata will automatically be loaded into bcPlayer. The load behavior can be customized through the autoplay and position options.

      • false

        When autoload is disabled, getVideos immediately returns a Node object which contains a response field that can be used to setup an observer function to capture the request response details.

    • autoplay INTEGER OPTIONAL

      Specifies the index of the video that should start playing when the load process ends (in case of a playlist). A value of -1 will prevent auto playback when the load process ends. By default autoplay is set to 0. this property is passed along to the load function, which is responsible for the metadata load process. Ignored if autoload is disabled.

    • position STRING OPTIONAL

      Specify the position the new metadata should be load into if bcPlayer already contains previous contents. Internally. this property is passed along to the load function, which is responsible for the metadata load process. Ignored if autoload is disabled. The possible string values are:

      • replace DEFAULT

        Replace previous contents with the new content. If position isn't specified, replace is used by default.

      • append

        Add the new content at the end of the current content.

      • prepend

        Add the new content at the start of the current content.

    • <custom-prop> DYNAMIC OPTIONAL

      It’s also possible to specify custom properties to be passed along to the response object. These are especially useful when the autoload option is disabled. On the other hand, if the autoload option is enabled, these properties are ignored.

Return Value

  • invalid

    Returns invalid if autoload is enabled.

  • Node

    Returns a Node object if autoload is disabled. This Node contains a response field which can be used to setup an observer function where the request response can be captured.

Code Snippet

                        sub init()
                            ' autoload enabled
                            m.bcPlayer.callFunc("getVideos", "name:wildlife", {
                              params: {limit: 10, offset: 20},
                              autoplay: -1
                            })
                    
                            ' OR
                    
                            ' autoload disabled
                            responseNode = m.bcPlayer.callFunc("getVideos", "name:wildlife", {
                              params: {limit: 10, offset: 20},
                              autoload: false,
                              myCustomOption: "hello world"
                            })
                    
                            ' make sure the response Node is available so it can be used to retrieve the response metadata
                            if responseNode <> invalid then
                    
                              ' set up an observer function for the "response" field
                              responseNode.observeField("response", "onVideosResponse")
                    
                            end if
                    
                          end sub
                    
                          sub onVideosResponse(ev)
                    
                            ' ev.getData() returns the Playback API response properties
                            response = ev.getData()
                    
                            ' if the request failed for any reason, handle the error
                            if response.code <> 200 then
                              ' handle the failed request here
                              return
                            end if

                            options = response.options 
                            
                            ' retrieve the custom properties from the response object
                            myCustomOption = options.myCustomOption

                            ' the "body" property contains videos metadata
                            videosMetadata = response.body
                    
                            ' if needed, "videosMetadata" can be customized here before feeding it into the "load" function (keep in mind some properties shouldn't be changed)
                    
                            ' load the customized videos metadata into bcPlayer for playback
                            m.bcPlayer.callFunc("load", videosMetadata, {
                              autoplay: -1
                            })
                    
                          end sub
                        

getPlaylist

Retrieves a Brightcove playlist through Playback API and, if configured to do so, loads its metadata into bcPlayer and starts playback.

Playback API reference.

Parameters:

  • id STRING REQUIRED

    Brightcove playlist ID or reference ID to be retrieved. To get a playlist using a playlist reference ID, id must be formatted like so: ref:<reference_id>.

  • options ASSOCIATIVE ARRAY OPTIONAL

    Additional options to allow for some behaviors to be customized. The following properties can be set in this object:

    • params ASSOCIATIVE ARRAY OPTIONAL

      Playback API request parameters as specified in the Playback API Reference. The following properties are supported:

      • limit INTEGER OPTIONAL

        The number of videos to return.

      • offset INTEGER OPTIONAL

        The number of videos to skip - used to page multiple sets of videos.

      • ad_config_id STRING OPTIONAL

        Include server-side ad insertion.

      • config_id STRING OPTIONAL

        Include and set equal to the delivery rules id in order to have the delivery rules applied.

    • autoload BOOLEAN OPTIONAL

      Specifies if the playlist metadata should be loaded into bcPlayer once the request response is available.

      • true DEFAULT

        Playlist metadata will automatically be loaded into bcPlayer. The load behavior can be customized through the autoplay and position options.

      • false

        When autoload is disabled, getPlaylist only retrieve Brightcove videos metadata. In this case, getPlaylist returns a Node object which contains a response field that can be used to setup an observer function to capture the request response details.

    • autoplay INTEGER OPTIONAL

      Specifies the index of the video that should start playing when the load process ends. A value of -1 will prevent auto playback when the load process ends. By default autoplay is set to 0. this property is passed along to the load function, which is responsible for the metadata load process. Ignored if autoload is disabled.

    • position STRING OPTIONAL

      Specify the position the new metadata should be load into if bcPlayer already contains previous contents. Internally. this property is passed along to the load function, which is responsible for the metadata load process. Ignored if autoload is disabled. The possible string values are:

      • replace DEFAULT

        Replace previous contents with the new content. If position isn't specified, replace is used by default.

      • append

        Add the new content at the end of the current content.

      • prepend

        Add the new content at the start of the current content.

    • <custom-prop> DYNAMIC OPTIONAL

      It’s also possible to specify custom properties to be passed along to the response object. These are especially useful when the autoload option is disabled. On the other hand, if the autoload option is enabled, these properties are ignored.

Return Value

  • invalid

    Returns invalid if autoload is enabled.

  • Node

    Returns a Node object if autoload is disabled. This Node contains a response field which can be used to setup an observer function where the request response can be captured.

Code Snippet

                        sub init()
                            ' autoload enabled
                            m.bcPlayer.callFunc("getPlaylist", playlistID, {
                              params: {limit: 10, offset: 20},
                              autoplay: 3
                            })
                    
                            ' OR
                    
                            ' autoload disabled
                            responseNode = m.bcPlayer.callFunc("getPlaylist", playlistID, {
                              params: {limit: 10, offset: 20},
                              autoload: false,
                              myCustomOption: "hello world"
                            })
                    
                            ' make sure the response Node is available so it can be used to retrieve the response metadata
                            if responseNode <> invalid then
                    
                              ' set up an observer function for the "response" field
                              responseNode.observeField("response", "onPlaylistResponse")
                    
                            end if
                    
                          end sub
                    
                          sub onPlaylistResponse(ev)
                    
                            ' ev.getData() returns the Playback API response properties
                            response = ev.getData()
                    
                            ' if the request failed for any reason, handle the error
                            if response.code <> 200 then
                              ' handle the failed request here
                              return
                            end if

                            options = response.options

                            ' retrieve the custom properties from the response object
                            myCustomOption = options.myCustomOption
                    
                            ' the "body" property contains the playlist metadata
                            playlistMetadata = response.body
                    
                            ' if needed, "playlistMetadata" can be customized here before feeding it into the "load" function (keep in mind some properties shouldn't be changed)
                    
                            ' load the customized playlist metadata into bcPlayer for playback
                            m.bcPlayer.callFunc("load", playlistMetadata, {
                              autoplay: 3 ' TBI feature
                            })
                    
                          end sub
                    
                        

getRelated

ASSOCIATIVE ARRAY

Retrieves a set of Brightcove videos that are related to the specified video id through Playback API.

Using the name and short description of the specified video id, the Playback API searches for videos with any partial matches in the following fields: name, short_description, long_description, tags.

Playback API reference.

Parameters:

  • id STRING REQUIRED

    Brightcove playlist ID or reference ID to be retrieved. To get a playlist using a playlist reference ID, id must be formatted like so: ref:<reference_id>.

  • options ASSOCIATIVE ARRAY OPTIONAL

    Additional options to allow for some behaviors to be customized. The following properties can be set in this object:

    • params ASSOCIATIVE ARRAY OPTIONAL

      Playback API request parameters as specified in the Playback API Reference. The following properties are supported:

      • limit INTEGER OPTIONAL

        The number of videos to return.

      • offset INTEGER OPTIONAL

        The number of videos to skip - used to page multiple sets of videos.

      • ad_config_id STRING OPTIONAL

        Include server-side ad insertion.

      • config_id STRING OPTIONAL

        Include and set equal to the delivery rules id in order to have the delivery rules applied.

    • autoload BOOLEAN OPTIONAL

      Specifies if the playlist metadata should be loaded into bcPlayer once the request response is available.

      • true DEFAULT

        Videos metadata will automatically be loaded into bcPlayer. The load behavior can be customized through the autoplay and position options [To be implemented].

      • false

        When autoload is disabled, getRelated only retrieve Brightcove videos metadata. In this case, getRelated returns a Node object which contains a response field that can be used to setup an observer function to capture the request response details.

    • autoplay INTEGER OPTIONAL

      Specifies the index of the video that should start playing when the load process ends. A value of -1 will prevent auto playback when the load process ends. By default autoplay is set to 0. this property is passed along to the load function, which is responsible for the metadata load process. Ignored if autoload is disabled.

    • position STRING OPTIONAL

      Specify the position the new metadata should be load into if bcPlayer already contains previous contents. Internally. this property is passed along to the load function, which is responsible for the metadata load process. Ignored if autoload is disabled. The possible string values are:

      • replace DEFAULT

        Replace previous contents with the new content. If position isn't specified, replace is used by default.

      • append

        Add the new content at the end of the current content.

      • prepend

        Add the new content at the start of the current content.

    • <custom-prop> DYNAMIC OPTIONAL

      It’s also possible to specify custom properties to be passed along to the response object. These are especially useful when the autoload option is disabled. On the other hand, if the autoload option is enabled, these properties are ignored.

Return Value

  • invalid

    Returns invalid if autoload is enabled.

  • Node

    Returns a Node object if autoload is disabled. This Node contains a response field which can be used to setup an observer function where the request response can be captured.

Code Snippet

                        sub init()
                            ' autoload enabled
                            m.bcPlayer.callFunc("getRelated", videoID, {
                              params: {limit: 10, offset: 20},
                              autoplay: 3 
                            })
                    
                            ' OR
                    
                            ' autoload disabled
                            responseNode = m.bcPlayer.callFunc("getRelated", videoID, {
                              params: {limit: 10, offset: 20},
                              autoload: false,
                              myCustomOption: "hello world"
                            })
                    
                            ' make sure the response Node is available so it can be used to retrieve the response metadata
                            if responseNode <> invalid then
                    
                              ' set up an observer function for the "response" field
                              responseNode.observeField("response", "onRelatedResponse")
                    
                            end if
                    
                          end sub
                    
                          sub onRelatedResponse(ev)
                    
                            ' ev.getData() returns the Playback API response properties
                            response = ev.getData()
                    
                            ' if the request failed for any reason, handle the error
                            if response.code <> 200 then
                              ' handle the failed request here
                              return
                            end if
                                
                            options = response.options 

                            ' retrieve the custom properties from the response object
                            myCustomOption = options.myCustomOption
                    
                            ' the "body" property contains the related videos metadata
                            relatedMetadata = response.body
                    
                            ' if needed, "relatedMetadata" can be customized here before feeding it into the "load" function (keep in mind some properties shouldn't be changed)
                    
                            ' load the customized related videos metadata into bcPlayer for playback
                            m.bcPlayer.callFunc("load", relatedMetadata, {
                              autoplay: 3 ' To be implemented feature
                            })
                    
                          end sub
                        

close

Initiates the close action, which depending on the parameter provided, terminates/kills bcPlayer completely (hard close) or just stops and clears the current playback session (soft close). By default, if no parameter is provided, it executes a hard close.

The hard close is an asynchronous process, at the end of which it triggers a bcPlayer.on.closed event to confirm that the close process is complete.

Once the close action is called, the bcPlayer.on.close event is also triggered specifying the type of close action that was called (soft or hard).

The close process can also be triggered internally by the closeOnBack and closeOnFinished configurations, if configured to do so.

Be aware that a hard close completely kills the bcPlayer node instance and it’s not possible to access/use its functions afterwards.

Parameters

  • kill BOOLEAN OPTIONAL

    • true DEFAULT

      Triggers a hard close action, which terminates/kills the bcPlayer instance completely.

    • false

      Triggers a soft close action, which stops the current playback session and clears the content. The bcPlayer node remains on standby waiting for other commands.

Return value

VOID

Code Snippet

                        sub init()

   ...

   ' listen for the "close" event, in case some action needs to be taken when closing bcPlayer
   m.bcPlayer.on.observeField("close", "onClose")

   ' listen for the "closed" event, which is only triggered by a hard close
   m.bcPlayer.on.observeField("closed", "onClosed")

   ' trigger the close action
   m.bcPlayer.callFunc("close")

 end sub

 sub onClose(ev)

   data = ev.getData() ' data => {type: "soft" / "hard"}

   ' bcPlayer close action was triggered, 
   ' data.type specifies what type of close was requested

 end sub

 sub onClosed()

   ' bcPlayer was completely terminated by a hard close action. 
   ' If there's still any bcPlayer reference in the app or fields observers, these
   ' should be removed / unobserved at this point

   m.bcPlayer.on.unobserveField("close")
   m.bcPlayer.on.unobserveField("closed")
   m.bcPlayer = invalid

 end sub
                        

Video Sources Selection

When playing a Videocloud video or playlist in the bcPlayer node through the load, playVideo, playVideos, playPlaylist and playRelated functions, the video/videos metadata is parsed and the video sources are filtered through the following stages:

Step Description
1

Sources go through an initial filtering process where one source is selected per stream type (HLS and DASH), DRM system (Widevine, Playready and no DRM) and protocol (HTTP/HTTPS).

Sources are added to the mapping object according to the following prioritization rules:

  • MP4 sources (per protocol)

    • All MP4 sources that contain the avg_bitrate, width and height properties are added to the mapping object.

    • The native Roku Video node automatically handles non-adaptive fixed-bitrate stream formats, so providing multiple MP4 sources with different bitrates/size allows the Video node to automatically switch between them depending on the streaming conditions (Roku device, network connection, screen size, etc).

  • HLS sources (per DRM system and protocol)

    • The source contains the codecs property.

    • The source contains the has_joc property set to true.

    • The source with the highest ext_x_version property value.

  • DASH sources (per DRM system and protocol)

    • The source contains the codecs property.

    • The source contains the has_joc property set to true.

Sources mapping object
                            { 
                                mp4: { 
                                  http: [<video-source>, ...], 
                                  https: [<video-source>, ...] 
                                },
                                hls: {
                                  widevine: { 
                                    http: <video-source>, 
                                    https: <video-source>
                                  },
                                  none: { 
                                    http: <video-source>, 
                                    https: <video-source>
                                  }
                                },
                                dash: {
                                  widevine: { 
                                    http: <video-source>, 
                                    https: <video-source>
                                  },
                                  playready: { 
                                    http: <video-source>, 
                                    https: <video-source>
                                  },
                                  none: { 
                                    http: <video-source>, 
                                    https: <video-source>
                                  }
                                }
                              }
                            
2

Once the sources mapping object is set, a single source is selected based on the values of the streamPreference and drmPreference bcPlayer config fields.

This process iterates through the streamPreference array and for each stream type/container the following steps are executed until one source is selected:

  1. MP4 stream preference:

    1. If the HTTPS source is available, select that one.

    2. If not, select the HTTP source.

  2. HLS and DASH stream preferences:

    1. Iterates through the drmPreference array and for each DRM system (Widevine, Playready, none):

      1. If the HTTPS source is available, select that one.

      2. If not, select the HTTP source.

3

Once a Videocloud video source has been selected, it’s then converted into the required Video ContentNode fields.

At this stage the selected source URL is also verified for any supported query parameters we might need to set, such as the Forensic Watermarking token or JWT.

bcAPI component

This component allows for independent access to Brightcove’s Playback API without having to initialize a bcPlayer component. bcAPI extends a Task node, and as such, is controlled through the controlcontrol field.

bcAPI is able to handle multiple requests at the same time (configurable through the maxRequests field) and it also provides an interface that enables any HTTP request to be triggered.

It’s up to developers to choose the best workflow for this node, but we recommend one instance to be created somewhere during the app launch process and then referenced throughout the app.

An instance of this node can be created like so:

    
        m.bcAPI = createObject("roSGNode", "bcLib:bcAPI")
    

Once an instance of the node is available, it’s possible to customize it by setting up its fields. All the fields default values are listed below.

        sub init()

            ' create a bcAPI node reference
            m.bcAPI = createObject("roSGNode", "bcLib:bcAPI")
          
            ' observe the response field to access the API responses
            m.bcAPI.observeField("ready", "onAPIready")
            
            ' configure bcAPI node fields
            m.bcAPI.setFields({
              credentials: invalid,
              
              logger: invalid, ' optional: provide a bcLib:Logger node instance
              maxRequests: 5,
              control: "run" ' initialize bcAPI task imediately
            })
            
            m.bcAPI.getVideo = {id: "<my-video-id>"}

            end sub

            sub onAPIResponse(ev)

              response = ev.getData()

            end sub
        

Config Fields

Credentials

ASSOCIATIVE ARRAY OPTIONAL

Configures Brightcove API credentials. It should contain the Account ID as well as the Policy Key or Authentication token. These are used to retrieve videos metadata from Brightcove’s Playback API.

If valid Brightcove credentials aren’t provided in this field, the bcAPI node will only be able to trigger HTTP requests through the request function.

Possible Values:

An ASSOCIATIVE ARRAY containing the following keys:

  • account_id STRING REQUIRED

    • Specifies Brightcove user account ID.

  • policy_key STRING OPTIONAL

    • Specifies the user policy key required to access the Playback API.

  • auth_token STRING OPTIONAL

    • Specifies the JSON Web Token required to:

      • Provide Playback Restriction rules (Playback Rights) through Edge Playback Authorization (EPA).
      • To specify License Keys Protection for HLSe content playback.

Code Snippet

                    m.bcAPI.credentials = {account_id: "my-account-id", policy_key: "my-policy-key"}

 ' OR
 
 m.bcAPI.setFields({
   ' ...
   credentials: {account_id: "my-account-id", policy_key: "my-policy-key"},
   ' ...
 })
                    

maxRequests

INTEGER OPTIONAL

Specifies the number of simultaneous requests that can be executed at the same time. If the number of requests surpass the value defined in maxRequests, these requests are put on hold until the ongoing requests are completed. It follows a FIFO approach.

Possible Values:

  • 5 DEFAULT

  • A positive integer value.

Code Sinippet

                m.bcAPI.maxRequests = 3

            ' OR
            
            m.bcAPI.setFields({
              ' ...
              maxRequests: 3,
              ' ...    
            })
                

logger

Specifies the Logger node reference to be used for logging purposes.

Possible Values:

  • bcLib:Logger reference.

Code Snippet

                logger = createObject("roSGNode", "bcLib:Logger")

            m.bcAPI.logger = logger
            
            ' OR
            
            m.bcAPI.setFields({
              ' ...
              logger: logger,
              ' ...    
            })
                

Action Fields

Since bcAPI is a Task node, it's not feasible to interact with it through Functions so all the actions requested to this node are initiated through its fields. Check below the list of all possible actions this node provides.


request

Allows for the execution of any HTTP request. Brightcove credentials are not required.

Request responses can be obtained through one of two ways:

  • By providing a response Node with a response AssociativeArray field, bcAPI will set the request response data into that field, which will then be available on any observing function.
  • By observing the response bcAPI output field if no response Node is provided.

This structure is exactly the same whether it’s set through the response Node or the bcAPI response field.

Possible Values:

An AssociativeArray object containing the following properties:

  • data ASSOCIATIVE ARRAY REQUIRED

    Contains the request data. The following properties are possible:

    • id STRING OPTIONAL

      A custom request ID so it can then be identified when processing the response data. Specially useful when parsing responses from the response field instead of a response Node. If not provided, defaults to “request“.

      • request DEFAULT

    • url STRING REQUIRED

      The request URL.

    • headers ASSOCIATIVE ARRAY OPTIONAL

      Request headers in a key-value Associative Array object. Roku’s x-roku-reserved-dev-id header is automatically set.

    • method STRING OPTIONAL

      Request method. The possible values are:

      • get DEFAULT

      • post

      • delete

      • put

      • patch

    • body STRING / ASSOCIATIVE ARRAY OPTIONAL

      Request body. If an Associative Array object is provided, it’s automatically parsed into a string before sending the request.

    • gzip BOOLEAN OPTIONAL

      Enables the GZIP encoding through EnableEncodings. Disabled by default.

    • cookies BOOLEAN OPTIONAL

      Enables cookies through EnableCookies. Disabled by default.

    • http2 BOOLEAN OPTIONAL

      Enables HTTP/2 support through SetHttpVersion. Disabled by default.

    • forceFormat STRING OPTIONAL

      Specifies how the response body should be formatted. The possible values are:

      • auto DEFAULT

        Checks for the content-type response header and if it’s set to application/json the response body is parsed into an Associative Array object. If not, the response body is set as a string.

      • json

        Forces the parsing of the response body into an Associative Array object. This may result in unwanted results if the response content is not a valid JSON string.

      • string

        The request response body is set as a string.

    • options Associative Array OPTIONAL

      Custom parameters that will be passed along to the response object as is.

  • node NODE OPTIONAL

    Response Node with a response field where the request response will be set into. If not provided (default), the response data can be accessed through bcAPI response output field.

Code Snippet

                    sub init()

 ' initialize bcAPI node reference
 m.bcAPI = createObject("roSGNode", "bcLib:bcAPI")

 ' setup bcAPI config fields and initiate the bcAPI Task
 m.bcAPI.setFields({
   ' ...
   control: "run"
 })

 ' observe bcAPI "response" field to retrieve the response data
 ' keep in mind that if a response Node isn't provided, all request responses 
 ' are set into the bcAPI response field
 m.bcAPI.observeField("response", "onResponse")

 ' setup the request configuration and initiate it
 m.bcAPI.request = {
   data: {
     ' it's important that a custom ID is set here so that this request response 
     ' can be easily identified in the response observing function
     id: "myCustomRequest"
     url: "https://my.request.url"
     method: "post",
     body: {some: "body-content"}
     options: {extradata: "some data I may need in the response"}
   }
 }

 ' OR

 ' create a response Node that will be used to "catch" the request response data
 responseNode = createObject("roSGNode", "Node")

 ' create an Associative Array "response" field in this Node
 responseNode.addFields({ response: {} })

 ' observe the just added "response" field to capture the response data
 responseNode.observeField("response", "onResponse")

 ' setup the request configuration, provide the response Node and initiate the request
 m.bcAPI.request = {
   node: responseNode,
   data: {
     ' the id could be omitted when parsing the response in a specific function
     id: "myOtherCustomRequest" 
     url: "https://my.other.request.url"
     method: "post",
     body: {someOther: "body-content"}
     options: {extradata: "some other data I may need in the response"}
   }
 }

 end sub

 sub onResponse(ev)

   response = ev.getData()

   ' the data provided in the "options" property is available in the response object as is
   options = response.options
   ? options.extradata

   if response.id = "myCustomRequest" then

     ' handle "myCustomRequest" response here

   else if response.id = "myOtherCustomRequest" then

     ' handle "myOtherCustomRequest" response here    
   end if

 end sub
                    

getVideo

ASSOCIATIVE ARRAY

Retrieves a specific Brightcove video metadata through the Playback API. The response object is handled as described in the request field.

In this case, the response id property is always “getVideo“.

Playback API reference.

Possible Values:

An AssociativeArray object containing the following properties:

  • id STRING REQUIRED

    Brightcove video ID or video reference ID to be retrieved. To get a video using a video reference ID, id must be formatted like so: ref:<reference_id>.

  • params ASSOCIATIVE ARRAY OPTIONAL

    Playback API request parameters as specified in the Playback API Reference. The following properties are supported:

    • ad_config_id STRING OPTIONAL

      Include server-side ad insertion.

    • config_id STRING OPTIONAL

      Include and set equal to the delivery rules id in order to have the delivery rules applied.

  • node NODE OPTIONAL

    Response Node with a response field where the request response will be set into. If not provided (default), the response data can be accessed through bcAPI response output field.

Code Snippet

                sub init()

 ' initialize bcAPI node reference
 m.bcAPI = createObject("roSGNode", "bcLib:bcAPI")

 ' setup bcAPI config fields and initiate the bcAPI Task
 m.bcAPI.setFields({
   ' ...
   control: "run"
 })

 ' observe bcAPI "response" field to retrieve the response data
 ' keep in mind that if a response Node isn't provided, all request responses are 
 ' set into the bcAPI response field
 m.bcAPI.observeField("response", "onResponse")
 
 ' setup the getVideo configuration and initiate it
 m.bcAPI.getVideo = {
   id: "<brightcove-video-id>",
   params: {
     ad_config_id: "my-ad-config-id"
   }
 }
   
   ' OR
   
   ' create a response Node that will be used to "catch" the getVideo response data
   responseNode = createObject("roSGNode", "Node")
   
   ' create an Associative Array "response" field in this Node
   responseNode.addFields({ response: {} })
   
   ' observe the just added "response" field to capture the response data
   responseNode.observeField("response", "onResponse")
   
   ' setup the getVideo configuration, provide the response Node and initiate the API request
   m.bcAPI.getVideo = {
     node: responseNode,
     id: "<brightcove-video-id>",
     params: {
       ad_config_id: "my-ad-config-id"
     }
   }
   
 end sub
 
 sub onResponse(ev)
   
   response = ev.getData()
   
   ' handle the "getVideo" request response here
   ' response.id is "getVideo"
   
 end sub
                

getVideos

ASSOCIATIVE ARRAY

Retrieves a set of Brightcove videos metadata through the Playback API. This option is commonly used to programmatically search for Brightcove videos.

The response object is handled as described in the request field. In this case, the response id property is always “getVideos“.

Playback API reference.

Possible Values:

An Associative Array object containing the following properties:

  • query STRING REQUIRED

    Search query used to retrieved a set of Brightcove videos. More details see CMS/Playback API

  • params ASSOCIATIVE ARRAY OPTIONAL

    Playback API request parameters as specified in the Playback API Reference. The following properties are supported:

    • limit INTEGER OPTIONAL

      The number of videos to return.

    • offset INTEGER OPTIONAL

      The number of videos to skip - used to page multiple sets of videos.

    • sort STRING OPTIONAL

      Field to sort results by. Check the Playback API Reference for all the possible values.

    • ad_config_id STRING OPTIONAL

      Include server-side ad insertion.

    • config_id STRING OPTIONAL

      Include and set equal to the delivery rules id in order to have the delivery rules applied.

  • node NODE OPTIONAL

    Response Node with a response field where the request response will be set into. If not provided (default), the response data can be accessed through bcAPI response output field.

Code Snippet

                sub init()

 ' initialize bcAPI node reference
 m.bcAPI = createObject("roSGNode", "bcLib:bcAPI")

 ' setup bcAPI config fields and initiate the bcAPI Task
 m.bcAPI.setFields({
   ' ...
   control: "run"
 })

 ' observe bcAPI "response" field to retrieve the response data
 ' keep in mind that if a response Node isn't provided, all request responses are 
 ' set into the bcAPI response field
 m.bcAPI.observeField("response", "onResponse")

 ' setup the getVideos configuration and initiate it
 m.bcAPI.getVideos = {
   query: "",
   params: {
     limit: 10,
     offset: 20,
     ad_config_id: "my-ad-config-id"
   }
 }
   
   ' OR
   
   ' create a response Node that will be used to "catch" the getVideos response data
   responseNode = createObject("roSGNode", "Node")
   
   ' create an Associative Array "response" field in this Node
   responseNode.addFields({ response: {} })
   
   ' observe the just added "response" field to capture the response data
   responseNode.observeField("response", "onResponse")
   
   ' setup the getVideos configuration, provide the response Node and initiate the API request
   m.bcAPI.getVideos = {
     node: responseNode,
     query: "<videos-search-query>",
     params: {
       limit: 10,
       offset: 20,
       ad_config_id: "my-ad-config-id"
     }
   }
   
 end sub
 
 sub onResponse(ev)
   
   response = ev.getData()
   
   ' handle the "getVideos" request response here
   ' response.id is "getVideos"
   
 end sub
                

getRelated

ASSOCIATIVE ARRAY

Retrieves a set of Brightcove videos that are related to the specified video id through Playback API.

Using the name and short description of the specified video id, the Playback API searches for videos with any partial matches in the following fields: name, short_description , long_description, tags.

The response object is handled as described in the request field. In this case, the response id property is always “getRelated“.

Playback API reference

Possible Values:

An AssociativeArray object containing the following properties:

  • id STRING REQUIRED

    Brightcove video ID or reference ID to retrieve the related videos from. To get the related videos of a video using the video reference ID, id must be formatted like so: ref:<reference_id>.

  • params ASSOCIATIVE ARRAY OPTIONAL

    Playback API request parameters as specified in the Playback API Reference. The following properties are supported:

    • limit INTEGER OPTIONAL

      The number of videos to return.

    • offset INTEGER OPTIONAL

      The number of videos to skip - used to page multiple sets of videos.

    • ad_config_id STRING OPTIONAL

      Include server-side ad insertion.

    • config_id STRING OPTIONAL

      Include and set equal to the delivery rules id in order to have the delivery rules applied.

  • node NODE OPTIONAL

    Response Node with a response field where the request response will be set into. If not provided (default), the response data can be accessed through bcAPI response output field.

Code Snippet

                sub init()

 ' initialize bcAPI node reference
 m.bcAPI = createObject("roSGNode", "bcLib:bcAPI")

 ' setup bcAPI config fields and initiate the bcAPI Task
 m.bcAPI.setFields({
   ' ...
   control: "run"
 })

 ' observe bcAPI "response" field to retrieve the response data
 ' keep in mind that if a response Node isn't provided, all request responses are 
 ' set into the bcAPI response field
 m.bcAPI.observeField("response", "onResponse")

 ' setup the getVideos configuration and initiate it
 m.bcAPI.getRelated = {
   id: "<video-id>",
   params: {
     limit: 10,
     offset: 20,
     ad_config_id: "my-ad-config-id"
   }
 }
   
   ' OR
   
   ' create a response Node that will be used to "catch" the getRelated response data
   responseNode = createObject("roSGNode", "Node")
   
   ' create an Associative Array "response" field in this Node
   responseNode.addFields({ response: {} })
   
   ' observe the just added "response" field to capture the response data
   responseNode.observeField("response", "onResponse")
   
   ' setup the getRelated configuration, provide the response Node and initiate the API request
   m.bcAPI.getRelated = {
     node: responseNode,
     id: "<video-id>",
     params: {
       limit: 10,
       offset: 20,
       ad_config_id: "my-ad-config-id"
     }
   }
   
 end sub
 
 sub onResponse(ev)
   
   response = ev.getData()
   
   ' handle the "getRelated" request response here
   ' response.id is "getRelated"
   
 end sub
                

getPlaylist

ASSOCIATIVE ARRAY

Retrieves a Brightcove playlist metadata through Playback API.

The response object is handled as described in the request field. In this case, the response id property is always “getPlaylist“.

Playback API reference

Possible Values:

An AssociativeArray object containing the following properties:

  • id STRING REQUIRED

    Brightcove playlist ID or reference ID to be retrieved. To get a playlist using a playlist reference ID, id must be formatted like so: ref:<reference_id>.

  • params ASSOCIATIVE ARRAY OPTIONAL

    Playback API request parameters as specified in the Playback API Reference. The following properties are supported:

    • limit INTEGER OPTIONAL

      The number of videos to return.

    • offset INTEGER OPTIONAL

      The number of videos to skip - used to page multiple sets of videos.

    • ad_config_id STRING OPTIONAL

      Include server-side ad insertion.

    • config_id STRING OPTIONAL

      Include and set equal to the delivery rules id in order to have the delivery rules applied.

Code Snippet

                sub init()

 ' initialize bcAPI node reference
 m.bcAPI = createObject("roSGNode", "bcLib:bcAPI")

 ' setup bcAPI config fields and initiate the bcAPI Task
 m.bcAPI.setFields({
   ' ...
   control: "run"
 })

 ' observe bcAPI "response" field to retrieve the response data
 ' keep in mind that if a response Node isn't provided, all request responses are 
 ' set into the bcAPI response field
 m.bcAPI.observeField("response", "onResponse")

 ' setup the getPlaylist configuration and initiate it
 m.bcAPI.getPlaylist = {
   id: "<playlist-id>",
   params: {
     limit: 10,
     offset: 20,
     ad_config_id: "my-ad-config-id"
   }
 }
   
   ' OR
   
   ' create a response Node that will be used to "catch" the getPlaylist response data
   responseNode = createObject("roSGNode", "Node")
   
   ' create an Associative Array "response" field in this Node
   responseNode.addFields({ response: {} })
   
   ' observe the just added "response" field to capture the response data
   responseNode.observeField("response", "onResponse")
   
   ' setup the getPlaylist configuration, provide the response Node and initiate the API request
   m.bcAPI.getPlaylist = {
     node: responseNode,
     id: "<playlist-id>",
     params: {
       limit: 10,
       offset: 20,
       ad_config_id: "my-ad-config-id"
     }
   }
   
 end sub
 
 sub onResponse(ev)
   
   response = ev.getData()
   
   ' handle the "getPlaylist" request response here
   ' response.id is "getPlaylist"
   
 end sub
                

abort

BOOLEAN

Aborts currently ongoing requests.

If a response Node was provided in the request configuration, its response field is set to the following value: {aborted: true}. This allows the response handler to be notified that the request was aborted.

Possible Values:

  • false no action.

  • true aborts currently ongoing requests.

Code Snippet

                ' ...
                    
 ' all requests that had a response Node provided will get notified once the request is aborted
 m.bcAPI.abort = true

 ' ...
                

kill

BOOLEAN

Aborts all ongoing requests and completely terminates the bcAPI Task. Once kill is requested there is no way to bring bcAPI functionality back on, so a new bcAPI node instance would need to be created.

Since this process is asynchronous, once the bcAPI is completely terminated the ready field is set back to false to notify eventual observing functions about the Task termination.

Possible Values:

  • false no action.

  • true aborts ongoing requests and terminates the bcAPI Task.

Code Snippet

                ' ...

                    ' just like the "bcAPI.abort", all requests that had a response Node provided will 
                    ' get notified once the request is aborted prior to the Task termination
                    m.bcAPI.kill = true 
                    
                ' ...
                

Output Fields

response

ASSOCIATIVE ARRAY

Requests responses can be accessed through the response field unless a response Node was provided in the request options to capture the response metadata.

Possible Values:

The response is an Associative Array object whose properties can vary depending on the type of response it refers to:

  • HTTP request response

    • id STRING

      The request ID. If not provided in a request, contains the timestamp the request was initiated at. In a Brightcove Playback API it’s set to the specific request name.

    • code INTEGER

      The response HTTP status code.

    • headers ASSOCIATIVE ARRAY

      The response HTTP headers.

    • failure STRING

      An error message is applicable, OK in a successful request. failure contains the GetFailureReason function.

    • duration FLOAT

      Request duration since its initialization until a response is received.

    • body ASSOCIATIVE ARRAY STRING

      The response body.

      In a request the body format may depend on the forceFormat option.

      In a Brightcove Playback API request the response metadata is provided in an Associative Array object.

    • request ASSOCIATIVE ARRAY

      Some data from the original request, includes the following properties:

      • url STRING

        The request URL

      • method STRING

        The request method (get, post, etc)

  • Internal error (configuration issues)

    • id STRING

      ID of the request that originated the error (request, getVideo, getVideos, getRelated, getPlaylist or the custom request ID).

    • code INTEGER

      1, 2 or 3. The higher the number the deeper the origin of the error is.

    • duration FLOAT

      Hardcoded to -1 as it’s not relevant in this case.

    • failure STRING

      The error message.

  • Aborted request (in a response Node only)

    • aborted BOOLEAN

      Hardcoded to true.

Code Snippet

                    sub init()

   ' initialize bcAPI node reference
   m.bcAPI = createObject("roSGNode", "bcLib:bcAPI")

   ' setup bcAPI config fields and initiate the bcAPI Task
   m.bcAPI.setFields({
     ' ...
     control: "run"
   })

   ' observe bcAPI "response" field to retrieve the response data
   ' keep in mind that if a response Node isn't provided, all request responses are 
   ' set into the bcAPI response field
   m.bcAPI.observeField("response", "onResponse")

   ' setup the request configuration and initiate it
   m.bcAPI.request = {
     data: {...}
   }

   ' OR

   ' create a response Node that will be used to "catch" the request response data
   responseNode = createObject("roSGNode", "Node")

   ' create an Associative Array "response" field in this Node
   responseNode.addFields({ response: {} })

   ' observe the just added "response" field to capture the response data
   responseNode.observeField("response", "onResponse")

   ' setup the request configuration, provide the response Node and initiate the request
   ' bcAPI.response will not get this request response
   m.bcAPI.request = {
     node: responseNode,
     data: {...}
   }

 end sub

 sub onResponse(ev)

   response = ev.getData()

   ' handle request response

 end sub

ready

BOOLEAN

Read-only field that indicates if the bcAPI Task is ready to process request commands or has been terminated.

A bcAPI node instance can be terminated through the following actions:

  • setting its control field to stop

  • setting its kill field is set to true

Possible Values:

  • false bcAPI has not been complete initiated or has been completely terminated. No requests can be executed in this state.

  • true bcAPI Task is ready to trigger requests

Code Snippet

                sub init()

   ' initialize bcAPI node reference
   m.bcAPI = createObject("roSGNode", "bcLib:bcAPI")

   ' observe the "ready" field
   m.bcAPI.observeField("ready", "onReady")

   ' setup bcAPI config fields and initiate the bcAPI Task
   m.bcAPI.setFields({
     ' ...
     control: "run"
   })

   ' Trigger bcAPI requests here
   ' The bcAPI node is able to process request commands at this point, right after its initialization.
   ' There's no need to wait for it to be ready as it can detect that a new request command was initiated

   ' ...

   ' terminate the bcAPI node instance.
   ' This will abort all ongoing requests and terminate the task, after which the ready field is set to false
   m.bcAPI.kill = true

 end sub

 sub onReady(ev)

   isReady = ev.getData()
   if NOT isReady then

     ' the bcAPI task been terminated and cannot be used anymore

   end if

 end sub

Utils

The Utils node provides a set of Brightscript helping utilities that may be useful for validations or common operations.

An instance of this node can be created like so:

                    
                        m.bcUtils = createObject("roSGNode", "bcLib:Utils")
                    

Once a Utils instance is available, its functions can be accessed as follows:

                    
                        ' checks if the passed data is an Associative Array, in this case isAA is true
                        isAA = m.bcUtils.callFunc("isAA", {b: "c"})
                    

Functions

validate

Validates passed values according to the rules provided.

Parameters:

  • value DYNAMIC REQUIRED

    The value meant to be validated.

  • map ASSOCIATIVE ARRAY REQUIRED

    A map of rules used to validate the provided value against. This Associative Array object contains the following properties:

    • type STRING REQUIRED

      Specifies the expected value type. The following types are supported:

      • string Value must be a String.

      • number Value must be a number (Integer, Float, Double or LongInteger).

      • boolean Value must be a Boolean.

      • array Value must be an Array.

      • node Value must be a roSGNode.

      • aa Value must be an Associative Array.

      • <type> If none of the previous values is recognized, it uses <type> to support other Roku types. Please be aware that type() can return different values for the “same” type, ie: “String” vs “roString”.

    • required BOOLEAN OPTIONAL

      Specifies that the value cannot be invalid if true. Default to true if not provided. Applicable to all types.

    • empty BOOLEAN OPTIONAL

      Specifies that the value can be an empty String (““), Associative Array ({}) or Array ([]) if true.

      Defaults to true if not provided. Only applicable to string, aa and array types.

    • minLength INTEGER OPTIONAL

      Specifies the minimum length of a String (number of chars), Associative Array (number of keys) or Array (number of entries). Only applicable to string, aa and array types.

    • maxLength INTEGER OPTIONAL

      Specifies the maximum length of a String (number of chars), Associative Array (number of keys) or Array (number of entries). Only applicable to string, aa and array types.

    • enum STRING ARRAY OPTIONAL

      Specifies a list of possible values value can take. The contains function is used to verify if the value is present in enum. Only applicable to string and number types.

    • min INTEGER OPTIONAL

      Specifies the minimum value of value. Only applicable to the number type.

    • max INTEGER OPTIONAL

      Specifies the maximum value of value. Only applicable to the number type.

    • null BOOLEAN OPTIONAL

      Specifies if value can be 0. Only applicable to the number type.

    • properties ASSOCIATIVE ARRAY OPTIONAL

      Specifies a map of rules to be applied to a specific Associative Array property. This allows for a recursion execution of validate. All the properties listed in the map section are supported. Only applicable to the aa type.

    • subtype STRING OPTIONAL

      Specifies the subtype (as indicated by value.subtype()) that value should reflect. Only applicable to the node type.

    • fields ARRAY OPTIONAL

      Specifies a list of fields that the value node must have (as indicated by value.hasField("field")). An Array of Strings must be provided where each entry represents the name of a field. Only applicable to the node type.

    • interface STRING OPTIONAL

      Specifies the interface (as indicated by getInterface()) that value should reflect. Only applicable to the node type.

Return Value

BOOLEAN

Returns a Boolean value that indicates if value respects all the rules provided in the map parameter. A failed validation of a single rule will invalidate the whole validation and return false.

Code Snippet

                        m.bcUtils = createObject("roSGNode", "bcLib:Utils")
                            test1 = "A random string"
                            validTest1 = m.bcUtils.callFunc("validate", test1, {type: "string", maxLength: 4})
                            ? validTest1 ' false because test1 fails the maxLength validation rule
                    
                            test2 = "hello-world"
                            ' keep in mind that when specifying "enum" as a string, the inStr() function
                            ' is used to search for the value
                            validTest2 = m.bcUtils.callFunc("validate", test2, {
                              type: "string",
                              enum: "hello-world/hello-planet/hello-pluto"
                            })
                            ' OR
                            validTest2 = m.bcUtils.callFunc("validate", test2, {
                              type: "string",
                              enum: ["hello-world","hello-planet","hello-pluto"]
                            })
                            ? validTest2 ' true because "hello-world" is a string and
                            ' it's specified in the enum validation rule
                    
                            test4 = invalid
                            validTest3 = m.bcUtils.callFunc("validate", test3, {type: "string", empty: false})
                            ? validTest3 ' false because, by default, the "required" validation rule is true
                    
                            test4 = createObject("roSGNode", "Node")
                            test4.addFields({hello: "world"})
                            validTest4 = m.bcUtils.callFunc("validate", test4, {
                                type: "node",
                                interface: "ifSGNodeChildren",
                                subtype: "Node",
                                fields: ["hello"]
                            })
                            ? validTest4 ' true because all validation rules are valid
                    
                            test5 = {hello: {world: []}}
                            validTest5 = m.bcUtils.callFunc("validate", test5, {
                                type: "aa",
                                properties: {
                                    hello: {
                                        type: "aa",
                                        properties: {
                                            world: {
                                                type: "array",
                                                empty: false
                                            }
                                        }
                                    }
                                }
                            })
                            ? validTest5 ' false because, as specified by the validation rules,
                            ' "test5.hello.world" cannot be an empty array
                    
                            test6 = [1, 2, 4, 8, "testing"]
                            validTest6 = m.bcUtils.callFunc("validate", test6, {type: "array", maxLength: 5})
                            ? validTest6 ' true because test6 respects the array and maxLength validation rule
                        

contains

Allows to search for a needle in a haystack. Internally the indexOf function is used to run the search.

Parameters:

  • haystack STRING ARRAY REQUIRED

    A String or Array where to search for the needle. Have in mind the following details:

    • If haystack is a string, the needle should also be a string.

    • If haystack is an array:

      • If needle is a string, it'll be lower-cased before the search process. Haystack string items are also lower-cased for a proper comparison with needle.

      • If needle is not a string, the comparison is made with needle = haystack[i]..

  • needle STRING NUMBER REQUIRED

    The value to find in the haystack. When comparing strings, both needle and haystack are lower-cased.

Return Value

BOOLEAN

Returns true if needle is found in haystack or false otherwise.

Code Snippet

                        m.bcUtils = createObject("roSGNode", "bcLib:Utils")
                            test = m.bcUtils.callFunc("contains", "This is A tEst string", "a test")
                            ' test = true
                    
                            test = m.bcUtils.callFunc("contains", [2, "a", 5], "5")
                            ' test = false
                        

indexOf

Just like contains, searches for a needle in a haystack, but returns the index of the needle in the haystack if found instead.

Parameters:

  • haystack STRING ARRAY REQUIRED

    A String or Array where to search for the needle. Have in mind the following details:

    • If haystack is a string, the needle should also be a string.

    • If haystack is an array:

      • If needle is a string, it'll be lower-cased before the search process. Haystack string items are also lower-cased for a proper comparison with needle.

      • If needle is not a string, the comparison is made with needle = haystack[i]..

  • needle STRING NUMBER REQUIRED

    The value to find in the haystack. When comparing strings, both needle and haystack are lower-cased.

Return Value

INTEGER

  • -1 if needle isn't found.

  • Index of needle in haystack. Either the haystack array index where needle was found or the inStr() result if needle and haystack are strings.

Code Snippet

                    m.bcUtils = createObject("roSGNode", "bcLib:Utils")
 test = m.bcUtils.callFunc("indexOf", "This is A tEst string", "a test")
 ' test = 8
 
 test = m.bcUtils.callFunc("indexOf", [2, "a", 5], "5")
 ' test = -1
                    

isBool

Checks if value is a Boolean.

  • value DYNAMIC REQUIRED

Return Value

BOOLEAN

  • true if value is Boolean, false otherwise.

Code Snippet

                    m.bcUtils = createObject("roSGNode", "bcLib:Utils")
 test = m.bcUtils.callFunc("isBool", "Def not a boolean")
 ' test = false
                    

isFunction

Checks if value is a Function.

Parameters

  • value DYNAMIC REQUIRED

Return Value

BOOLEAN

  • true if value is Function, false otherwise.

Code Snippet

                    m.bcUtils = createObject("roSGNode", "bcLib:Utils")
                sub myTestFnc()
                  ? "hello world"
                end sub
                
                test = m.bcUtils.callFunc("isFunction", myTestFnc)
                ' test = true
                    

isAA

Checks if value is an Associative Array object.

Parameters:

  • value DYNAMIC REQUIRED

Return Value

BOOLEAN

  • true if value is an Associative Array object, false otherwise.

Code Snippet

                    m.bcUtils = createObject("roSGNode", "bcLib:Utils")
 test = m.bcUtils.callFunc("isAA", {})
 ' test = true
                    

isArray

Checks if value is an Array object.

Parameters:

  • value DYNAMIC REQUIRED

Return Value

BOOLEAN

  • true if value is an Array object, false otherwise.

Code Snippet

                    m.bcUtils = createObject("roSGNode", "bcLib:Utils")
 test = m.bcUtils.callFunc("isArray", ["this", "is", "an", "array"])
 ' test = true
                    

isInt

Checks if value is an Integer number.

Parameters:

  • value DYNAMIC REQUIRED

Return Value

BOOLEAN

  • true if value is an Integer number, false otherwise.

Code Snippet

                    m.bcUtils = createObject("roSGNode", "bcLib:Utils")
 test = m.bcUtils.callFunc("isInt", "123")
 ' test = false
                    

isFloat

Checks if value is an Float number.

Parameters:

  • value DYNAMIC REQUIRED

Return Value

BOOLEAN

  • true if value is an Float number, false otherwise.

Code Snippet

                    m.bcUtils = createObject("roSGNode", "bcLib:Utils")
 test = m.bcUtils.callFunc("isFloat", 1.23)
 ' test = true
                    

isNumber

Checks if value is an Integer, Float, Double or LongInteger number.

Parameters:

  • value DYNAMIC REQUIRED

Return Value

BOOLEAN

  • true if value is an Integer, Float, Double or LongInteger number, false otherwise.

Code Snippet

                    m.bcUtils = createObject("roSGNode", "bcLib:Utils")
 test = m.bcUtils.callFunc("isNumber", 323)
 ' test = true
                    

isString

Checks if value is a String.

Parameters:

  • value DYNAMIC REQUIRED

Return Value

BOOLEAN

  • true if value is a String, false otherwise.

Code Snippet

                    m.bcUtils = createObject("roSGNode", "bcLib:Utils")
 test = m.bcUtils.callFunc("isString", "323")
 ' test = true
                    

charAt

Get the character positioned at a specific index of a string.

Parameters:

  • string STRING REQUIRED

    The string to get the character from.

  • index INTEGER REQUIRED

    The index of the character.

Return Value

STRING

  • The character at the position specified by index.

Code Snippet

                    m.bcUtils = createObject("roSGNode", "bcLib:Utils")
 test = m.bcUtils.callFunc("charAt", "My String", 3)
 ' test = "S"
                    

toString

Converts any type to a string.

Parameters:

  • value DYNAMIC REQUIRED

    The value to be converted into a string.

  • maxDepth INDEX OPTIONAL

    Specifies the max depth of a roSGNode, Array or Associative Array that should be converted to string. If not specified, the default value is 3. The minimum maxDepth value is 1. Keep in mind that increasing the maxDepth will exponentially increase the performance hit as well.

Return Value

STRING

Returns a string representation of value. The supported types include:

  • <uninitialized>

    Returns “UNINITIALIZED“.

  • invalid

    Returns “INVALID“.

  • string

    Returns value.

  • integer

    Returns the number string representation.

  • float

    Returns the number string representation.

  • double

    Returns the number string representation.

  • roSGNode

    Converts the Node fields to an AssociativeArray object, converts it to string and returns it in the following format: “<Component: NodeType {NodeFields}>". If maxDepth has been reached, the following format is returned: “<Component: NodeType>".

  • Array

    Converts the Array to a string by converting each individual Array entry to a String in a recursive execution of this function. If maxDepth is reached, the following format is returned: “[ArrayLength]".

  • List

    Just like Array, converts the List to a string by converting each individual List entry to a String in a recursive execution of this function. If maxDepth is reached, the following format is returned: “[ListLength]".

  • Associative Array

    Converts the Associative Array to a string by converting each individual key value to a String in a recursive execution of this function. If maxDepth is reached, the following format is returned: “{[ListOfKeys]}".

  • Boolean

    Returns the Boolean string representation.

  • roDateTime

    Returns the DateTime ISO string.

  • Any other “ro<node-name>“ nodes

    Returns the following format: “<Component: NodeType>".

  • Any other value not mention will return an empty String.

Code Snippet

                    m.bcUtils = createObject("roSGNode", "bcLib:Utils")
 test = m.bcUtils.callFunc("toString", 567)
 ' test = "567"
 
 test2 = { one: { two: { three: { four: { five: "Hello World" } } } } }
 test2 = m.bcUtils.callFunc("toString", test2, 2)
 ' test2 = "{\"one\":{\"two\":{[\"three\"]}}}"
                    

toDouble

Converts a string to double.

Parameters:

  • value STRING REQUIRED

    The string value to be converted into a Double value.

Return Value

DOUBLE

Returns the converted value as a Double number.

Code Snippet

                    m.bcUtils = createObject("roSGNode", "bcLib:Utils")
                ? m.bcUtils.callFunc("toDouble", "3244.34343")        ' => 3244.34343#
                ? m.bcUtils.callFunc("toDouble", "not a number")      ' => 0#
                ? m.bcUtils.callFunc("toDouble", "dfdfd.435454")      ' => 0.435454#
                ? m.bcUtils.callFunc("toDouble", "0.45454454")        ' => 0.45454454#
                ? m.bcUtils.callFunc("toDouble", "-34343.45454454")   ' => -34343.45454454#
                    

setAddFields

Adds or updates a set of properties in the specified Node. It essentially goes through the list of properties provided in the fields parameter and:

  • If the field does not exist in the Node provided: adds the new field with the value provided.

  • If the field already exists in the Node provided: updates its value with the value provided.

The change and focusedChild properties are removed from the fields object, if present, before applying the fields to the Node.

Parameters:

  • node NODE REQUIRED

    The Node reference which will get its fields updated

  • fields ASSOCIATIVE ARRAY REQUIRED

    A set of key-value pairs representing the field names and the respective values to be added / updated in the Node provided.

Return Value

VOID

Code Snippet

                        m.bcUtils = createObject("roSGNode", "bcLib:Utils")
 testNode = createObject("roSGNode", "ContentNode")
 testNode.id = "hello world"
 
 m.bcUtils.callFunc("setAddFields", {
   id: "hello planet",
   customField: "my custom field"
 })
 
 ? "testNode id: " testNode.id ' => "hello planet"
 ? "testNode customField: " testNode.customField ' => "my custom field"
                        

addURLParams

Adds the provided key-value pairs as query parameters into the URL provided.

Be aware that this function does not verify if query parameters already exist, it simply appends all the properties in the params parameter to the url value.

Parameters:

  • url STRING REQUIRED

    The URL where query parameter will be added.

  • params ASSOCIATIVE ARRAY REQUIRED

    A key-value object specifying the query parameter names and values to be added into url.

Return Value

STRING

Returns url with the added query parameters. If, for any reason, no query parameters were added, url is returned as is.

Code Snippet

                    m.bcUtils = createObject("roSGNode", "bcLib:Utils")
 url = "http://my.fancy.url"
 url = m.bcUtils.callFunc("addURLParams", url, {hello: "world"})
 ? url ' => "http://my.fancy.url?hello=world"
 
 ' running the function again with the same parameters will result in duplicated query parameters
 url = m.bcUtils.callFunc("addURLParams", url, {hello: "world"})
 ? url ' => "http://my.fancy.url?hello=world&hello=world"
                    

match

Search for matching substrings in a String through a regex pattern. If the matching pattern contains N parenthetical substrings, the relevant substrings are returned as an array of length N+1, where array[0] is again the entire match and each additional entry in the array is the match for the corresponding parenthetical expression.

Uses Roku’s roRegex component internally.

Parameters:

  • string STRING REQUIRED

    The string to be searched for matching substrings.

  • pattern STRING REQUIRED

    The regex pattern.

  • flag STRING OPTIONAL

    Specifies the behavior flags. Empty string if not provided. Any combination of the following flags is supported:

    • i Case insensitive match.

    • m Multiline mode. The start of line ^ and end of line $ constructs match immediately following or before any newline in the subject string as well as the very start and end of the string. Normally, just the start and end of the string would match.

    • s Sets dot-all mode that includes newline in the .* regular expression. This modifier is equivalent to Perl's /s modifier.

    • x Sets extended mode that ignores whitespace characters except when escaped or inside a character class. Characters between an unescaped # outside a character a character class and the next newline character, inclusive, are also ignored. This modifier is equivalent to Perl's /x modifier.

Return Value

ARRAY

Returns an Array of matched substrings from string. If no match was made, an empty array is returned. If a match was made, the entire match is returned in array[0]. If there are no parenthetical substrings this is the only entry in the array.

Code Snippet

                    m.bcUtils = createObject("roSGNode", "bcLib:Utils")
 test = m.bcUtils.callFunc("match", "abcd", "(a|(z))(bc)", "i")
 ' test = ["abc", "a", "", "bc"]
                    

replace

Replaces all occurrences of a matching pattern in string with replacement String and returns the result. The replacement may contain numbered back-references to parenthetical substrings.

Keep in mind that the replace function does not use any behavior flags.

Uses Roku’s roRegex component internally.

Parameters:

  • string STRING REQUIRED

    The string where occurrences of a matching pattern will be replaced by replacement.

  • pattern STRING REQUIRED

    The regex pattern.

  • replacement STRING REQUIRED

    The string to be used to replace matches in the provided string.

Return Value

STRING

A string with the result of the replace operation.

Code Snippet

                    m.bcUtils = createObject("roSGNode", "bcLib:Utils")
 test = m.bcUtils.callFunc("replace", "Abracadabra", "a", "x")
 ' test = "Abrxcxdxbrx"
                    

truncate

Allows to truncate a string by the specific number of chars and set a custom truncate char.

Parameters:

  • string STRING REQUIRED

    The string to check.

  • length INTEGER REQUIRED

    The end characters to check.

  • chars STRING DEFAULT

    Chars that will be added in the truncate position of the string. Defaults to ... if not provided.

Return Value

STRING

Returns the truncated string.

Code Snippet

                    m.bcUtils = createObject("roSGNode", "bcLib:Utils")
 test = m.bcUtils.callFunc("truncate", "My String", 3)
 ' test = "My ..."
 
 test2 = m.bcUtils.callFunc("truncate", "My String", 2, "-")
 ' test2 = "My-"
 
 test3 = m.bcUtils.callFunc("truncate", "My String", 2, "")
 ' test3 = "My"
                    

toMD5

Generates the hash of a string using MD5 algorithm.

Parameters:

  • string STRING REQUIRED

    The string to generate the MD5 hash from.

Return Value

STRING

Returns the string MD5 hash.

Code Snippet

                    m.bcUtils = createObject("roSGNode", "bcLib:Utils")
                        test = m.bcUtils.callFunc("toMD5", "My String")
                        ' test = "4545102cc40ea0a85124cf4b31574661"
                    

toSHA1

Generates the hash of a string using SHA1 algorithm.

Parameters:

  • string STRING REQUIRED

    The string to generate the SHA1 hash from.

Return Value

STRING

Returns the string SHA1 hash.

Code Snippet

                    m.bcUtils = createObject("roSGNode", "bcLib:Utils")
                        test = m.bcUtils.callFunc("toSHA1", "My String")
                        ' test = "c9dacbd8a688c5b310890310e14272ac11be5744"
                    

toSHA256

Generates the hash of a string using SHA256 algorithm.

Parameters:

  • string STRING REQUIRED

    The string to generate the SHA256 hash from.

Return Value

STRING

Returns the string SHA256 hash.

Code Snippet

                    m.bcUtils = createObject("roSGNode", "bcLib:Utils")
                        test = m.bcUtils.callFunc("toSHA256", "My String")
                        ' test = "3f9a07d83c604dba400d13df4d34566b78338804f0b3181d4e02089fe4daa7b0"
                    

toSHA512

Generates the hash of a string using SHA512 algorithm.

Parameters:

  • string STRING REQUIRED

    The string to generate the SHA512 hash from.

Return Value

STRING

Returns the string SHA512 hash.

Code Snippet

                    m.bcUtils = createObject("roSGNode", "bcLib:Utils")
                        test = m.bcUtils.callFunc("toSHA512", "My String")
                        ' test = "8c4b4171030e0483f46805abfa1b9..."
                    

is4kReady

Checks if the current Roku device is capable of reproducing 4K content. The following items are verified:

  • Connected display resolution (must be 2160p for 4K content playback)

  • [Roku STB only] HDCP version (must be 2.2 for 4K content playback)

  • Roku device video decoding capabilities (must be able to decode hevc and vp9 video codecs)

The Roku device is considered 4K Ready if all of these items are valid.

Parameters:

This function has no parameters.

Return Value

BOOLEAN

Returns true if the device is able to reproduce 4K content, false otherwise.

Code Snippet

                    m.bcUtils = createObject("roSGNode", "bcLib:Utils")
                        test = m.bcUtils.callFunc("is4kReady")
                        ' test = true
                    

isHDRReady

Checks if the current Roku device is capable of reproducing the specified HDR type. Uses getDisplayProperties for this purpose.

Parameters:

  • hdr STRING OPTIONAL

    The HDR type to check for support. The following values are supported:

    • "" DEFAULT

      Checks if any HDR type is supported. This is the default behavior if hdr is not provided.

    • hdr10

      Checks if HDR10 is supported.

    • hdr10plus

      Checks if HDR10+ is supported.

    • hlg

      Checks if HLG is supported.

    • dolbyvision

      Checks if Dolby Vision is supported.

Return Value

BOOLEAN

Returns true if the specified HDR type is supported, false otherwise.

Code Snippet

                    m.bcUtils = createObject("roSGNode", "bcLib:Utils")
                        test = m.bcUtils.callFunc("isHDRReady", "hdr10plus")
                        ' test = false
                    

canPlayAudio

Checks if the current Roku device is capable of reproducing the specified audio codec. Essentially this function provides an interface for CanDecodeAudio.

Parameters:

  • params ASSOCIATIVE ARRAY REQUIRED

    Specifies the audio codec to check for support. Supports the same properties as the CanDecodeAudio audio_format parameter.

Return Value

BOOLEAN

Returns true if the device is able to reproduce the specified audio codec, false otherwise. Essentially returns the value of the CanDecodeAudio return result property.

Code Snippet

                    m.bcUtils = createObject("roSGNode", "bcLib:Utils")
                        test = m.bcUtils.callFunc("canPlayAudio", {codec: "eac3", Atmos: 1})
                        ' test = false
                
                    

Logger

The Logger node allows to configure and trigger logging messages.

The bcPlayer node already has an internal Logger node which can be configured through the bcPlayer.logLevel field. Keep in mind that when running a Roku app in production, the bcPlayer logs should be captured through the bcPlayer.on.logOutput event.

A Logger node can also be provided to bcAPI nodes to trigger internal logging messages.

An instance of this node can be created like so:

                sub init()

                    ' create a Logger node instance
                    m.bcLogger = createObject("roSGNode", "bcLib:Logger")
                    
                    ' set the output observe when using the "capture" mode
                    m.bcLogger.observeField("output", "onLog")
                    
                    ' set the "capture" mode so that log messages are sent into the "output" field
                    m.bcLogger.mode = "capture"
                  
                    ' minimum logging level
                    m.bcLogger.level = 1
                    
                    m.bcLogger.callFunc("error", "My error message", <extra-details-to-log>)
                    
                  end sub
                    
                  sub onLog(ev)
                  
                    ' handle the log data here
                  
                  end sub
                

Fields

level

INTEGER OPTIONAL

Specifies the minimum log level. Only log messages with an equal or higher level are triggered.

Possible Values:

  • 0 Error. Triggers Error logs only.

  • 1 Warning. Triggers Warning and Error logs only.

  • 2 Info. Triggers Info, Warning and Error logs only.

  • 3 Debug. Triggers Debug, Info, Warning and Error logs only.

  • 4 DEFAULT Verbose. Triggers all log levels.


mode

STRING OPTIONAL

Specifies where the log messages are sent to.

Possible values:

  • telnet DEFAULT

    Prints log messages in the following format:

    [hh:mm:ss.ms][<level-label>]: <log-message> <optional-data>

  • capture

    Log messages are sent to the output field.


output

ASSOCIATIVE ARRAY

Read-only field used to capture log messages data. This can be useful to transfer log data to an external logging component.

Only applicable if mode is set to capture.

Possible values:

Provides an Associative Array object with the following properties:

  • level INTEGER

    Specifies the log message level.

  • time INTEGER

    Specifies the log message timestamp (in seconds).

  • message STRING

    Specifies the log message.

  • params DYNAMIC

    Specifies extra parameters some log messages might provide. This can be any data type, usually a string or an Associative Array. invalid if no extra parameters are provided.


Functions

The following functions allow log messages to be triggered from the Logger node.

error

Triggers an error log message (level 0).

Parameters:

  • message STRING REQUIRED

    Specifies the log message.

  • params DYNAMIC OPTIONAL

    Specifies the log message.

Code Snippet

                            m.bcLogger = createObject("roSGNode", "bcLib:Logger")
 m.bcLogger.callFunc("error", "my error message", <optional-data>)
                            

warn

Triggers a warning log message (level 1).

Parameters:

  • message STRING REQUIRED

    Specifies the log message.

  • params DYNAMIC OPTIONAL

    Specifies any useful data to be logged.

Code Snippet

                            m.bcLogger = createObject("roSGNode", "bcLib:Logger")
 m.bcLogger.callFunc("warn", "my warning message", <optional-data>)
                                
                            

info

Triggers an info log message (level 2).

Parameters:

  • message STRING REQUIRED

    Specifies the log message.

  • params DYNAMIC OPTIONAL

    Specifies any useful data to be logged.

Code Snippet

                            m.bcLogger = createObject("roSGNode", "bcLib:Logger")
 m.bcLogger.callFunc("info", "my informational message", <optional-data>)
                            

debug

Triggers a debug log message (level 3).

Parameters:

  • message STRING REQUIRED

    Specifies the log message.

  • params DYNAMIC OPTIONAL

    Specifies any useful data to be logged.

Code Snippet

                            m.bcLogger = createObject("roSGNode", "bcLib:Logger")
 m.bcLogger.callFunc("debug", "my debug message", <optional-data>)
                            

verbose

Triggers a verbose log message (level 4).

Parameters:

  • message STRING REQUIRED

    Specifies the log message.

  • params DYNAMIC OPTIONAL

    Specifies any useful data to be logged.

Code Snippet

                            m.bcLogger = createObject("roSGNode", "bcLib:Logger")
 m.bcLogger.callFunc("verbose", "my verbose message", <optional-data>)
                            

Dialog

Dialog provides a StandardDialog node with extended customization options. Since Dialog extends the native StandardDialog, all its fields are accessible through Dialog as well.

Once a Dialog node is instanced and configured, it can be shown by assigning it to the dialog field of the app's Scene node.

Dialog component can be initialized like so:

                sub init()

     ' create a Dialog node instance
     m.dialog = createObject("roSGNode", "bcLib:Dialog")
 
     ' set up its fields
     m.dialog.setFields({ ... })
 
     ' assign it to the app Scene "dialog" field to show it
     m.top.getScene().dialog = m.dialog
 
 end sub
                

Fields

Besides the native fields of StandardDialog, Dialog provides a set of custom fields meant to streamline the creation and setup of a Dialog window.

theme

ASSOCIATIVE ARRAY OPTIONAL

Allows to set up the Dialog theme colors. The properties provided in theme are reflected in the StandardDialog palette field.

Possible values

  • Supports all StandardDialog palette field properties. If not provided, Roku default colors are used.

Code Sinippet

                            m.dialog = createObject("roSGNode", "bcLib:Dialog")
                                m.dialog.theme = {
                                  DialogBackgroundColor: "#29292900",
                                  DialogTextColor: "#D1D1D100",
                                  DialogFocusColor: "#B9323200"
                                }
                        
                                m.top.getScene().dialog = m.dialog
                            

titleConfig

ASSOCIATIVE ARRAY OPTIONAL

Allows to customize the Dialog title area.

Possible values:

Supports all StdDlgTitleArea fields plus the following custom properties:

  • fontSize INTEGER OPTIONAL

    Specifies the Dialog title font size. If not provided, the default StdDlgTitleArea font size is used.

  • fontUrl STRING OPTIONAL

    Specifies the Dialog title font URL. If not provided, the default StdDlgTitleArea font URL is used.

  • align STRING OPTIONAL

    Specifies the Dialog title text horizontal alignment. The following values are supported:

    • left DEFAULT

    • right

    • center

Code Sinippet

                        m.dialog = createObject("roSGNode", "bcLib:Dialog")
                            m.dialog.titleConfig = {
                              primaryTitle: "My Dialog",
                              primaryIcon: "pkg:/my/dialog/icon.png",
                              align: "center"
                            }
                        

content

ARRAY OPTIONAL

Allows to customize the Dialog content area.

Possible values:

Supports an Array where each entry represents a component in the Dialog content area. Any combination of the following items is supported:

  • STRING

    Adds a StdDlgTextItem node to the Dialog content area. The provided string specifies its text field.

  • ASSOCIATIVE ARRAY

    Adds the specified component to the Dialog content area. The type property value defines what type of component will be added as well as the other properties specific to that component. The following sets of properties are supported, per component type:

    • Text component (StdTextItem)
      • type STRING REQUIRED

        Specifies the type of the component, text for a StdDlgTextItem component.

      • text STRING OPTIONAL

        Specifies the StdDlgTextItem text field value.

      • style STRING OPTIONAL

        Specifies the StdDlgTextItem namedTextStyle field value. If not provided, normal is used.

      • align STRING OPTIONAL

        Specifies the text horizontal alignment. The following values are supported:

        • left DEFAULT

        • right

        • center

    • Progress component
      • type STRING REQUIRED

        Specifies the type of the component, progress for a StdDlgProgressItem component.

      • text STRING OPTIONAL

        Specifies the StdDlgProgressItem text field value.

      • interval INTEGER OPTIONAL

        Specifies the internal BusySpinner node spinInterval field value.

      • counterclockwise BOOLEAN OPTIONAL

        Specifies if the internal BusySpinner node should rotate in the counter-clockwise direction. Set to false if not specified.

      • size NUMBER OPTIONAL

        Specifies the width and height values of the internal BusySpinner node.

      • url STRING OPTIONAL

        Specifies the Poster node url of the internal BusySpinner node. The size property is required for the url value to be properly applied.

    • MultiStyle component
      • type STRING REQUIRED

        Specifies the type of the component, multistyle for a StdDlgMultiStyleTextItem component.

      • text STRING OPTIONAL

        Specifies the StdDlgMultiStyleTextItem text field value.

      • styles ASSOCIATIVE ARRAY OPTIONAL

        Specifies the StdDlgMultiStyleTextItem drawingStyles field value. Keep in mind that the specified styles require all the following properties to be provided:

        • fontSize REQUIRED

        • fontUri REQUIRED

        • color REQUIRED

      • align STRING OPTIONAL

        Specifies the text horizontal alignment. The following values are supported:

        • left DEFAULT

        • right

        • center

    • Graphic component
      • type STRING REQUIRED

        Specifies the type of the component, graphic for a StdDlgGraphicItem component.

      • text STRING OPTIONAL

        Specifies the StdDlgGraphicItem text field value.

      • url STRING OPTIONAL

        Specifies the StdDlgGraphicItem graphicUri field value.

      • width NUMBER OPTIONAL

        Specifies the StdDlgGraphicItem graphicWidth field value.

      • height NUMBER OPTIONAL

        Specifies the StdDlgGraphicItem graphicHeight field value.

      • align STRING OPTIONAL

        Specifies the StdDlgGraphicItem graphicAlign field value. The following values are supported:

        • left DEFAULT

        • right

        • center_above

        • center_below

Code Sinippet

                        m.dialog = createObject("roSGNode", "bcLib:Dialog")

                            m.dialog.content = [
                                "My Pretty Dialog",
                                {
                                    type: "text",
                                    text: "My bold and centered Pretty Dialog"
                                    style: "bold",
                                    align: "center"
                                },
                                {
                                    type: "multistyle",
                                    text: "My <p>Pretty</p> Dialog"
                                    styles: {
                                        default: {
                                            fontSize: 34
                                            fontUri: "font:SystemFontFile"
                                            color: "#EFEFEFFF"
                                        },
                                        p: {
                                            fontSize: 42
                                            fontUri: "font:SystemFontFile"
                                            color: "#00FF00FF"
                                        }
                                    },
                                    align: "center"
                                }
                            ]
                            
                            m.top.getScene().dialog = m.dialog
                        

The code snippet above produces the following Dialog content:


sidecard

ASSOCIATIVE ARRAY OPTIONAL

Allows to set up the Dialog side card area.

Possible values:

  • invalid removes the current side card if present.

  • An Associative Array containing any of the StdDlgSideCardArea fields plus the following custom properties:

    • content ASSOCIATIVE ARRAY REQUIRED

      Specifies the Dialog side card contents. Any combination of the following items is supported:

      • ASSOCIATIVE ARRAY

        An Associative Array object specifying the name of a Node and its fields. The following properties are required:

        • node STRING REQUIRED

          Specifies the name of the Node that should be added into the Dialog side card.

        • fields ASSOCIATIVE ARRAY REQUIRED

          Specifies the fields of the Node and its values.

      • NODE

        A Node reference. This Node will be added as is to the side card content area.

Code Sinippet

                        m.dialog = createObject("roSGNode", "bcLib:Dialog")

                            m.dialog.setFields({
                                  titleConfig: { 
                                      primaryTitle : "My Pretty Dialog"
                                  },
                                  content: [
                                      "Once upon a time a pretty Dialog"
                                  ],
                                  sidecard: {
                                      extendToDialogEdge: true,
                                      horizAlign: "left",
                                      width: 300,
                                      content: [
                                          {
                                              node: "Poster",
                                              fields: { 
                                                width: 300, 
                                                height: 300, 
                                                uri: "https://images.unsplash.com/photo-1553095066-5014bc7b7f2d?q=80&w=300&h=300&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxzZWFyY2h8Mnx8d2FsbCUyMGJhY2tncm91bmR8ZW58MHx8MHx8fDA%3D" 
                                              }
                                          },
                                          {
                                              node: "Label",
                                              fields: {
                                                text: "Fancy", 
                                                horizAlign: "center", 
                                                width: 300, 
                                                translation: [0, 180]
                                              }
                                          }
                                      ]
                                  }
                            })
                            
                            m.top.getScene().dialog = m.dialog
                        

The code snippet above produces the following Dialog content:

Image by usplash

buttons

ARRAY OPTIONAL

Allows to set up the buttons of the Dialog.

Since Dialog extends a StandardDialog, its buttons selection and focus events can be accessed through the buttonSelected and buttonFocused fields.

Possible values:

An Array where each item is mapped into a StdDlgButton. Any combination of the following items is supported:

  • A String Value STRING

    Adds a StdDlgButton node with its text field set to the text provided.

  • An Associative Array object ASSOCIATIVE ARRAY

    Allows for some extra StdDlgButton customization options. The following properties are supported:

    • text STRING OPTIONAL

      Specifies the button text.

    • disabled BOOLEAN OPTIONAL

      Specifies if the button should be disabled. A disabled button cannot be focused or selected. If not provided, the default value is false.

    • align STRING OPTIONAL

      Specifies the button text horizontal alignment. The following values are supported:

      • left DEFAULT

        right

        center

    • closeDialog BOOLEAN OPTIONAL

      Specifies if this button should close the Dialog when selected. If not provided, the default value is false.

Code Sinippet

                        m.dialog = createObject("roSGNode", "bcLib:Dialog")

                            m.dialog.setFields({
                              titleConfig: {
                                primaryTitle: "My Pretty Dialog"
                              },
                              buttons: [
                                "Pretty",
                                {
                                    text: "Test",
                                    disabled: false,
                                    align: "center",
                                    closeDialog: true
                                },
                                {
                                    text: "Dialog",
                                    disabled: true,
                                    align: "right",
                                }
                              ]
                            })
                            
                            m.top.getScene().dialog = m.dialog
                        

The code snippet above produces the following Dialog content: