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.

Components

The Brightcove Roku SDK package contains the following components:

Features

The Brightcove Roku SDK package has the following features:

  • OOTB UI/UX.
  • VOD and Live streams playback support.
  • Native HLS/DASH seek thumbnails support.
  • Widevine and Playready DRM support.
  • HLS, DASH and MP4 stream formats support.
  • HLSe (HLS + AES-128 encryption) playback support (v4 manifests only).
  • SSAI support.
    • VOD.
    • Live - Brightcove sources only.
  • CSAI CSAS support.
    • VOD.
    • Live [to be implemented].
  • Brightcove Analytics support (Data Collection API v2).
  • Multichannel Audio on supported devices (5.1 AC3, 5.1 E-AC3, Dolby Atmos)
  • OOTB Voice Controls support.
  • Brightcove Forensic Watermarking
  • Configurable sources and DRM systems prioritization.
  • Multiple Audio Tracks support.
  • Configurable stream buffering timeout.
  • Expired sources refresh.
  • Playback retry on stream error.
  • Brightcove Playback API interfaces
  • Brightcove Edge Playback Authorization (EPA) support.
  • Load custom Brightcove videos metadata.
  • External video and playlist sources support.
  • Utilities
    • Brightscript general utilities
    • Logging component
    • Dialog component

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.

Custom UI/UX

  • TBD.

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 is triggered as soon as the pre-roll ends).
  • video_engagement: Sent periodically every 10 seconds while video content is playing.
  • 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.

Supported parameters

  • 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. This parameter 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).

Setup

To setup Brightcove Roku SDK in a Roku channel, you must request access to the SDK package file. Brightcove provides two ways for developers to access the SDK package file.

Package Sources

To include the Roku SDK in your project, you will need to obtain the SDK package source. Brightcove provides access to the Roku SDK through a specific URL endpoint using Semantic Versioning. This enables you to target specific versions of the SDK you wish to implement in your Roku applications.


  <!-- Latest Major Version -->
  https://players.brightcove.net/roku-sdk/{MAJOR_VERSION}/roku-sdk.pkg
  
  <!-- Specific Version -->
  https://players.brightcove.net/roku-sdk/{MAJOR_VERSION}.{MINOR_VERSION}.{BUILD_VERSION}/roku-sdk.pkg
      

Available Versions

  1. 1.0.0
  2. 1.0.1
  3. 1.2.0
  4. 1.2.1
  5. 1.2.2
  6. 1.2.3
  7. 2.0.0

Retrieving a Specific Version

To download a specific version of the Roku SDK, replace the placeholders in the URL with the respective version numbers. For instance, to download version 1.2.3, your URL would be:


  https://players.brightcove.net/roku-sdk/1.2.3/roku-sdk.pkg
      

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://brightcove/sdk/remote/url/here/bcLib.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.
                    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 (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 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.
                    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 library package into their Roku channel.

Accessing 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:

        
            ' 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")
        

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.setFields({
              streamPreference: ["hls", "dash", "mp4"],
              drmPreference: ["widevine", "playready", "none"],
              logLevel: 4,
              credentials: invalid,           
              env: "production",
              watermarkToken: "",
              spinnerConfig: {},
              closeOnBack: true,
              retryOnError: true,
              enableDialogs: true,
              bufferTimeout: 0,
              dialogTheme: {
                DialogBackgroundColor: "#00000000",
                DialogSecondaryItemColor: "#00000000"
              },
              loading: false
            })

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

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

            csai = m.bcPlayer.csai
            csai.setFields({
              enabled: false
              useCSAS: true
              closeOnFinish: true
              maxRequests: 1
              enableJIT: true
              enableInPodStitching: true
              adMeasurements: {}
              adConstraints: {}
              event: {} ' read-only
            })
        

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 API.

If the credentials aren’t provided, the bcPlayer node will only be able to playback videos from external sources through bcPlayer.setSources and bcPlayer.addSource functions.

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).
      • To specify License Keys Protection for HLSe content playback.

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:

An ASSOCIATIVE ARRAY containing the following keys:

  • A string containing the Forensic Watermarking token.

  • "" DEFAULT

                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:

An array containing any combination of the following values:

  • -1 disable all the logging.

  • 0 log error messages only.

  • 1 log error and warning messages.

  • 2 log error, warning and info messages.

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

  • 4 DEFAULT log error, warning, info, verbose and debug 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 loading spinner. This field is independent from the OOTB UI built in loading spinner.

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

Possible Values:

An array containing any combination of the following 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

Configures the activation of the retry on error flow. This flow allows bcPlayer to automatically retry the video playback with another video source when a specific source results in a playback error during the initial 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 streamPreference and 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.

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
                    })
                

closeOnBack

BOOLEAN OPTIONAL

Configures the back remote control button action to terminate the bcPlayer node when pressed.

It’s enabled by default, when you press the back button, the bcPlayer node will be terminated (to bring it back, it needs to be reinitialized from scratch).

This behavior can be disabled, in which case developers can capture the back button press through a bcPlayer.on.keyEvent event listener and handle it as they see fit without having to terminate the bcPlayer node.

Possible Values:

  • false Disables the close on error behavior.

  • true DEFAULT Enables the close on error behavior.

Code Snippet

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

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
                    })
                

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"
                      }
                    })
                

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
                

bufferTimeout

INTEGER OPTIONAL

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

Setting it to 0 disables the buffering timeout timer.

If the retryOnError config is enabled, if a buffering timeout error is trigger it’ll retry playing other available sources with no visual interruption to the user. Although an error will still be triggered through the bcPlayer.on.error event.

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
                

on

ROSGNODE 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. Check the code snippet to understand how to setup event listeners to capture these events.

Event List

Events
Event Data Description
sdkReady

BOOLEAN

  • true bcPlayer features are "live" and 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.

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.

start

ASSOCOATIVE ARRAY

Provides an ASSOCIATIVE ARRAY object with the following properties:

  • 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.

  • 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 at the start of every video playback. It triggers only once per video asset, and it provides a set of useful information about the video that just started playing. Most of the information provided is retrieved from the native Video node. Please refer to the Roku documentation for more specific details on those fields.

play To be implemented
pause To be implemented
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 NATIVE

  • Integer number

Triggered right before starting video playback. Provides the index of the video that will start playing in the playlist.

This event reflects the native Video.contentIndex field and its generally useful when playing video playlists.

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.

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

    • addSource triggered when an error occurs within the addSource 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 NATIVE 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
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.

close

BOOLEAN

  • true the bcPlayer node has been completely terminated.

  • false not used.

Triggered when the bcPlayer is completely terminated. Keep in mind that when the close function is called, the bcPlayer is not terminated immediately as it still waits for any task that might still be in progress. Once all tasks complete, the close event is triggered.

This event can be used to clean up any remaining bcPlayer references and observers.

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.

voiceComand

ASSOCIATIVE ARRAY

Provides an ASSOCIATIVE ARRAY object with the following keys:

  • handled BOOLEAN REQUIRED

    Indicates if the event was handled internally by bcPlayer.

  • event specific properties

Provides voice commands events data. The contents of the ASSOCIATIVE ARRAY will vary depend of the voice command event. It contains the native event properties plus the handled property which indicates if the event was handled internally by bcPlayer. Keep in mind that some events may not be triggered in this event when the native Video node captures it and handles it internally, specially when using the Roku’s OOTB UI/UX.

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 = ev.getData()   ' "data" contains the event data
                    event = ev.getField() ' "event" contains the event name ("finished" or "error" in this example)
                    
                    ' 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:  ' 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).

      • vmap-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 ASSOCIATIVE ARRAY REQUIRED

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

    • live ASSOCIATIVE ARRAY REQUIRED

      Specifies if the currently playing asset is a live stream.

                            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.

useCSAS

BOOLEAN OPTIONAL

Toggles the CSAI implementation between Client-Side Ad Stitching (CSAS) and RAF’s showAds() function.

Possible values:

  • true DEFAULT - Implements Client-Side Ad Stitching (CSAS).

  • false - implements CSAI through RAF's showAds() function.

closeOnFinish

BOOLEAN OPTIONAL

Specifies if bcPlayer should automatically close when CSAI video playback finishes. Only applicable when playing a single video or the last video in a playlist.

Possible values:

  • true DEFAULT - closes the bcPlayer when CSAI video playback finishes.

  • false - no action occurs when playback finishes. The close even can be accessed through bcPlayer.csai.event to customize the behavior.

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 1
enableJIT

BOOLEAN OPTIONAL

Specifies RAF’s enableJITPods() function parameter.

Possible values:

  • true DEFAULT - Enables “Just In Time” fetching of midroll ads.

  • false - disabled JIT feature.

enableInPodStitching To be implemented.
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

Asynchronously loads Playback API contents (a video or a playlist) into the bcPlayer and starts the playback. 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 may trigger two bcPlayer.on.load events:

  • A start event when the load process begins.
  • an error event when an error occurs during the load process.
  • An end event when the load process is completed and the new Video content is set.

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 [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 the video from auto playing when the load process ends. By default autoplay is set to 0.

    • position STRING OPTIONAL [To be implemented] 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
                
                        ' [To be implemented] 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 a listener 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 single video 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 ASSOCIATIVE ARRAY 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.

    • [To be Implemented] 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.

      • [To be Implemented] append

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

      • [To be Implemented] 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 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, 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 [To be implemented].

      • 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 details.

    • 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

      [To be implemented] 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.

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 ' To be implemented feature
                            })
                    
                            ' OR
                    
                            ' autoload disabled
                            responseNode = m.bcPlayer.callFunc("getVideo", videoID, {
                              params: {ad_config_id: adConfigID},
                              autoload: false
                            })
                    
                            ' 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
                    
                            ' 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 ' To be implemented feature
                            })
                    
                          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 [To be implemented].

      • 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

      [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

      [To be implemented] 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.

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 ' To be implemented feature
                            })
                    
                            ' OR
                    
                            ' autoload disabled
                            responseNode = m.bcPlayer.callFunc("getVideos", "name:wildlife", {
                              params: {limit: 10, offset: 20},
                              autoload: false
                            })
                    
                            ' 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
                    
                            ' 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 ' To be implemented feature
                            })
                    
                          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 [To be implemented].

      • 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

      [To be implemented] 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

      [To be implemented] 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.

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 ' To be implemented feature
                            })
                    
                            ' OR
                    
                            ' autoload disabled
                            responseNode = m.bcPlayer.callFunc("getPlaylist", playlistID, {
                              params: {limit: 10, offset: 20},
                              autoload: false
                            })
                    
                            ' 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
                    
                            ' 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 ' To be implemented feature
                            })
                    
                          end sub
                    
                        

getRelated

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

Using the name and short description of the specified video, 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

      [To be implemented] 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

      [To be implemented] 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.

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 ' To be implemented feature
                            })
                    
                            ' OR
                    
                            ' autoload disabled
                            responseNode = m.bcPlayer.callFunc("getRelated", videoID, {
                              params: {limit: 10, offset: 20},
                              autoload: false
                            })
                    
                            ' 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
                    
                            ' 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
                        

playback

Allows control of bcPlayer playback. It provides the same playback actions as the native Video control field plus some other custom actions introduced by bcPlayer.

Parameters:

  • action STRING REQUIRED

    Specifies the playback action. The supported values are:

    • All values supported by the native control field:

      • play

        • To play a specific video in the playlist, the index can be provided through the data parameter.

        • By default it plays the first video in the playlist if an index is not specified.

        • If play is requested over the same video that is currently playing, it will behave as pause (if the the video is currently playing) or resume (if the video is currently paused).

      • pause

      • resume

      • stop

      • replay

      • prebuffer

      • skipcontent

    • next

      If current content is a playlist, skips to the next video, if available. Otherwise does nothing. Before skipping, the next video source TTL is validated and if expired the sources will first be refreshed and only then the skip action gets triggered. SSAI or CSAI is also setup, if enabled and applicable, while loading the next video.

    • previous

      If current content is a playlist, skips to the previous video, if available. Otherwise does nothing. Before skipping, the previous video source TTL is validated and if expired the sources will first be refreshed and only then the skip action gets triggered. SSAI or CSAI are also setup, if enabled and applicable, while loading the previous video.

    • seek

      Allows to seek to a specific playback position. This is specially useful during CSAI video playback, where the active Video node isn’t easily accessible. The position value should be specified through the data parameter.

  • data DYNAMIC OPTIONAL

    Allows extra data to be provided to execute the applicable actions. Valid for the following actions:

    • play INTEGER OPTIONAL

      • data can specify the video index for playback.

    • seek INTEGER

      • data should specify the seek position.

Return Value

  • boolean

    Returns true if the parameters provided are valid. Be aware that it might still return true and the next or previous actions are not applicable (i.e., next won't work if it's playing the last video in a playlist).

Code Snippet

                        sub init()
                      ' play the video index 3 in the playlist
                      m.bcPlayer.callFunc("playback", "play", 3)
                    
                      ' seek to the position 54 in the stream
                      m.bcPlayer.callFunc("playback", "seek", 54)
                    
                      ' skip to the next video, if available and if content is a playlist
                      m.bcPlayer.callFunc("playback", "next")
                    
                      ' the same can be accomplish with:
                      m.bcPlayer.callFunc("playlist", "next")
                    
                    end sub
                        

playlist

Provides playlist specific features. Allows for a better control over items in a playlist. If bcPlayer content is not a playlist, this function will do nothing.

Parameters:

  • action STRING REQUIRED

    Specifies the action to be executed. The following values are supported:

    • contains

      [To be implemented] Checks if a video exists in the playlist through the video URL provided.

    • currentIndex

      Get the index of the video that is currently playing in the playlist.

    • currentItem

      Get the ContentNode of the currently playing video in the playlist.

    • item

      Get the ContentNode of the specified video index in the playlist.

    • first

      Get the ContentNode of the first video in the playlist.

    • indexOf

      [To be implemented] Get the index of a video through the video URL provided.

    • last

      Get the ContentNode of the last video in the playlist.

    • lastIndex

      Get the index of the last video in the playlist.

    • next

      Skips to the next video, if available. Otherwise does nothing. Before skipping, the next video source TTL is validated and if expired the sources will first be refreshed and only then the skip action gets triggered.

    • nextIndex

      Get the index of the next video in the playlist.

    • previous

      Skips to the previous video, if available. Otherwise does nothing. Before skipping, the previous video source TTL is validated and if expired the sources will first be refreshed and only then the skip action gets triggered.

    • previousIndex

      Get the index of the previous video in the playlist.

    • sort

      [To be implemented] Sorts the videos in the playlist

    • shuffle

      [To be implemented] Shuffles the videos in the playlist.

    • remove

      Removes the specified video index from the playlist.

  • data DYNAMIC OPTIONAL

    Parameters for some of the supported actions. Required for the following actions:

    • item

      INTEGER Specifies the video index.

    • [To be implemented] contains

      STRING Specifies the searched video URL.

    • [To be implemented] indexOf

      STRING Specifies the searched video URL.

    • [To be implemented] sort

      Specifies the sort options.

    • [To be implemented] remove

      STRING Specifies the video index.

Return Value

DYNAMIC The return value depends on the action executed. If content is not a playlist the return value is invalid for all actions. Otherwise, the return value per action is the following:

  • contains BOOLEAN

  • currentIndex INTEGER

  • currentItem NODE

  • item NODE

  • first NODE

  • indexOf INTEGER

  • last NODE

  • lastIndex INTEGER

  • next INVALID

  • nextIndex INTEGER

  • previous INVALID

  • previousIndex INTEGER

  • sort INVALID

  • shuffle INVALID

Code Snippet

                        sub init()
                            ' get the index of the next video in the playlist, if content is a playlist
                            nextVideoIndex = m.bcPlayer.callFunc("playlist", "nextIndex")
                            if nextVideoIndex = invalid then
                    
                              ' current content is not a playlist. Handle that situation here if required.
                    
                            end if
                    
                          end sub
                        

close

Closes bcPlayer and terminates all ongoing tasks and playback in the bcPlayer. The closing procedure is asynchronous so that any pending task doesn’t get abruptly interrupted. The closed confirmation can be obtained from the bcPlayer.on.close event.

Parameters:

  • This function has no parameters

Return Value

  • VOID

Code Snippet

                        sub init()
                            ' listen for the "close" event, in case some action needs to be taken only after the complete termination of the bcPlayer
                            m.bcPlayer.on.observeField("close", "onClose")
                    
                            ' trigger the close action
                            m.bcPlayer.callFunc("close")
                    
                          end sub
                    
                          sub onClose(ev)
                    
                            ' m.bcPlayer is now completely terminated
                    
                          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:

Video Sources
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.

    • Encryption dependent:

      • HLSe: The source with a ext_x_version property value different than 7.

      • HLS: 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: [, ...] 
                                },
                                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.

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")
          
            ' since a Task node initizalization is assyncronous, observe the "ready" field so all functions can be accessed once bcAPI loads completely
            m.bcAPI.observeField("ready", "onAPIready")
            
            ' configure bcAPI node fields
            m.bcAPI.setFields({
              credentials: invalid,
              
              logger: invalid, ' optional: provide a bcLib:Logger reference to capture logs from the bcAPI node
              maxRequests: 5,
              kill: false,
              abort: false,
              control: "run" ' initialize bcAPI task imediately
            })
            
          end sub
          
          <...>
          
          sub onAPIready(ev)
            isReady = ev.getData()
            if isReady then
            
              ' m.bcAPI node is ready to trigger API requests
              
            else
            
              ' m.bcAPI node was terminated and is no longer available to process new API requests
            
            end if
            
          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. Specially useful when parsing responses from the response field instead of a response Node. If not provided, the response id property is set to the timestamp the request was initiated at.

    • 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.

    • 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")
                        
                        ' observe the "ready" field
                        m.bcAPI.observeField("ready", "onReady")  
                        
                        ' setup bcAPI config fields and initiate the bcAPI Task
                        m.bcAPI.setFields({
                          ' ...
                          control: "run"
                        })
                        
                      end sub
                      
                      sub onReady(ev)
                        
                        isReady = ev.getData()
                        if isReady then
                        
                          ' 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: {
                              id: "myCustomRequest" ' it's important that a custom ID is set here so that this request response can be easily identified in the response observing function
                              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: {
                              id: "myOtherCustomRequest" ' the id could be omitted when parsing the response in a specific function
                              url: "https://my.other.request.url"
                              method: "post",
                              body: {someOther: "body-content"}
                              options: {extradata: "some other data I may need in the response"}
                            }
                          }
                        
                        end if
                        
                      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

                ' just like the request action, once the bcAPI is ready, the flow should be exactly the same
                    sub onReady(ev)
                    
                      ' 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: "",
                        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: "",
                        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

                ' just like the request action, once the bcAPI is ready, the flow should be exactly the same
                    sub onReady(ev)
                    
                      ' 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: "<videos-search-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 Hide the custom loading spinner.

    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

                ' just like the request action, once the bcAPI is ready, the flow should be exactly the same
                    sub onReady(ev)
                    
                      ' 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

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 Hide the custom loading spinner.

    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

                ' just like the request action, once the bcAPI is ready, the flow should be exactly the same
                    sub onReady(ev)
                    
                      ' 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

                ' ...

                    m.bcAPI.abort = true ' 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 value.

    • duration FLOAT

      Request duration since its initialization until a response is received.

    • body STRING / ASSOCIATIVE ARRAY

      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.

  • 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")
                
                        ' observe the "ready" field
                        m.bcAPI.observeField("ready", "onReady")
                
                        ' setup bcAPI config fields and initiate the bcAPI Task
                        m.bcAPI.setFields({
                          ' ...
                          control: "run"
                        })
                
                      end sub
                
                      sub onReady(ev)
                
                        isReady = ev.getData()
                        if isReady then
                
                          ' 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 if
                
                      end sub
                
                      sub onResponse(ev)
                
                        response = ev.getData()
                
                        ' handle request response
                
                      end sub
                    

ready

BOOLEAN

Indicates if the bcAPI Task is ready to receive request commands, Because of the asynchronous nature of Roku Task nodes, it’s recommended to observe for the ready field and only make use of it once ready is true. It can then be observed for the false value to confirm that the Task was completely terminated, if needed.

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"
                    })
                    
                  end sub
                  
                  sub onReady(ev)
                    
                    isReady = ev.getData()
                    if isReady then
                      
                      ' bcAPI is ready to trigger HTTP/API requests
                      
                    else
                    
                      ' bcAPI hasn't been initiated yet OR hasn't been completely terminated yet
                    
                    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

INTEGER

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

  • -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 check.

  • 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 to check.

  • pattern STRING REQUIRED

    The end characters to check.

  • 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 for logging messages to be configured and triggered.

bcPlayer node has an internal Logger node and one can also be provided to the bcAPI node so that internal log messages can be triggered and captured.

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

Allows the minimum log level to be customized. Only log messages with an equal or higher level are printed or sent to output.

Possible Values:

  • 0 Error. All log messages are processed.

  • 1 Warning. Only warning or higher level log messages are processed.

  • 2 Info. Only Info or higher level log messages are processed.

  • 3 Verbose. Only verbose or higher level log messages are processed.

  • 4 DEFAULT Debug. Only debug or higher level log messages are processed.


mode

STRING OPTIONAL

Specifies the log mode.

Possible values:

  • telnet DEFAULT

    Immediately prints log messages in the following format:

    [hh:mm:ss.ms][<level-label>]: <log-message> <optional-data>

  • capture

    Log messages are sent to output.


output

ASSOCIATIVE ARRAY

Read-only field used to capture log details. May be useful to transfer log details to be processed by an external log handler.

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>)
                            

verbose

Triggers a verbose 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("verbose", "my verbose message", <optional-data>)
                            

debug

Triggers a debug 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("debug", "my debug 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
      • 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 

Pretty

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:

  • STRING

    Adds a StdDlgButton node with its text field set to the text provided.

  • An Associative Array containing any of the StdDlgSideCardArea fields plus the following custom properties:

    • ASSOCIATIVE ARRAY

      Allows for some extra StdDlgButton customization options. The following properties are supported:

      • ASSOCIATIVE ARRAY

        An Associative Array object specifying the name of a Node and its fields. The following properties are required:

        • 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: