Overview
The Brightcove Roku SDK is a Roku ComponentLibrary package that can be imported and loaded into a Roku channel, allowing easy access to Brightcove’s Playback services in a Roku channel through a set of Brightscript components.
Index
- Features
- Sample App
- Setup
- Components
- bcPlayer
- Fields
- credentials
- watermarkToken
- streamPreference
- drmPreference
- logLevel
- spinnerConfig
- loading
- retryOnError
- retryOnBufferTimeout
- closeOnBack
- closeOnFinished
- enableDialogs
- enableGSC
- dialogTheme
- bufferTimeout
- analytics
- bufferTimeout
- sdkVersion
- adPlaying
- relativePosition
- visibleOnScreen
- playback
- analytics
- on
- ssai
- csai
- Functions
- Video Sources selection
- Fields
- bcAPI
- Utils
- Logger
- Dialog
- bcPlayer
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 - Pre-rolls only.
- Brightcove Analytics support (Data Collection API v2).
- Brightcove Ad Insights support.
- Brightcove Cross-Device Resume support.
- Multichannel Audio on supported devices (5.1 AC3, 5.1 E-AC3, Dolby Atmos)
- OOTB Voice Controls support.
- Brightcove Forensic Watermarking.
- Custom playlists support.
- 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
- Retrieve a video by video ID or reference.
- Retrieve videos by search query.
- Retrieve related videos by video ID or reference.
- Retrieve videos by playlist ID or reference.
- Brightcove Edge Playback Authorization (EPA) support.
- Brightcove Generic Stream Concurrency.
- Load custom Brightcove videos metadata.
- External/Custom sources support.
- Utilities
- Brightscript general utilities.
- Logging component.
- Dialog component.
Future additions
- TVe support
- Google IMA DAI support
- Custom trickplay UI/UX support
Sources Refresh
Brightcove video sources have a Time To Live (TTL) timestamp associated with it which, once expired, video playback will not be possible through that source. The bcPlayer automatically checks for sources TTL expiration in the following situations:
- When starting a video playback for the first time.
- When switching to a previous or next video in a playlist.
If a Brightcove video source is detected to be expired, it’ll be automatically refreshed by:
- Retrieving updated source URL from the Playback API.
- Reset the video
url
ContentNode field. Keep in mind this step may trigger anybcPlayer.content
observing functions.
Once the video sources are updated, bcPlayer will resume the requested action (next/previous, play the requested video, load CSAI/SSAI handlers, complete the ongoing metadata loading process) with the updated sources in place.
Voice Controls
Allows users to control the video playback through voice commands. These voice commands are captured by a supported Roku Remote Control as well as the Roku mobile app and sent to the Roku app. With the OOTB Roku UI most of these commands are handled natively. With a custom UI experience the Brightcove SDK will automatically handle the commands. Learn more.
OOTB UI/UX
- Basic Commands.
- play - Start playback if paused or stopped / resume playback if paused.
- pause - Pause playback.
- ok - Pause / resume playback.
- replay - Rewind playback 10 to 25 seconds (time depends on application's implementation).
- rewind - Rewind playback until another command is received and processed.
- forward - Fast forward playback until another command is received and processed.
- Enhanced commands.
- start over - Start playback from the beginning.
- seek - Skip playback forwards or backwards by the specified time.
- next - Play next video when having a playlist.
Brightcove Generic Stream Concurrency
The Generic Stream Concurrency allow users to limit stream concurrency using a heartbeat mechanism without the need for DRM. Generic Stream Concurrency allows you to specify the maximum number of video streams a particular user can watch simultaneously. Limiting stream concurrency will help the user to prevent their content being stolen or illegally watched through the theft or inappropriate sharing of credentials.
In order for the Generic Stream Concurrency feature to work, a JWT must be provided in the bcPlayer.credentials.auth_token
property and the bcPlayer.enableGsc
flag must be enabled.
Brightcove Analytics
The following events and their respective fields will be sent automatically to Brightcove by the SDK. The end user can provide the information for most of the fields in each event. Alternatively, the SDK will attempt to build it and include it in the events. Otherwise, some fields won't be sent. Learn more.
Events
- player_init: Sent when the player is initialized.
- player_load: Sent when the player is initialized.
- video_impression: Sent when the metadata for a video added to the player finishes loading and the player is ready to start video playback, either via auto-play or user interaction.
- play_request: Sent when the user presses to play the asset. (once per session per media stream).
- video_view: Sent when the first frame of the video starts (applies to the video content. If a pre-roll is present, the
video_view
is triggered as soon as the pre-roll ends). - video_engagement: Sent periodically every 10 seconds while video content is playing, or sooner if playback is interrupted for any reason.
- ad_mode_begin: Sent when an ad break starts.
- ad_mode_complete: Sent when an ad break finishes.
- error: Sent when a playback error occurs.
- catalog_request: Sent when a request to the Playback API is triggered (through
bcPlayer
only). - catalog_response: Sent on a successful Playback API response.
- catalog_request_error: Sent on an error Playback API response.
Metrics
- sesion: random UUID representing the unique session ID.
- domain:
videocloud
videocloud 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 thebcPlayer.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. Theuser
is also required to use Brightcove’s Cross-Device Resume feature. This value should be provided through thebcPlayer.analytics.user
field. - destination:
OPTIONAL
value ofbcPlayer.analytics.destination
, if provided. - source:
OPTIONAL
value ofbcPlayer.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>
- if
- 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
.
- if only
- 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 frombcPlayer.streamingSegment
in case of MP4 playback). - rendition_indicated_bps: specifies the stream bitrate (this value is retrieved from
bcPlayer.streamingSegment
andbcPlayer.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
andbcPlayer.downloadedSegment
). - rendition_width: specifies the rendition width (this value is retrieved from
bcPlayer.streamingSegment
andbcPlayer.downloadedSegment
). - rebuffering_seconds: specifies the rebuffering duration measured during the buffering state of bcPlayer.
- rebuffering_count: specifies the number of rebufferings in a playback session.
- forward_buffer_seconds: specifies the start time of the segment from the start of the video (this value is retrieved from
bcPlayer.downloadedSegment
). - measured_bps: specifies the ratio of the number of bits included in the most recently downloaded segment to the time spend downloading that segment, in bits per second. Calculated from the data provided by
bcPlayer.downloadedSegment
. - player_width: specifies the player width as per the
bcPlayer.width
field. - player_height: specifies the player height as per the
bcPlayer.height
field. - dropped_frames: specifies the number of frames that have been dropped since playback was started (this value is retrieved from
bcPlayer.decoderStats
). - remote_ip: specifies the Roku device external IP address.
- user_agent: specifies Roku's user-agent value as per
roUrlTransfer.GetUserAgent()
. - platform: hardcoded to
"roku-sdk"
. - media_type: hardcoded to
"video"
. - delivery_type:
"ondemand"
for VOD,"live"
for live streams. - start_time_ms: specifies the video playback start time.
- load_time_ms: specifies the video load time.
Ad Insights
Ad insights helps understand the impact of ad monetization on audience's engagement by showing the relationships between ad frequency/intensity and session length/frequency to help understand the most effective ad loads.
The following events and metrics are supported in the Roku SDK. Since some of the metric values are retrieved from the VAST/VMAP file provided, it’s possible that some metrics are not sent if their values can’t be found. Learn more
Events
- ad_mode_begin: Sent when the ad pod begin.
- ad_error: Sent when there was an error during ad mode.
- ad_begin: Sent when an ad within the pod has begun.
- ad_viewable_impression: Sent per the MRC Viewability Standards. (The ad must be at least 50% visible on the screen for two consecutive seconds. These do not have to be the first two seconds, but can be any two seconds during the ad’s playback).
- ad_complete: Sent when an ad within the pod has ended.
- ad_mode_complete: Sent when the ad pod has ended.
- video_resumed: Sent when the content playback has resumed. (This is only send following mid-rolls).
Metrics
- ads_pod_index: Specifies the index of the pod relative to the content.
- ads_pod_ad_count: Specifies the number of ads in the current pod.
- ads_pod_duration: Specifies the total number of seconds the ad pod is expected to run.
- ads_pod_host: Host name from the ad server URL called to return the ad pod.
- ads_pod_type: Specifies the type of the pod (pre, mid, post).
- ads_pod_request_ms: Milliseconds from ad request sent to ad request received.
- ads_pod_request_mode: Specifies how ads were requested.
- ads_pod_time_offset: Specifies the content time offset at which the current ad pod was scheduled.
- ads_ad_index: Specifies the position of the ad relative to the pod.
- ads_ad_system: Specifies source ad server information included in the ad response.
- ads_ad_advertiser: Specifies the advertiser name as defined by the serving party.
- ads_ad_isci: Specifies the CI (Industry Standard Commercial Identifier) code for an ad. Currently we are attributing the adId.
- ads_ad_creative_id: Specifies the ID of the selected creative for the ad.
- ads_ad_duration: Specifies the duration in seconds of the selected ad.
- ads_ad_title: Specifies the ad title from the VAST response.
- ads_ad_audible_duration: Specifies the number of seconds of ad playback where volume was >= 1% and not muted.
- ads_ad_play_duration: Specifies the number of seconds of ad media played.
- ads_ad_skipped: Specifies if the ad was skipped.
- ads_ad_interaction: Specifies if the ad was interacted.
Sample App
The Roku SDK Sample App provides a set of Roku SDK application examples to help you learn about the Roku SDK components and features in a practical environment.
The README.md file provides all the details on how to set it up, configure, customize and launch
Setup
To setup Brightcove Roku SDK in a Roku channel you first need to request access to the SDK package file. Since Roku’s ComponentLibrary allows packages to be imported and loaded both locally and remotely into a Roku channel, Brightcove provides two different ways for developers to gain access to the SDK package file.
Package Sources
The Roku SDK library package sources can be obtained from https://players.brightcove.net/roku-sdk. Since Roku SDK releases use Semantic Versioning, the URL endpoint will vary depending on what release version of interest. It’s possible to obtain specific versions of the Roku SDK package like so:
https://players.brightcove.net/roku-sdk/{MAJOR-VERSION}.{MINOR-VERSION}.{BUILD-VERSION}/roku-sdk.pkg
Where MINOR-VERSION
and BUILD-VERSION
are optional, but MAYOR-VERSION
is always required.
A full list of available Roku SDK versions is included in the changelog.
Brightcove always recommends the latest Roku SDK version, but if you have specific need of a version, you can specify version numbers in the URL.
For example, if we assume that these versions were available:
- 1.0.0
- 1.0.1
- 1.2.0
- 1.2.1
- 1.2.2
- 1.2.3
- 2.0.0
The following examples specify how the Roku SDK packages could be retrieved based on the requested version:
https://players.brightcove.net/roku-sdk/1/roku-sdk.pkg
- refers to the most recent version in the v1 major release. In this example, it would refer to the v1.2.3 release.- Keep in mind that if the v1.2.4 or v1.3.0 versions were released, this endpoint would retrieve those packages instead.
https://players.brightcove.net/roku-sdk/1.0/roku-sdk.pkg
- refers to the most recent version in the v1.0 minor release. In this example, it refers to the v1.0.1 release.https://players.brightcove.net/roku-sdk/1.2.3/roku-sdk.pkg
- in this case, refers to the v1.2.3 release.
It’s also possible to retrieve the most recent version of the Roku SDK library package from the following endpoint:
Changelog
The changelog can be retrieved from the following endpoint. A full list of available Roku SDK versions is included.
Loading the library directly from the source
In this case the Roku SDK package URL can be set directly into the ComponentLibrary
uri
field. The ComponentLibrary
node will handle the package file download and loading process automatically. For example, to load the latest v1 major release into a Roku channel, you can follow these steps:
In the scene XML component, create the
ComponentLibrary
node and set itsid
anduri
fields.The
uri
field contains the SDK package URL.The
id
field is used during the library components initialization.
<?xml version="1.0" encoding="utf-8" ?> <component name="MainScene" extends="Scene"> <interface> <!-- your mainscene fields here --> </interface> <script type="text/brightscript" uri="MainScene.brs"/> <children> <ComponentLibrary id="bcLib" uri="https://players.brightcove.net/roku-sdk/1/roku-sdk.pkg" /> </children> </component>
- In the
init()
function of the Scene's brightscript file, set up the ComponentLibrary reference and an observer for theloadStatus
field so you can detect when the SDK library is successfully downloaded and ready to be referenced.sub init() m.bcLib = m.top.findNode("bcLib") m.bcLib.observeField("loadStatus", "onLoadStatus") end sub sub onLoadStatus(ev) status = ev.getData() if status = "ready" then ' bcLib was successfully downloaded and all its components are now accessible else if status = "loading" then ' bcLib package is currently being downloaded else if status = "failed" then ' Something went wrong with the bcLib download/load process. ' Please check if the package URL was properly set. end if end sub
Loading the library locally
In this case, you should manually download the Roku SDK package file from Brightcove sources and embed it into a Roku channel. In this process the library is simply loaded from the internal channel’s file structure at runtime. This is the recommended approach as it’s much faster and efficient than letting ComponentLibrary
download and load the SDK package. For this approach, the following steps can be taken:
- Download the SDK package manually.
- Place the SDK package in the Roku channel file structure (feel free to rename the file, in this case we named it bcLib.pkg). The exact location doesn't matter. In the following example, it was placed in the lib directory.
- In the scene XML component, create the
ComponentLibrary
node and set theid
anduri
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>
- The
- In the scene's
init()
function of the Scene's brightscript file, set up the ComponentLibrary reference and an observer for theloadStatus
field so you can detect when the SDK library is successfully loaded.sub init() m.bcLib = m.top.findNode("bcLib") m.bcLib.observeField("loadStatus", "onLoadStatus") end sub sub onLoadStatus(ev) status = ev.getData() if status = "ready" then ' bcLib was successfully downloaded and all its components are now accessible else if status = "loading" then ' bcLib package is currently being downloaded else if status = "failed" then ' Something went wrong with the bcLib download/load process. ' Please check if the package URL was properly set. end if end sub
Loading the library dynamically
It’s recommended to set the ComponentLibrary
in the scene’s children section with the proper package URL so that the library loading process starts immediately during the Scene initialization, but depending on the use case, it could also be useful to be able to dynamically load the library anywhere in the channel. This can be done by initializing the ComponentLibrary
node in the brightscript code as such:
sub init()
' this can be placed anywhere in the Scene node code,
' although usually we want it to load as soon as possible so we can immediately access its components
m.bcLib = createObject("roSGNode", "ComponentLibrary")
m.bcLib.observeField("loadStatus", "onLoadStatus")
m.bcLib.id = "bcLib"
m.bcLib.uri = "<path_or_url_to_the_pkg_file>"
end sub
This allows you to control where and when exactly they want to load the Roku SDK library package into their Roku channel.
Accessing Roku SDK components
Once the SDK library is successfully loaded (ie, the ComponentLibrary
loadStatus
field is ready
), an instance of any of its components can be created like so:
' creating an instance of the bcPlayer component from the bcLib library
' 1 - create an instance of the bcPlayer node
' This won't make the bcPlayer node visible in the app, it still needs to be added to the node tree list after this step
m.bcPlayer = createObject("roSGNode", "bcLib:bcPlayer")
' 2 - create an instance of the bcPlayer node and append it to the parentNode node.
' If parentNode is already in the node tree list and is visible, this will also make the bcPlayer node visible in the app
m.bcPlayer = parentNode.createChild("bcLib:bcPlayer")
In place of the usual SGNode component name (in the createObject
and createChild
functions), an external library component must be referred as: “
<ComponentLibrary-id>
:
<component-name>
".
bcPlayer component
The bcPlayer component is the main SDK node as it enables both Brightcove sources and external sources video playback in Roku channels. This node essentially extends Roku’s native Video node, allowing all its fields to be easily accessed for further customization options. It is possible to configure the appearance of some elements in the node as well as some behaviors and flows by customizing the node fields values.
An instance of this node can be created like so:
m.bcPlayer = createObject("roSGNode", "bcLib:bcPlayer")
Once an instance of the node is available, it’s possible to customize it by setting up its fields. All the fields default values are listed below.
m.bcPlayer = createObject("roSGNode", "bcLib:bcPlayer")
m.bcPlayer.observeField("on", "onEvent") ' read-only field
m.bcPlayer.observeField("adPlaying", "onAdPlaying") ' read-only field
m.bcPlayer.setFields({
streamPreference: ["hls", "dash", "mp4"],
drmPreference: ["widevine", "playready", "none"],
width: 1920, ' current UI width
height: 1080, ' current UI height
logLevel: 0,
credentials: invalid,
env: "production",
watermarkToken: "",
spinnerConfig: {},
closeOnBack: "hard",
closeOnFinished: "hard",
retryOnError: true,
retryOnBufferTimeout: false,
enableDialogs: true,
enableGsc: false,
bufferTimeout: 0,
dialogTheme: {
DialogBackgroundColor: "#00000000",
DialogSecondaryItemColor: "#00000000"
}
})
playback = m.bcPlayer.playback
playback.observeField("index", "onIndex") ' read-only field
playback.setFields({
loop: false,
autoPlayNext: false
})
analytics = m.bcPlayer.analytics
analytics.observeField("eventOut", "onAnalyticsEvent") ' read-only field
analytics.setFields({
accountId: ""
url: ""
applicationID: ""
env: ""
playerId: ""
playerName: ""
accountId: ""
user: ""
destination: ""
source: ""
})
ssai = m.bcPlayer.ssai
ssai.observeField("event", "onSSAIEvent") ' read-only field
ssai.setFields({
enabled: false
enableDiscontinuities: true
adMeasurements: {}
bcovToken: ""
macros: {}
})
csai = m.bcPlayer.csai
csai.observeField("event", "onCSAIEvent") ' read-only field
csai.setFields({
enabled: false
maxRequests: 5
adMeasurements: {}
adConstraints: {}
})
Fields
The bcPlayer node is configured through a set of fields. Since it extends the native Video node, all native fields are also accessible; these can be checked out in Roku documentation.
The following tags are used in this section to make the identification of the different types of fields easier.
<VALUE_TYPE>
Specifies the expected type of a field value or ASSOCIATIVE ARRAY key value (e.g., string, float, integer…).OPTIONAL
Specifies an optional field or ASSOCIATIVE ARRAY key. If an optional field isn’t specifically set, theDEFAULT
value is be used.REQUIRED
Specifies that a field or ASSOCIATIVE ARRAY key is required (write-only properties) or is always present (read-only properties). If a required field is not set, an error message will be presented in the built-in logger.DEFAULT
Specifies the default value of a field or ASSOCIATIVE ARRAY key.NATIVE
Identifies a native field. These fields are aliases or references of a native Roku node fields. Roku documentation should be consulted for a more detailed description of these fields.CONTROL
Identifies fields that can control the video playback in any way.
Credentials
ASSOCIATIVE ARRAY
OPTIONAL
Configures Brightcove API credentials. It should contain the account ID as well as the policy key. These are used to retrieve video metadata from the Brightcove Playback or EPA API.
If the credentials aren’t provided, the bcPlayer node will only be able to playback videos from external sources through the bcPlayer.loadCustom
function.
Possible Values:
An ASSOCIATIVE ARRAY containing the following keys:
account_id
STRING
REQUIRED
Specifies Brightcove API user account ID.
-
policy_key
STRING
OPTIONAL
Specifies the user policy key required to access the Playback API.
-
auth_token
STRING
OPTIONAL
Specifies the JSON Web Token required to:
- Provide Playback Restriction rules (Playback Rights) through Edge Playback Authorization (EPA).
- Specify License Keys Protection for HLSe content playback.
- Enable the Generic Stream Concurrency feature.
Code Snippet
m.bcPlayer = createObject("roSGNode", "bcLib:bcPlayer")
m.bcPlayer.credentials = {
account_id: "<brightcove_user_account_id>"
policy_key: "<brightcove_user_policy_key>"
auth_token: "<brightcove_user_auth_token>"
}
' or
m.bcPlayer.setFields({
' ...other fields here...
credentials: {
account_id: "<brightcove_user_account_id>"
policy_key: "<brightcove_user_policy_key>"
auth_token: "<brightcove_user_auth_token>"
}
})
watermarkToken
STRING
OPTIONAL
Configures the Forensic Watermarking token, which is required when playing watermarked encoded Brightcove sources.
Playing a watermarked video without the watermarkToken
field properly set will result in a playback error.
Please check Videocloud documentation for more information on Forensic Watermark.
Possible Values:
A string containing the Forensic Watermarking token.
""
DEFAULT
Code Snippet
m.bcPlayer = createObject("roSGNode", "bcLib:bcPlayer")
m.bcPlayer.watermarkToken = "<forensic_watermarking_token>"
' or
m.bcPlayer.setFields({
' ...other fields here...
watermarkToken: "<forensic_watermarking_token>"
})
streamPreference
ARRAY
OPTIONAL
Configures sources types/containers preferences ordered by the priority each type/container will have when filtering the available video sources.
This allows you to setup the bcPlayer so that only certain stream types/containers are used or ignored, and the order in those sources will be filtered.
Playing a video in which no sources are listed in the streamPreference
field will result in an error.
Find more information on how the sources are parsed and filtered in the Sources Selection section.
Possible Values:
An array containing any combination of the following values:
hls
dash
mp4
DEFAULT
["hls", "dash", "mp4"]
Code Snippet
m.bcPlayer = createObject("roSGNode", "bcLib:bcPlayer")
m.bcPlayer.streamPreference = ["dash"] ' will only playback DASH sources
' or
m.bcPlayer.setFields({
' ...other fields here...
streamPreference: ["dash", "mp4"] ' will play DASH sources. If no DASH source is availble, will play MP4 sources
})
drmPreference
ARRAY
OPTIONAL
Configures DRM encryption systems preferences ordered by the priority each DRM system will have when filtering the available video sources.
This allows developers to setup the bcPlayer so that only certain DRM encrypted sources are used or ignored and the order in which the sources will be filtered through.
Playing a video in which no DRM encrypted sources are listed in the drmPreference
field will result in an error. The none
value forces the selection of sources with no DRM encryption.
Find more information on how the sources are parsed and filtered in the Sources Selection section.
Possible Values:
An array containing any combination of the following values:
widevine
Supported on HLS and DASH sources only.playready
Supported on DASH sources only, ignored on HLS sources.none
DEFAULT
["widevine", "playready", "none"]
Code Snippet
m.bcPlayer = createObject("roSGNode", "bcLib:bcPlayer")
m.bcPlayer.streamPreference = ["none"] ' play sources with no DRM encryption only
' or
m.bcPlayer.setFields({
' ...other fields here...
streamPreference: ["playready", "widevine"] ' play a DASH source encrypted with Playready DRM and, if not available, play a Widevine encrypted source instead
})
logLevel
INTEGER
OPTIONAL
Configures the logging level on the bcPlayer node. Only the specified messages will be triggered.
If set to -1
no logging messages will be triggered. In a production environment it's recommended to set it to -1
to avoid the execution of the logging internal functions.
Possible Values:
-1
disable all the logging.0
DEFAULT
log error messages only.1
log error and warning messages.2
log error, warning and info messages.3
log error, warning, info and debug messages.4
log error, warning, info, debug and verbose messages.
Code Snippet
m.bcPlayer = createObject("roSGNode", "bcLib:bcPlayer")
m.bcPlayer.logLevel = 3
' or
m.bcPlayer.setFields({
' ...other fields here...
logLevel: 3
})
spinnerConfig
ASSOCIATIVE ARRAY
OPTIONAL
Configures the custom loading spinner appearance.
When using Roku’s native Video node UI/UX, this spinner is only visible during the execution of API requests, as the native Video node contains its non-customizable loading spinner, which is visible during buffering operations.
Possible Values:
An Asociantive Array with the following optional keys:
URL
STRING
OPTIONAL
Specifies the spinner image path
DEFAULT
Internal PNG image path which looks like so:
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 andfalse
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
and1
.DEFAULT
1
Code Snippet
m.bcPlayer = createObject("roSGNode", "bcLib:bcPlayer")
m.bcPlayer.spinnerConfig = {
url: "pkg:/my/spinner/image.png"
size: 200
color: "#d32228"
clockwise: false ' counterclockwise rotation
interval: 0.8 ' completes a 360 rotation in 800 miliseconds
opacity: 0.8 ' sets an opacity of 80%
}
' or
m.bcPlayer.setFields({
' ...other fields here...
spinnerConfig: {
url: "pkg:/my/spinner/image.png"
size: 200
color: "#d32228"
clockwise: false ' counterclockwise rotation
interval: 0.8 ' completes a 360 rotation in 800 miliseconds
opacity: 0.8 ' sets an opacity of 80%
}
})
loading
BOOLEAN
OPTIONAL
Controls the custom loading spinner visibility. This field is used by internal functions but it also allows the custom spinner to be controller externally if needed.
Keep in mind that
- The OOTB UI has its own loading spinner. This field is independent from the OOTB UI built in loading spinner.
- Internal bcPlayer functions will automatically toggle the loading field value depending on what operations are being executed.
The appearance of the loading spinner can be customized through the spinnerConfig field.
Possible Values:
false
DEFAULT
Hide the custom loading spinner.true
Show the custom loading spinner.
Code Snippet
m.bcPlayer = createObject("roSGNode", "bcLib:bcPlayer")
m.bcPlayer.loading = true
' or
m.bcPlayer.setFields({
' ...other fields here...
loading: true
})
retryOnError
BOOLEAN
OPTIONAL
Toggles the retry on error feature which, when enabled, allows bcPlayer to automatically retry video playback with a different video source if a playback error is triggered during the initial video buffering process.
If all the available video sources fail to play an error will be triggered.
The retry on error flow follows the sources type and DRM encryption preferences/priorities set in the bcPlayer.streamPreference
and bcPlayer.drmPreference
fields.
This flow is only relevant at the initial source loading, ie, a playback error triggered mid-playback will not trigger the retry on error flow.
This feature is not applicable to CSAI videos.
Possible Values:
false
Disables the retry on error flow.true
DEFAULT
Enables the retry on error flow.
Code Snippet
m.bcPlayer = createObject("roSGNode", "bcLib:bcPlayer")
m.bcPlayer.retryOnError = false
' or
m.bcPlayer.setFields({
' ...other fields here...
retryOnError: false
})
retryOnBufferTimeout
BOOLEAN
OPTIONAL
Configures the retry on buffer timeout feature which, when enabled, allows bcPlayer to automatically retry video playback with a different video source when a buffering timeout error occurs.
If the bcPlayer.bufferTimeout
configuration is disabled (ie, is set to 0
), this feature is ignored.
The bcPlayer.on.timeout
event data contains a retry
flag which indicates if bcPlayer is going to retry the playback with a different source.
Possible Values:
false
DEFAULT
Disables the retry on buffer timeout feature.true
Enables the retry on buffer timeout feature, ifbcPlayer.bufferTimeout
is enabled.
Code Snippet
m.bcPlayer = createObject("roSGNode", "bcLib:bcPlayer")
m.bcPlayer.on.observeField("timeout", "onTimeout")
m.bcPlayer.retryOnBufferTimeout = true
' or
m.bcPlayer.setFields({
' ...other fields here...
retryOnBufferTimeout: true
})
...
sub onTimeout(ev)
' ev.getData() -> {contentIndex: Integer, bufferingStatus: AssociativeArray, retry: Boolean}
end sub
closeOnBack
STRING
OPTIONAL
Configures the back key press action.
It’s set to hard
by default, which means that when the user presses the back key, it’ll completely terminate/kill the bcPlayer instance.
Setting it to soft
causes the bcPlayer to do a soft close, which means that the current playback session is stopped and terminated but the bcPlayer node instance is kept alive and ready to receive other commands.
This behavior can be disabled (by setting this field to off
), in which case developers could capture the back key press through the bcPlayer.on.keyEvent event
listener and handle it manually. This also means that the bcPlayer node will let the back key event bubble up, so the app should be prepared to capture and handle it in a onKeyEvent
function.
If an invalid value is set, it’ll automatically be reset back to hard
.
Possible Values:
off
Disables the close on back action.soft
Soft closes the bcPlayer when the user presses the back key.hard
DEFAULT
Hard closes the bcPlayer when the user presses the back key.
Code Snippet
m.bcPlayer = createObject("roSGNode", "bcLib:bcPlayer")
m.bcPlayer.closeOnBack = "off" ' disable the close on back action
' or
m.bcPlayer.setFields({
' ...other fields here...
closeOnBack: "off"
})
...
' somewhere in a bcPlayer parent node...
function onKeyEvent(key as string, press as boolean) as boolean
handled = false
if key = "back" then
closePlayer() ' developers should handle the back key press here since the closeOnBack action was disabled
handled = true
end if
return handled
end function
closeOnFinished
BOOLEAN
OPTIONAL
Configures the bcPlayer behavior at the end of video playback.
When enabled (i.e., set to soft
or hard
), the bcPlayer will automatically close once the video playback reaches the end. In a playlist, this behavior depends on the following playback configurations:
bcPlayer.playback.autoPlayNext
- if theautoPlayNext
flag is enabled, once a video reaches the end, it'll play the next video in the playlist, if available.bcPlayer.playback.loop
- if theloop
flag is enabled, once the last video in the playlist finishes, it'll loop the playlist and play the first video.
When disabled (i.e., set to off
), developers should handle the finished
event manually through the bcPlayer.on.finished
or the bcPlayer.csai
close
event.
If an invalid value is set, it'll automatically be reset back to hard
.
Keep in mind that the close action will trigger a bcPlayer.on.close event, where the close type (soft
or hard
) can be checked.
Possible Values:
off
: Disables the close on finish action.soft
: Soft closes the bcPlayer when video playback finishes (depending on whether it’s playing a playlist or not and on the autoPlayNext and loop configuration values).hard
DEFAULT
: Hard closes the bcPlayer when video playback finishes (depending on whether it’s playing a playlist or not and on theautoPlayNext
andloop
configuration values).
Code Snippet
m.bcPlayer = createObject("roSGNode", "bcLib:bcPlayer")
m.bcPlayer.closeOnFinished = "off"
' or
m.bcPlayer.setFields({
' ...other fields here...
closeOnFinished: "off"
})
enableDialogs
BOOLEAN
OPTIONAL
Configures bcPlayer to show error dialogs when an error occurs.
It’s enabled by default; you can disable it and capture the errors through the bcPlayer.on.error
event.
These dialogs appearance can be customized through the dialogTheme field.
Possible Values:
false
Disables error dialogs.true
DEFAULT
Enables error dialogs.
Code Snippet
m.bcPlayer = createObject("roSGNode", "bcLib:bcPlayer")
m.bcPlayer.enableDialogs = false
' or
m.bcPlayer.setFields({
' ...other fields here...
enableDialogs: false
})
enableGSC
BOOLEAN
OPTIONAL
Toggles Brightcove Generic Stream Concurrency (GSC) feature on and off in bcPlayer.
Generic Stream Concurrency allows developers to define the number of video streams that a specific user can watch concurrently. Limiting stream concurrency helps preventing content being stolen or illegally watched through the theft or inappropriate sharing of credentials. Learn more.
Possible Values:
false
DEFAULT
Disables the GSC feature.true
Enables the the GSC feature if a validbcPlayer.credentials.auth_token
is also provided.
Code Snippet
m.bcPlayer = createObject("roSGNode", "bcLib:bcPlayer")
m.bcPlayer.credentials = {
...
auth_token: ""
...
}
m.bcPlayer.enableGSC = true
' or
m.bcPlayer.setFields({
' ...other fields here...
credentials: {
...
auth_token: ""
...
}
enableGSC: true
})
dialogTheme
ASSOCIATIVE ARRAY
OPTIONAL
Configures error dialogs appearance when enableDialogs is enabled.
The expected properties are the same as the native StandardDialog palette
field properties, except for DialogItemColor
, DialogInputFieldColor
, DialogSecondaryTextColor
, and DialogKeyboardColor
properties, which do not apply.
Check below how the error dialogs look like in the default configuration.
Possible Values:
An ASSOCIATIVE ARRAY with the following optional keys:
DialogBackgroundColor
STRING
OPTIONAL
Specifies the blend color for dialog's background bitmap.
DEFAULT
"#00000000"
DialogTextColor
STRING
OPTIONAL
Specifies the title and content text color.
DEFAULT
Default Roku native color.
DialogFocusColor
STRING
OPTIONAL
Specifies the focused button and scrollbar thumb colors.
DEFAULT
Default Roku native color.
DialogFocusItemColor
STRING
OPTIONAL
Specifies the focused button text color.
DEFAULT
Default Roku native color.
DialogSecondaryItemColor
STRING
OPTIONAL
Specifies the title divider color.
DEFAULT
"#00000000"
DialogFootprintColor
STRING
OPTIONAL
Specifies the button focus footprint color as well as the unfocused scrollbar thumb and track color.
DEFAULT
Default Roku native color.
Code Snippet
m.bcPlayer = createObject("roSGNode", "bcLib:bcPlayer")
m.bcPlayer.dialogTheme = {
DialogBackgroundColor: "#00000000"
DialogTextColor: "#dbdbdb"
DialogFocusColor: "#d32228"
DialogFocusItemColor: "#ab2125"
DialogSecondaryItemColor: "#dbdbdb"
DialogFootprintColor: "#dbdbdb"
}
' or
m.bcPlayer.setFields({
' ...other fields here...
dialogTheme: {
DialogBackgroundColor: "#00000000"
DialogTextColor: "#dbdbdb"
DialogFocusColor: "#d32228"
DialogFocusItemColor: "#ab2125"
DialogSecondaryItemColor: "#dbdbdb"
DialogFootprintColor: "#dbdbdb"
}
})
bufferTimeout
INTEGER
OPTIONAL
Configures the buffering timeout period, in seconds. This configuration allows developers to setup a timer which is initiated once the initial video buffering begins and at the end of which a timeout error will be triggered if the video playback hasn’t yet initiated.
Setting it to 0
disables the buffering timeout timer.
When the video buffering times out, a bcPlayer.on.timeout
event is triggered. Additionally, if the bcPlayer.retryOnBufferTimeout
configuration flag is enabled, the bcPlayer will retry the playback with a different source, if available. Otherwise, a dialog window is shown (if bcPlayer.enableDialogs
is enabled).
Possible Values:
- A positive integer value (seconds).
DEFAULT
0
buffering timeout disabled.
Code Snippet
m.bcPlayer = createObject("roSGNode", "bcLib:bcPlayer")
m.bcPlayer.bufferTimeout = 20
' or
m.bcPlayer.setFields({
' ...other fields here...
bufferTimeout: 20
})
sdkVersion
STRING
READ-ONLY
Provides the Roku SDK version.
Possible Values:
- The version number in the following format:
<major-version>.<minor-version>.<build-version>
Code Snippet
m.bcPlayer = createObject("roSGNode", "bcLib:bcPlayer")
sdkVersion = m.bcPlayer.sdkVersion
adPlaying
BOOLEAN
READ-ONLY
Indicates if a SSAI or CSAI ad is currently playing.
Possible Values:
true
An ad is currently playing.false
No ad is currently playing.
Code Snippet
sub init()
m.bcPlayer = createObject("roSGNode", "bcLib:bcPlayer")
m.bcPlayer.observeField("adPlaying", "onAdPlaying")
end sub
...
sub onAdPlaying(ev)
? "is it playing ads? " ev.getData()
end sub
relativePosition
FLOAT
READ-ONLY
Specifies the relative playback position on SSAI enabled videos. The relative position is the video content playback position when all the ads are ignored.
When playing a video without SSAI, the relativePosition
value reflects the native Video.position
field.
Code Snippet
sub init()
m.bcPlayer = createObject("roSGNode", "bcLib:bcPlayer")
m.bcPlayer.observeField("relativePosition", "onRelativePosition")
end sub
...
sub onRelativePosition(ev)
? "Relative position: " ev.getData()
end sub
visibleOnScreen
BOOLEAN
READ-ONLY
Specifies if the bcPlayer node is at least 50% of its size visible on the screen based on its size, position and visible
and opacity
field.
Please be aware that this field does not have into account the app node tree list so, for example, it ignores situations where another component is positioned over the bcPlayer node and covers it partially or completely.
Possible Values:
true
The bcPlayer node is at least 50% visible on the screen.false
The bcPlayer node is completely hidden or less than 50% visible on the screen.
Code Snippet
sub init()
m.bcPlayer = createObject("roSGNode", "bcLib:bcPlayer")
m.bcPlayer.observeField("visibleOnScreen", "onVisibleOnScreen")
end sub
...
sub onVisibleOnScreen(ev)
? "Is bcPlayer visible on screen? " ev.getData()
end sub
playback
NODE
Allows for a deeper level of control over video playback and content management in the bcPlayer.
Fields
Field | Description |
---|---|
index |
Specifies the index of the video playing in a playlist. It's set to |
loop |
Specifies if video playback should automatically loop in a playlist when executing the
|
autoPlayNext |
Specifies if bcPlayer should automatically play the next video in a playlist when video playback finishes.
|
Functions
Name | Parameters | Description |
---|---|---|
load |
|
Loads new content into bcPlayer for playback. This function is used internally by the bcPlayer
If
Returns a |
preload |
|
Preloads a video for playback at a later time. It does not start video playback. Preloading a video means to process and initialize the SSAI and CSAI components as well as validate the video stream TTL, when applicable. As such, please keep in mind that this is an asynchronous process. This process is useful when there’s a need to get everything ready to start playing a specific video at a later time (through the The If there’s a video playback session currently ongoing when Triggers a Returns a |
play |
|
Preloads a video and initiates or resumes playback. The If
Just like Triggers a Returns a |
prebuffer |
|
Preloads a video and starts prebuffering it. The If index is lower than Prebuffering does not apply to CSAI videos. Triggers a Returns a |
pause |
- |
Pauses video playback. Applies to CSAI and non-CSAI videos. Returns a |
terminate |
- |
Stops video playback. Essentially, the Applies to CSAI and non-CSAI videos. Returns a |
playNext |
- |
Plays the next video in the playlist. Applies to playlists only. Essentially, this function executes the When the
Triggers a Returns a |
playPrevious |
- |
Plays the previous video in the playlist. Applies to playlists only. Essentially, this function executes the When the
Triggers a Returns a |
seek |
|
Seeks to the specified position. Essentially, the Applies to CSAI and non-CSAI videos. Returns a |
replay |
- |
Seeks back 10 seconds in the current playback session. Essentially, the Applies to CSAI and non-CSAI videos. Returns a |
clear |
|
Clears the current playback session. It essentially stops the current playback, clears the bcPlayer content and internal flags. The |
removeItem |
|
Removes the video specified by the Only applicable to playlists. [TBI] The
Returns a |
getContent |
- |
Retrieves the current bcPlayer content. If the current content is a playlist, it returns a ContentNode containing child ContentNodes representing the videos in the playlist. Returns a |
getItemCount |
- |
Returns the number of videos currently loaded into the bcPlayer. Returns Returns Returns a |
getItem |
|
Retrieves a single video ContentNode through its index specified by the If the content is not a playlist, If Returns Returns a |
getActiveItem |
- |
Retrieves the video that is currently playing, similar to calling Returns Returns a |
getFirstItem |
- |
Retrieves the first video in the playlist. Returns Returns a |
getLastItem |
- |
Retrieves the last video in the playlist. Returns Returns a |
getTrickplay |
- |
Retrieves the native UI TrickplayBar node. When CSAI video playback is ongoing, returns the RAFContentRenderer TrickplayBar node instead. Returns Returns a |
isActiveItem |
|
Checks if the provided node is currently active/playing. Returns a |
is |
|
Allows to check the state of the ongoing playback session. Returns a
|
Code snippet
m.bcPlayer = createObject("roSGNode", "bcLib:bcPlayer")
' setup the main bcPlayer configurations
m.bcPlayer.setFields({
credentials: {...}
...
})
' setup the playback configurations, if needed
m.bcPlayer.playback.setFields({
loop: true, ' enable the playlist loop behavior
autoPlayNext: true ' enable the autoPlayNext behavior
})
' -------------------------------------------------
' Use-case 1 - add a custom video ContentNode and start playback
' -------------------------------------------------
videoLoaded = m.bcPlayer.playback.callFunc("load", MyVideoContentNode)
if videoLoaded then
m.bcPlayer.playback.callFunc("play")
else
' handle the load process failure
end if
' -------------------------------------------------
' -------------------------------------------------
' Use-case 2 - add custom video metadata and start prebuffering it
' -------------------------------------------------
m.bcPlayer.on.observeField("load", "onLoad") ' since the loadCustom fucntion is asynchronous, we need to wait for the process to complete before handling its playback
m.bcPlayer.callFunc("loadCustom", {<my-video>}, {autoplay: -1}) ' load the custom video metadata and disable autoplay
...
sub onLoad(ev)
data = ev.getData()
if data.error <> invalid then
' handle the load error
return
end if
' the video content has been loaded successfully, initiate the prebuffer process
m.bcPlayer.playback.callFunc("prebuffer", 0)
end sub
' -------------------------------------------------
' -------------------------------------------------
' Use-case 3 - retrieve a Brightcove playlist and prebuffer the 3rd video in the playlist
' -------------------------------------------------
m.bcPlayer.on.observeField("load", "onLoad")
m.bcPlayer.on.observeField("error", "onError")
m.bcPlayer.callFunc("getPlaylist", "my-playlist-id", {autoplay: -1}) ' load the playlist and disable the autoplay behavior
...
sub onError(ev)
data = ev.getData()
if data.source = "getPlaylist" then
' handle an eventual getPlaylist error
end if
end sub
sub onLoad(ev)
data = ev.getData()
if data.error <> invalid then
' handle the load error
return
end if
' the playlist content has been loaded successfully, initiate the prebuffer process
m.bcPlayer.playback.callFunc("prebuffer", 2)
end sub
' -------------------------------------------------
' -------------------------------------------------
' Use-case 4 - update the active video title
' -------------------------------------------------
activeVideo = m.bcPlayer.playback.callFunc("getActiveItem")
if activeVideo <> invalid then
activeVideo.title = "A Brand New Fancy Title"
end if
' -------------------------------------------------
analytics
NODE
Configures Brightcove’s Data Collection API support. This node allows for some of the Analytics metrics to be customized thus allowing for some flexibility and account for different use cases.
It also provides a read-only field where all the triggered events data can be accessed for further processing or logging.
All the available fields are listed in the table below.
Field | Description |
---|---|
accountID | STRING OPTIONAL
|
url | STRING OPTIONAL
|
applicationID | STRING OPTIONAL
|
env | STRING OPTIONAL
|
playerID | STRING OPTIONAL
|
playerName | STRING OPTIONAL
|
user | STRING OPTIONAL
|
destination | STRING OPTIONAL
|
source | STRING OPTIONAL
|
eventOut | associative array READ-ONLY
|
Code Snippet
m.bcPlayer = createObject("roSGNode", "bcLib:bcPlayer")
m.bcPlayer.analytics.accountID = "my account ID" ' setting a different accountID
m.bcPlayer.analytics.user = "123456" ' setting the user identification
m.bcPlayer.analytics.observeField("eventOut", "onAnalyticsEvent") ' observing the eventOut field
...
sub onAnalyticsEvent(ev)
data = ev.getData()
eventName = data.event
? "Analytics " + eventName + " event data: " data
end sub
on
NODE
READ-ONLY
Allows access to all the bcPlayer events. Developers should setup event listeners to capture the events data through the observeField()
or observeFieldScoped()
functions. Check the table below for all the available events and the data they provide.
Event List
Event | Data | Description |
---|---|---|
sdkReady |
|
Indicates if the bcPlayer internal components have been completely initiated. If the |
load |
Provides an ASSOCIATIVE ARRAY object with the following properties:
|
Allows for a better tracking of the load and loadCustom progress. The |
loadItem |
Provides an AssociativeArray object with the following properties:
|
Triggers when a new video is loaded in the bcPlayer for playback. This event is triggered by the |
start |
Provides an ASSOCIATIVE ARRAY object with the following properties:
Reference to the native
Reference to the native
Reference to the native
Reference to the native
Reference to the native
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 |
The Keep in mind that if the user rewinds or seeks to a specific position after the video playback has finished, this event is triggered once again for the same video. |
playing |
Provides an AssociativeArray object with the following properties:
|
Reflects the |
pause |
Provides an AssociativeArray object with the following properties:
|
Reflects the |
resume | To be implemented | |
replay | To be implemented | |
previous |
Provides an ASSOCIATIVE ARRAY object with the following properties:
|
The play previous video action has been triggered. This event is only available when playing a playlist structure. |
next |
Provides an ASSOCIATIVE ARRAY object with the following properties:
|
The play next video action has been triggered. This event is only available when playing a playlist structure. |
finished |
Provides an ASSOCIATIVE ARRAY object with the following properties:
|
Triggered at the end of a video playback. The following situations will trigger a
|
playlistIndex |
|
Triggered when loading up a video for playback. Specifies the index of the video that was loaded. When playing a single video this event sends |
disconnect |
|
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 |
Provides an ASSOCIATIVE ARRAY object with the following keys:
|
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 |
Provides an ASSOCIATIVE ARRAY object with the following keys:
|
Reflects the |
duration | To be implemented | |
timedMetaData | To be implemented | |
timeout |
|
Triggered when video buffering times out. This event is only applicable if the |
dialogClose |
|
Triggered when an error dialog is closed by a user action, usually pressing the Dialog Close button. |
mute | To be implemented | |
size |
|
Triggered when the |
isHidden |
|
Triggered when the bcPlayer node visibility changes. This event is controlled by a Be aware that this event might not be 100% accurate in certain situations due to the way the Roku OS handles the native Video node, preventing the native |
close |
|
Triggered when bcPlayer close action is called. This action can be called by developers themselves through the The type property specifies what type of close action was requested, soft or hard.
Keep in mind that the hard close process is asynchronous. If, for example, there are any HTTP requests ongoing, it’ll wait for those requests to complete and only then end the close process. At that point, the |
closed |
|
Triggered when bcPlayer and it’s internal components were completely terminated by a hard close. At this point, the bcPlayer node reference cannot be used as it’s internal functions are no longer available. Typically, this is where all bcPlayer references and field observers in the app are removed / unobserved. |
logOutput |
Provides an ASSOCIATIVE ARRAY object with the following keys:
|
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 |
keyEvent |
Provides an ASSOCIATIVE ARRAY object with the following keys:
|
Triggered when the user presses and releases a remote control button and the button event is captured in the bcPlayer node. Keep in mind that some button events are captured by the native Video node, in which case bcPlayer won’t be able to capture it and make it available in this event. |
voiceCommand |
[TBI] |
Code Snippet
sub init()
m.bcPlayer = createObject("roSGNode", "bcLib:bcPlayer")
' setup an event listener specifically for the "finished" event
m.bcPlayer.on.observeField("finished", "onFinished")
' its also possible to handle all the events in a single event listener function
m.bcPlayer.on.observeField("finished", "onPlayerEvent")
m.bcPlayer.on.observeField("error", "onPlayerEvent")
end sub
' create the event listener function where the event data can be accessed
sub onFinished(ev)
data = ev.getData() ' data contains the "finished" event data
' handle the "finished" event here...
end sub
' create a universal event listener function where all the events can be handled
sub onPlayerEvent(ev)
' "data" contains the event data
data = ev.getData()
' "event" contains the event name ("finished" or "error" in this example)
event = ev.getField()
' handle the event here...
' typically there should be an if or switch structure to filter the events
end sub
ssai
NODE
Allows to configure SSAI support in the bcPlayer
.
Live video streams only support SSAI service provided by Brightcove.
When setting up SSAI in a Brightcove video, the bcPlayer
will automatically set the adsData
field in the video ContentNode node. This field stores all the SSAI details, including the parsed VAST/VMAP data and it’s required to initialize RAF. Currently Brightcove SSAI sources will automatically create the adsData
field, but it should also be possible to adapt it to work with custom metadata and other SSAI providers (VOD sources only), like so:
m.bcPlayer = createObject("roSGNode", "bcLib:bcPlayer")
' enable SSAI handling
m.bcPlayer.ssai.enabled = true
' setup the custom metadata you wish to load through the loadCustom function and add the adsData property
' this function should start video playback automatically
m.bcPlayer.callFunc("loadCustom", {
... ' add the custom metadata properties
Url: "https://my.ssai.video.url" ' make sure to set the video URL. This should be a stitched video, containing both the ads and the content
StreamFormat: "hls/dash" ' set the stream format
adsData: { ' adsData should be an AssociativeArray object
type: "ssai", ' specifies that this is a SSAI enabled video
adBreaks: < adBreaks-ad-structure> ' provide the Ad Structure array as requested by Roku. This information is usually parsed from a VAST/VMAP document
}
})
Through the bcPlayer.ssai.macros
field it’s possible to specify a set of macros that will get replaced in the ad tag (please check the bcPlayer.ssai.macros
field description in the table below for more details), but it’s also possible to add custom macros into the ad tag as well, by setting up the vmapMacros
field in the video ContentNode node. vmapMacros
should be an Associative Array object and all the key-value pairs provided will be added into the ad tag (please be aware that it doesn’t check if the macro is already present in the ad tag, if it is, it’ll add it anyway).
sub init()
m.bcPlayer = createObject("roSGNode", "bcLib:bcPlayer")
' enable SSAI handling
m.bcPlayer.ssai.enabled = true
' request the SSAI ready video metadata through PAPI and disable the autoload flag so that the metadata can be adjusted before loading it into bcPlayer
' if you already have the metadata, you can skip this step and move on to the onVideoResponse() logic where the vmapMacros property is added.
rNode = m.bcPlayer.callFunc("getVideo", SSAIVideoID, { autoload: false })
if rNode <> invalid then rNode.observeField("response", "onVideoResponse")
end sub
sub onVideoResponse(ev)
data = ev.getData()
if data.code <> 200 then
' handle the error
return
end if
metadata = data.body
' setup the vmapMacros property.
' List all the custom macros you wish to add into the ad tag
' Make sure that these macros are not repeated in the bcPlayer.ssai.macros field, otherwise the ad tag might end up with duplicated macros
metadata.vmapMacros = {
myCustomMacro: "hello-world"
}
' load the metadata into bcPlayer
m.bcPlayer.callFunc("load", metadata)
end sub
Fields
Field | Description |
---|---|
enabled |
Toggles SSAI support on and off. If set to false (the default value), SSAI will be disabled on all videos.
|
enableDiscontinuities |
Toggles discontinuities/multiperiods in Brightcove sources. More info here.
|
adMeasurements |
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.
|
bcovToken |
Specifies a Brightcove authentication JWT. This allows SSAI videos to use a different token than the one provided through the
|
macros |
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 For example, if the VMAP ad tag URL contains the following query parameter: Roku macros can also be used as a macro value. Using the same ad tag example, setting Be aware that the
|
event |
Read-only property that allows access to ad related events triggered by RAF through the Possible values: An Associative Array object with the following properties:
|
Code snippet
m.bcPlayer = createObject("roSGNode", "bcLib:bcPlayer")
m.bcPlayer.ssai.enabled = true ' enable SSAI
m.bcPlayer.ssai.adMeasurements = { childDirected: true } ' specify that child directed videos will play. Make sure to reset this property when playing non-child directed videos
m.bcPlayer.ssai.observeField("event", "onSSAIEvent")
...
sub onSSAIEvent(ev)
? "SSAI Event: " ev.getData()
end sub
csai
Allows to configure CSAI support in the bcPlayer
.
bcPlayer
employs Roku's Client-Side Ad Stitching (CSAS) solution for CSAI handling.
When playing videos with CSAS, RAF creates its own internal Video nodes to seamlessly stitch video content and ad content together. This means that the bcPlayer native Video fields won't be able to control video playback or get the usual playback events. Alternatively, while playing CSAS videos, the following options are available:
RAFContentRenderer
This node is created and handled by RAF and replaces
bcPlayer
as the playback controller. It contains most of the Video node fields so they can be observed and updated as required (such as the Videocontrol
,state
andposition
fields). This node is added as a child of bcPlayer and its reference can be obtained through thestart
CSAI event (available inbcPlayer.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
Theevent
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 |
Toggles CSAI support on and off. If set to false (the default value), CSAI will be disabled on all videos. Possible values:
|
maxRequests |
Specifies the maximum number of attempts the getAds() function is allowed to make. This property allows RAF's setAdPrefs() function parameter to be customized.
|
adMeasurements |
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:
|
adConstraints |
Specifies RAF’s setAdConstraints() function parameters. Possible values
|
event |
Read-only property that allows access to video content and ad related events triggered by RAF through the Possible values An Associative Array object with the following properties:
|
Code snippet
m.bcPlayer = createObject("roSGNode", "bcLib:bcPlayer")
m.bcPlayer.csai.enabled = true ' enable CSAI
m.bcPlayer.csai.adMeasurements = { childDirected: true } ' specify that child directed videos will play. Make sure to reset this property when playing non-child directed videos
m.bcPlayer.csai.observeField("event", "onCSAIEvent")
...
sub onCSAIEvent(ev)
? "CSAI Event: " ev.getData()
end sub
Functions
The bcPlayer node also provides some functions to interact with the Video content and playback.
Load
Loads Brightcove Playback API video or playlist metadata into the bcPlayer asynchronously. Usually the data entered in the load function comes from the bcAPI component available in the Brightcove SDK which retrieves videos data from the Playback API, but it’s also used internally by the getVideo, getVideos, getPlaylist and getRelated functions.
The load
function triggers a bcPlayer.on.load
event reporting on the success or failure of the load process.
Parameters:
data
DYNAMIC
REQUIRED
Brightcove videos data to load into the bcPlayer for playback. This data can represent a single video or multiple videos. The possible values are:A single video object
ASSOCIATIVE ARRAY
Video by ID/ReferenceExpected metadata object structure:
{ account_id: "<papi-video-account_id>" sources: [<papi-video-sources>], <...> },
Any other properties in this object (besides
account_id
andsources
) are automatically set as fields of thebcPlayer.content
ContentNode, taking into account the following custom specifications:If the
title
property isn't provided and aname
property is,title
is set toname
.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 aduration
property is,length
is set toduration / 1000
.length
is a native field of a ContentNode and it specifies the length of a video in seconds. Theduration
property should contain the length of the video in milliseconds, if provided.If the
SDPosterUrl
,HDPosterUrl
andFHDPosterUrl
properties aren’t provided and a poster property is, these three properties are set to theposter
property value.poster
should provide the video poster image URL.SDPosterUrl
,HDPosterUrl
andFHDPosterUrl
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 theduration
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 is0
or below:live
is set totrue
.If
duration
value is above0
:live
is set tofalse
.
If the video is considered a live stream (
live
=true
) and the playstart property isn't provided, playstart is set to2147483647
. This forces the player to start playback from the live stream position.
A playlist object
ASSOCIATIVE ARRAY
Playlist by ID/ReferenceExpected 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 thebcPlayer.content
field.
An array containing a set of videos
ARRAY
Related Videos or Video SearchExpected metadata object structure:
[ { account_id: "<papi-video-account_id>" sources: [<papi-video-sources>], <...< }, <...< ]
This metadata is loaded into a Video playlist ContentNode structure.
options
ASSOCIATIVE ARRAY
OPTIONAL
Additional options that allow some behavior to be customized. The following properties can be set in this object:
autoplay
INTEGER
OPTIONAL
Specifies the index of the video that should start playing when the load process ends (in case of a playlist). A value of-1
will prevent the video from auto playing when the load process ends. By default autoplay is set to0
.-
prebuffer
BOOLEAN
OPTIONAL
Specifies if it should start prebuffering the video stream indicated in the
autoplay
option.-
false
DEFAULT
if
autoplay
is set (ie, >= 0), video playback will start when the loading process finishes -
true
if
autoplay
is set (ie, >= 0), video prebuffering will be initiated when the loading process finishes
-
position
STRING
OPTIONAL
Specifies where the new data should be loaded if bcPlayer already has content. Ie, should the data replace the old content, should it be added to the end or start of the current content. Possible values:replace
DEFAULT
Replace previous contents with the new content. If
position
isn't specified,replace
is used by default. If the current content is a single video, the new content will always replace it.append
Add the new content at the end of the current content. Only applicable if the current content is a playlist.
prepend
Add the new content at the start of the current content. Only applicable if the current content is a playlist.
Return Value
BOOLEAN
Indicates if the load process was properly initiated.
Code snippet
sub init()
m.bcPlayer = createObject("roSGNode", "bcLib:bcPlayer")
' load video data returned by the Playback API
m.bcPlayer.callFunc("load", videoMetadata)
' OR
' Set some options to customize the playlist loading behavior
m.bcPlayer.callFunc("load", playlistMetadata, {
autoplay: 3 ' start playing the video in the index 3 of the playlist
position: "end" ' append the playlist to the current contents
})
' OR
' it's also possible to manually customize Playback API metadata before loading it into bcPlayer
' start by requesting a specific video metadata from the Playback API, specifying the "autoload" config property as false so it returns back a response node
rNode = m.bcPlayer.callFunc("getVideo", videoID, { autoload: false })
' make sure the response Node is available so it can be used to retrieve the response metadata
if rNode <> invalid then
' set up an observer function for the "response" field
rNode.observeField("response", "onVideoResponse")
end if
end sub
sub onVideoResponse(ev)
' ev.getData() returns the Playback API response properties
response = ev.getData()
' if the request failed for any reason, handle the error
if response.code <> 200 then
' handle the failed request here
return
end if
' the "body" property contains the Video metadata
videoMetadata = response.body
' if needed, "videoMetadata" can be customized here before feeding it into the "load" function (keep in mind some properties shouldn't be changed)
' load the customized video metadata into bcPlayer for playback
m.bcPlayer.callFunc("load", videoMetadata)
end sub
loadCustom
Asynchronously loads custom metadata (a video or set of videos) into the bcPlayer. This function should be used to load non-Brightcove videos metadata.
Developers should provide the required playback properties as specified by Roku in their documentation page.
The loadCustom
function triggers a bcPlayer.on.load
event reporting on the success or failure of the load process.
Parameters:
metadata
ASSOCIATIVE ARRAY
REQUIRED
The video or playlist metadata to load into the bcPlayer for playback. All data is loaded as is into a ContentNode. The possible values are:
A single video
ASSOCIATIVE ARRAY
If an Associative Array object is provided, a single ContentNode is created and all key-value pairs are set as its fields.
A set of videos
ARRAY
If an Array of Associative Arrays is provided, the ContentNode is structured as a playlist where the videos ContentNodes are added into the parent playlist ContentNode.
options
ASSOCIATIVE ARRAY
OPTIONAL
Additional options allow some behaviors to be customized. The following properties can be set in this object:
autoplay
INTEGER
OPTIONAL
Specifies the index of the video that should start playing when the load process ends (in case of a playlist).
0
DEFAULT
Plays the first video in the playlist or the loaded video if not a playlist.
-1
Disables auto playback. This might be useful to preload / prebuffer the video.
-
prebuffer
BOOLEAN
OPTIONAL
Specifies if it should start prebuffering the video stream indicated in the
autoplay
option.-
false
DEFAULT
if
autoplay
is set (ie, >= 0), video playback will start when the loading process finishes -
true
if
autoplay
is set (ie, >= 0), video prebuffering will be initiated when the loading process finishes
-
position
STRING
OPTIONAL
Specify the position the new metadata should be load into if bcPlayer already contains previous contents. The possible string values are:
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. If the current content is not a playlist, a new playlist is created and both the current and new content are added to the playlist.
prepend
Add the new content at the start of the current content. If the current content is not a playlist, a new playlist is created and both the current and new content are added to the playlist.
Return value
BOOLEAN
Indicates if the load process was properly initiated.
Code snippet
sub init()
m.bcPlayer = createObject("roSGNode", "bcLib:bcPlayer")
' load custom video metadata
m.bcPlayer.callFunc("loadCustom", {
Url: "https://my.video.url", ' make sure the required playback fields are set, like Url, Streams or StreamUrls
StreamFormat: "hls", ' specify the StreamFormat when using the Url field
PlayStart: 40, ' start playback at 40 seconds
myCustomField: "hello world" ' custom fields can also be set, all properties are added as is
})
end sub
getVideo
Retrieves a specific Brightcove video through Playback API, if configured to do so, loads its metadata into bcPlayer, and starts playback.
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
andposition
options.false
When
autoload
is disabled,getVideo
will only retrieve Brightcove video metadata. In this case,getVideo
immediately returns aNode
object which contains aresponse
field that can be used to setup an observer function to capture the request response data.
autoplay
INTEGER
OPTIONAL
[To be implemented] Specifies the index of the video that should start playing when the load process ends (in case of a playlist). A value of
-1
will prevent auto playback when the load process ends. By defaultautoplay
is set to0
. this property is passed along to the load function, which is responsible for the metadata load process. Ignored ifautoload
is disabled.position
STRING
OPTIONAL
Specify the position the new metadata should be load into if bcPlayer already contains previous contents. Internally. this property is passed along to the load function, which is responsible for the metadata load process. Ignored if
autoload
is disabled. The possible string values are:replace
DEFAULT
Replace previous contents with the new content. If
position
isn't specified,replace
is used by default.append
Add the new content at the end of the current content.
prepend
Add the new content at the start of the current content.
-
<custom-prop>
DYNAMIC
OPTIONAL
It’s also possible to specify custom properties to be passed along to the response object. These are especially useful when the
autoload
option is disabled. On the other hand, if theautoload
option is enabled, these properties are ignored.
Return Value
invalid
Returns
invalid
ifautoload
is enabled.Node
Returns a
Node
object ifautoload
is disabled. ThisNode
contains aresponse
field which can be used to setup an observer function where the request response can be captured.
Code Snippet
sub init()
' autoload enabled
m.bcPlayer.callFunc("getVideo", videoID, {
params: {ad_config_id: adConfigID},
autoplay: -1
})
' OR
' autoload disabled
responseNode = m.bcPlayer.callFunc("getVideo", videoID, {
params: {ad_config_id: adConfigID},
autoload: false,
myCustomOption: "hello world"
})
' make sure the response Node is available so it can be used to retrieve the response metadata
if responseNode <> invalid then
' set up an observer function for the "response" field
responseNode.observeField("response", "onVideoResponse")
end if
end sub
sub onVideoResponse(ev)
' ev.getData() returns the Playback API response properties
response = ev.getData()
' if the request failed for any reason, handle the error
if response.code <> 200 then
' handle the failed request here
return
end if
options = response.options
' retrieve the custom properties from the response object
myCustomOption = options.myCustomOption
' the "body" property contains the Video metadata
videoMetadata = response.body
' if needed, "videoMetadata" can be customized here before feeding it into the "load" function (keep in mind some properties shouldn't be changed)
' load the customized video metadata into bcPlayer for playback
m.bcPlayer.callFunc("load", videoMetadata, {
autoplay: -1
})
end sub
getVideos
Retrieves a set of Brightcove videos through Playback API and, if configured to do so, loads its metadata into bcPlayer and starts playback.
This option is commonly used to programmatically search for Brightcove videos.
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
andposition
options.false
When
autoload
is disabled,getVideos
immediately returns aNode
object which contains aresponse
field that can be used to setup an observer function to capture the request response details.
autoplay
INTEGER
OPTIONAL
Specifies the index of the video that should start playing when the load process ends (in case of a playlist). A value of
-1
will prevent auto playback when the load process ends. By defaultautoplay
is set to0
. this property is passed along to the load function, which is responsible for the metadata load process. Ignored ifautoload
is disabled.position
STRING
OPTIONAL
Specify the position the new metadata should be load into if bcPlayer already contains previous contents. Internally. this property is passed along to the load function, which is responsible for the metadata load process. Ignored if
autoload
is disabled. The possible string values are:replace
DEFAULT
Replace previous contents with the new content. If
position
isn't specified,replace
is used by default.append
Add the new content at the end of the current content.
prepend
Add the new content at the start of the current content.
-
<custom-prop>
DYNAMIC
OPTIONAL
It’s also possible to specify custom properties to be passed along to the response object. These are especially useful when the
autoload
option is disabled. On the other hand, if theautoload
option is enabled, these properties are ignored.
Return Value
invalid
Returns
invalid
ifautoload
is enabled.Node
Returns a
Node
object ifautoload
is disabled. ThisNode
contains a response field which can be used to setup an observer function where the request response can be captured.
Code Snippet
sub init()
' autoload enabled
m.bcPlayer.callFunc("getVideos", "name:wildlife", {
params: {limit: 10, offset: 20},
autoplay: -1
})
' OR
' autoload disabled
responseNode = m.bcPlayer.callFunc("getVideos", "name:wildlife", {
params: {limit: 10, offset: 20},
autoload: false,
myCustomOption: "hello world"
})
' make sure the response Node is available so it can be used to retrieve the response metadata
if responseNode <> invalid then
' set up an observer function for the "response" field
responseNode.observeField("response", "onVideosResponse")
end if
end sub
sub onVideosResponse(ev)
' ev.getData() returns the Playback API response properties
response = ev.getData()
' if the request failed for any reason, handle the error
if response.code <> 200 then
' handle the failed request here
return
end if
options = response.options
' retrieve the custom properties from the response object
myCustomOption = options.myCustomOption
' the "body" property contains videos metadata
videosMetadata = response.body
' if needed, "videosMetadata" can be customized here before feeding it into the "load" function (keep in mind some properties shouldn't be changed)
' load the customized videos metadata into bcPlayer for playback
m.bcPlayer.callFunc("load", videosMetadata, {
autoplay: -1
})
end sub
getPlaylist
Retrieves a Brightcove playlist through Playback API and, if configured to do so, loads its metadata into bcPlayer and starts playback.
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
andposition
options.false
When
autoload
is disabled,getPlaylist
only retrieve Brightcove videos metadata. In this case,getPlaylist
returns aNode
object which contains aresponse
field that can be used to setup an observer function to capture the request response details.
autoplay
INTEGER
OPTIONAL
Specifies the index of the video that should start playing when the load process ends. A value of
-1
will prevent auto playback when the load process ends. By defaultautoplay
is set to0
. this property is passed along to the load function, which is responsible for the metadata load process. Ignored ifautoload
is disabled.position
STRING
OPTIONAL
Specify the position the new metadata should be load into if bcPlayer already contains previous contents. Internally. this property is passed along to the load function, which is responsible for the metadata load process. Ignored if
autoload
is disabled. The possible string values are:replace
DEFAULT
Replace previous contents with the new content. If
position
isn't specified,replace
is used by default.append
Add the new content at the end of the current content.
prepend
Add the new content at the start of the current content.
<custom-prop>
DYNAMIC
OPTIONAL
It’s also possible to specify custom properties to be passed along to the response object. These are especially useful when the
autoload
option is disabled. On the other hand, if theautoload
option is enabled, these properties are ignored.
Return Value
invalid
Returns
invalid
ifautoload
is enabled.Node
Returns a
Node
object ifautoload
is disabled. ThisNode
contains a response field which can be used to setup an observer function where the request response can be captured.
Code Snippet
sub init()
' autoload enabled
m.bcPlayer.callFunc("getPlaylist", playlistID, {
params: {limit: 10, offset: 20},
autoplay: 3
})
' OR
' autoload disabled
responseNode = m.bcPlayer.callFunc("getPlaylist", playlistID, {
params: {limit: 10, offset: 20},
autoload: false,
myCustomOption: "hello world"
})
' make sure the response Node is available so it can be used to retrieve the response metadata
if responseNode <> invalid then
' set up an observer function for the "response" field
responseNode.observeField("response", "onPlaylistResponse")
end if
end sub
sub onPlaylistResponse(ev)
' ev.getData() returns the Playback API response properties
response = ev.getData()
' if the request failed for any reason, handle the error
if response.code <> 200 then
' handle the failed request here
return
end if
options = response.options
' retrieve the custom properties from the response object
myCustomOption = options.myCustomOption
' the "body" property contains the playlist metadata
playlistMetadata = response.body
' if needed, "playlistMetadata" can be customized here before feeding it into the "load" function (keep in mind some properties shouldn't be changed)
' load the customized playlist metadata into bcPlayer for playback
m.bcPlayer.callFunc("load", playlistMetadata, {
autoplay: 3 ' TBI feature
})
end sub
getRelated
ASSOCIATIVE ARRAY
Retrieves a set of Brightcove videos that are related to the specified video id
through Playback API.
Using the name and short description of the specified video id
, the Playback API searches for videos with any partial matches in the following fields: name
, short_description
, long_description
, tags
.
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
andposition
options [To be implemented].false
When
autoload
is disabled,getRelated
only retrieve Brightcove videos metadata. In this case,getRelated
returns aNode
object which contains aresponse
field that can be used to setup an observer function to capture the request response details.
autoplay
INTEGER
OPTIONAL
Specifies the index of the video that should start playing when the load process ends. A value of
-1
will prevent auto playback when the load process ends. By defaultautoplay
is set to0
. this property is passed along to the load function, which is responsible for the metadata load process. Ignored ifautoload
is disabled.position
STRING
OPTIONAL
Specify the position the new metadata should be load into if bcPlayer already contains previous contents. Internally. this property is passed along to the load function, which is responsible for the metadata load process. Ignored if
autoload
is disabled. The possible string values are:replace
DEFAULT
Replace previous contents with the new content. If
position
isn't specified,replace
is used by default.append
Add the new content at the end of the current content.
prepend
Add the new content at the start of the current content.
<custom-prop>
DYNAMIC
OPTIONAL
It’s also possible to specify custom properties to be passed along to the response object. These are especially useful when the
autoload
option is disabled. On the other hand, if theautoload
option is enabled, these properties are ignored.
Return Value
invalid
Returns
invalid
ifautoload
is enabled.Node
Returns a
Node
object ifautoload
is disabled. ThisNode
contains aresponse
field which can be used to setup an observer function where the request response can be captured.
Code Snippet
sub init()
' autoload enabled
m.bcPlayer.callFunc("getRelated", videoID, {
params: {limit: 10, offset: 20},
autoplay: 3
})
' OR
' autoload disabled
responseNode = m.bcPlayer.callFunc("getRelated", videoID, {
params: {limit: 10, offset: 20},
autoload: false,
myCustomOption: "hello world"
})
' make sure the response Node is available so it can be used to retrieve the response metadata
if responseNode <> invalid then
' set up an observer function for the "response" field
responseNode.observeField("response", "onRelatedResponse")
end if
end sub
sub onRelatedResponse(ev)
' ev.getData() returns the Playback API response properties
response = ev.getData()
' if the request failed for any reason, handle the error
if response.code <> 200 then
' handle the failed request here
return
end if
options = response.options
' retrieve the custom properties from the response object
myCustomOption = options.myCustomOption
' the "body" property contains the related videos metadata
relatedMetadata = response.body
' if needed, "relatedMetadata" can be customized here before feeding it into the "load" function (keep in mind some properties shouldn't be changed)
' load the customized related videos metadata into bcPlayer for playback
m.bcPlayer.callFunc("load", relatedMetadata, {
autoplay: 3 ' To be implemented feature
})
end sub
close
Initiates the close action, which depending on the parameter provided, terminates/kills bcPlayer completely (hard close) or just stops and clears the current playback session (soft close). By default, if no parameter is provided, it executes a hard close.
The hard close is an asynchronous process, at the end of which it triggers a bcPlayer.on.closed
event to confirm that the close process is complete.
Once the close action is called, the bcPlayer.on.close
event is also triggered specifying the type of close action that was called (soft or hard).
The close process can also be triggered internally by the closeOnBack
and closeOnFinished
configurations, if configured to do so.
Be aware that a hard close completely kills the bcPlayer node instance and it’s not possible to access/use its functions afterwards.
Parameters
-
kill
BOOLEAN
OPTIONAL
-
true
DEFAULT
Triggers a hard close action, which terminates/kills the bcPlayer instance completely.
-
false
Triggers a soft close action, which stops the current playback session and clears the content. The bcPlayer node remains on standby waiting for other commands.
-
Return value
VOID
Code Snippet
sub init()
...
' listen for the "close" event, in case some action needs to be taken when closing bcPlayer
m.bcPlayer.on.observeField("close", "onClose")
' listen for the "closed" event, which is only triggered by a hard close
m.bcPlayer.on.observeField("closed", "onClosed")
' trigger the close action
m.bcPlayer.callFunc("close")
end sub
sub onClose(ev)
data = ev.getData() ' data => {type: "soft" / "hard"}
' bcPlayer close action was triggered,
' data.type specifies what type of close was requested
end sub
sub onClosed()
' bcPlayer was completely terminated by a hard close action.
' If there's still any bcPlayer reference in the app or fields observers, these
' should be removed / unobserved at this point
m.bcPlayer.on.unobserveField("close")
m.bcPlayer.on.unobserveField("closed")
m.bcPlayer = invalid
end sub
Video Sources Selection
When playing a Videocloud video or playlist in the bcPlayer node through the load, playVideo, playVideos, playPlaylist and playRelated functions, the video/videos metadata is parsed and the video sources are filtered through the following stages:
Step | Description |
---|---|
1 | Sources go through an initial filtering process where one source is selected per stream type (HLS and DASH), DRM system (Widevine, Playready and no DRM) and protocol (HTTP/HTTPS). Sources are added to the mapping object according to the following prioritization rules:
Sources mapping object
|
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:
|
3 | Once a Videocloud video source has been selected, it’s then converted into the required Video ContentNode fields. At this stage the selected source URL is also verified for any supported query parameters we might need to set, such as the Forensic Watermarking token or JWT. |
bcAPI component
This component allows for independent access to Brightcove’s Playback API without having to initialize a bcPlayer component. bcAPI
extends a Task
node, and as such, is controlled through the control
control field.
bcAPI is able to handle multiple requests at the same time (configurable through the maxRequests
field) and it also provides an interface that enables any HTTP request to be triggered.
It’s up to developers to choose the best workflow for this node, but we recommend one instance to be created somewhere during the app launch process and then referenced throughout the app.
An instance of this node can be created like so:
m.bcAPI = createObject("roSGNode", "bcLib:bcAPI")
Once an instance of the node is available, it’s possible to customize it by setting up its fields. All the fields default values are listed below.
sub init()
' create a bcAPI node reference
m.bcAPI = createObject("roSGNode", "bcLib:bcAPI")
' observe the response field to access the API responses
m.bcAPI.observeField("ready", "onAPIready")
' configure bcAPI node fields
m.bcAPI.setFields({
credentials: invalid,
logger: invalid, ' optional: provide a bcLib:Logger node instance
maxRequests: 5,
control: "run" ' initialize bcAPI task imediately
})
m.bcAPI.getVideo = {id: "<my-video-id>"}
end sub
sub onAPIResponse(ev)
response = ev.getData()
end sub
Config Fields
Credentials
ASSOCIATIVE ARRAY
OPTIONAL
Configures Brightcove API credentials. It should contain the Account ID as well as the Policy Key or Authentication token. These are used to retrieve videos metadata from Brightcove’s Playback API.
If valid Brightcove credentials aren’t provided in this field, the bcAPI node will only be able to trigger HTTP requests through the request
function.
Possible Values:
An ASSOCIATIVE ARRAY containing the following keys:
account_id
STRING
REQUIRED
Specifies Brightcove user account ID.
-
policy_key
STRING
OPTIONAL
Specifies the user policy key required to access the Playback API.
-
auth_token
STRING
OPTIONAL
Specifies the JSON Web Token required to:
- Provide Playback Restriction rules (Playback Rights) through Edge Playback Authorization (EPA).
- To specify License Keys Protection for HLSe content playback.
Code Snippet
m.bcAPI.credentials = {account_id: "my-account-id", policy_key: "my-policy-key"}
' OR
m.bcAPI.setFields({
' ...
credentials: {account_id: "my-account-id", policy_key: "my-policy-key"},
' ...
})
maxRequests
INTEGER
OPTIONAL
Specifies the number of simultaneous requests that can be executed at the same time. If the number of requests surpass the value defined in maxRequests
, these requests are put on hold until the ongoing requests are completed. It follows a FIFO approach.
Possible Values:
5
DEFAULT
A positive integer value.
Code Sinippet
m.bcAPI.maxRequests = 3
' OR
m.bcAPI.setFields({
' ...
maxRequests: 3,
' ...
})
logger
Specifies the Logger node reference to be used for logging purposes.
Possible Values:
bcLib:Logger
reference.
Code Snippet
logger = createObject("roSGNode", "bcLib:Logger")
m.bcAPI.logger = logger
' OR
m.bcAPI.setFields({
' ...
logger: logger,
' ...
})
Action Fields
Since bcAPI
is a Task node, it's not feasible to interact with it through Functions so all the actions requested to this node are initiated through its fields. Check below the list of all possible actions this node provides.
request
Allows for the execution of any HTTP request. Brightcove credentials are not required.
Request responses can be obtained through one of two ways:
- By providing a response Node with a
response
AssociativeArray field, bcAPI will set the request response data into that field, which will then be available on any observing function. - By observing the response bcAPI output field if no response Node is provided.
This structure is exactly the same whether it’s set through the response Node or the bcAPI response
field.
Possible Values:
An AssociativeArray object containing the following properties:
data
ASSOCIATIVE ARRAY
REQUIRED
Contains the request data. The following properties are possible:
id
STRING
OPTIONAL
A custom request ID so it can then be identified when processing the response data. Specially useful when parsing responses from the response field instead of a response Node. If not provided, defaults to “request“.
request
DEFAULT
url
STRING
REQUIRED
The request URL.
headers
ASSOCIATIVE ARRAY
OPTIONAL
Request headers in a key-value Associative Array object. Roku’s
x-roku-reserved-dev-id
header is automatically set.method
STRING
OPTIONAL
Request method. The possible values are:
get
DEFAULT
post
delete
put
patch
body
STRING / ASSOCIATIVE ARRAY
OPTIONAL
Request body. If an Associative Array object is provided, it’s automatically parsed into a string before sending the request.
gzip
BOOLEAN
OPTIONAL
Enables the GZIP encoding through EnableEncodings. Disabled by default.
cookies
BOOLEAN
OPTIONAL
Enables cookies through EnableCookies. Disabled by default.
http2
BOOLEAN
OPTIONAL
Enables HTTP/2 support through SetHttpVersion. Disabled by default.
forceFormat
STRING
OPTIONAL
Specifies how the response body should be formatted. The possible values are:
auto
DEFAULT
Checks for the
content-type
response header and if it’s set toapplication/json
the response body is parsed into an Associative Array object. If not, the response body is set as a string.json
Forces the parsing of the response body into an Associative Array object. This may result in unwanted results if the response content is not a valid JSON string.
string
The request response body is set as a string.
options
Associative Array
OPTIONAL
Custom parameters that will be passed along to the response object as is.
node
NODE
OPTIONAL
Response Node with a
response
field where the request response will be set into. If not provided (default), the response data can be accessed through bcAPI response output field.
Code Snippet
sub init()
' initialize bcAPI node reference
m.bcAPI = createObject("roSGNode", "bcLib:bcAPI")
' setup bcAPI config fields and initiate the bcAPI Task
m.bcAPI.setFields({
' ...
control: "run"
})
' observe bcAPI "response" field to retrieve the response data
' keep in mind that if a response Node isn't provided, all request responses
' are set into the bcAPI response field
m.bcAPI.observeField("response", "onResponse")
' setup the request configuration and initiate it
m.bcAPI.request = {
data: {
' it's important that a custom ID is set here so that this request response
' can be easily identified in the response observing function
id: "myCustomRequest"
url: "https://my.request.url"
method: "post",
body: {some: "body-content"}
options: {extradata: "some data I may need in the response"}
}
}
' OR
' create a response Node that will be used to "catch" the request response data
responseNode = createObject("roSGNode", "Node")
' create an Associative Array "response" field in this Node
responseNode.addFields({ response: {} })
' observe the just added "response" field to capture the response data
responseNode.observeField("response", "onResponse")
' setup the request configuration, provide the response Node and initiate the request
m.bcAPI.request = {
node: responseNode,
data: {
' the id could be omitted when parsing the response in a specific function
id: "myOtherCustomRequest"
url: "https://my.other.request.url"
method: "post",
body: {someOther: "body-content"}
options: {extradata: "some other data I may need in the response"}
}
}
end sub
sub onResponse(ev)
response = ev.getData()
' the data provided in the "options" property is available in the response object as is
options = response.options
? options.extradata
if response.id = "myCustomRequest" then
' handle "myCustomRequest" response here
else if response.id = "myOtherCustomRequest" then
' handle "myOtherCustomRequest" response here
end if
end sub
getVideo
ASSOCIATIVE ARRAY
Retrieves a specific Brightcove video metadata through the Playback API. The response object is handled as described in the request field.
In this case, the response id
property is always “getVideo“.
Possible Values:
An AssociativeArray object containing the following properties:
id
STRING
REQUIRED
Brightcove video ID or video reference ID to be retrieved. To get a video using a video reference ID,
id
must be formatted like so:ref:<reference_id>
.params
ASSOCIATIVE ARRAY
OPTIONAL
Playback API request parameters as specified in the Playback API Reference. The following properties are supported:
ad_config_id
STRING
OPTIONAL
Include server-side ad insertion.
config_id
STRING
OPTIONAL
Include and set equal to the delivery rules id in order to have the delivery rules applied.
node
NODE
OPTIONAL
Response Node with a
response
field where the request response will be set into. If not provided (default), the response data can be accessed through bcAPI response output field.
Code Snippet
sub init()
' initialize bcAPI node reference
m.bcAPI = createObject("roSGNode", "bcLib:bcAPI")
' setup bcAPI config fields and initiate the bcAPI Task
m.bcAPI.setFields({
' ...
control: "run"
})
' observe bcAPI "response" field to retrieve the response data
' keep in mind that if a response Node isn't provided, all request responses are
' set into the bcAPI response field
m.bcAPI.observeField("response", "onResponse")
' setup the getVideo configuration and initiate it
m.bcAPI.getVideo = {
id: "<brightcove-video-id>",
params: {
ad_config_id: "my-ad-config-id"
}
}
' OR
' create a response Node that will be used to "catch" the getVideo response data
responseNode = createObject("roSGNode", "Node")
' create an Associative Array "response" field in this Node
responseNode.addFields({ response: {} })
' observe the just added "response" field to capture the response data
responseNode.observeField("response", "onResponse")
' setup the getVideo configuration, provide the response Node and initiate the API request
m.bcAPI.getVideo = {
node: responseNode,
id: "<brightcove-video-id>",
params: {
ad_config_id: "my-ad-config-id"
}
}
end sub
sub onResponse(ev)
response = ev.getData()
' handle the "getVideo" request response here
' response.id is "getVideo"
end sub
getVideos
ASSOCIATIVE ARRAY
Retrieves a set of Brightcove videos metadata through the Playback API. This option is commonly used to programmatically search for Brightcove videos.
The response object is handled as described in the request field. In this case, the response id property is always “getVideos“.
Possible Values:
An Associative Array object containing the following properties:
query
STRING
REQUIRED
Search query used to retrieved a set of Brightcove videos. More details see CMS/Playback API
params
ASSOCIATIVE ARRAY
OPTIONAL
Playback API request parameters as specified in the Playback API Reference. The following properties are supported:
limit
INTEGER
OPTIONAL
The number of videos to return.
offset
INTEGER
OPTIONAL
The number of videos to skip - used to page multiple sets of videos.
sort
STRING
OPTIONAL
Field to sort results by. Check the Playback API Reference for all the possible values.
ad_config_id
STRING
OPTIONAL
Include server-side ad insertion.
config_id
STRING
OPTIONAL
Include and set equal to the delivery rules id in order to have the delivery rules applied.
node
NODE
OPTIONAL
Response Node with a
response
field where the request response will be set into. If not provided (default), the response data can be accessed through bcAPI response output field.
Code Snippet
sub init()
' initialize bcAPI node reference
m.bcAPI = createObject("roSGNode", "bcLib:bcAPI")
' setup bcAPI config fields and initiate the bcAPI Task
m.bcAPI.setFields({
' ...
control: "run"
})
' observe bcAPI "response" field to retrieve the response data
' keep in mind that if a response Node isn't provided, all request responses are
' set into the bcAPI response field
m.bcAPI.observeField("response", "onResponse")
' setup the getVideos configuration and initiate it
m.bcAPI.getVideos = {
query: "",
params: {
limit: 10,
offset: 20,
ad_config_id: "my-ad-config-id"
}
}
' OR
' create a response Node that will be used to "catch" the getVideos response data
responseNode = createObject("roSGNode", "Node")
' create an Associative Array "response" field in this Node
responseNode.addFields({ response: {} })
' observe the just added "response" field to capture the response data
responseNode.observeField("response", "onResponse")
' setup the getVideos configuration, provide the response Node and initiate the API request
m.bcAPI.getVideos = {
node: responseNode,
query: "<videos-search-query>",
params: {
limit: 10,
offset: 20,
ad_config_id: "my-ad-config-id"
}
}
end sub
sub onResponse(ev)
response = ev.getData()
' handle the "getVideos" request response here
' response.id is "getVideos"
end sub
getRelated
ASSOCIATIVE ARRAY
Retrieves a set of Brightcove videos that are related to the specified video id
through Playback API.
Using the name and short description of the specified video id
, the Playback API searches for videos with any partial matches in the following fields: name
, short_description
, long_description
, tags
.
The response object is handled as described in the request field. In this case, the response id
property is always “getRelated“.
Possible Values:
An AssociativeArray object containing the following properties:
id
STRING
REQUIRED
Brightcove video ID or reference ID to retrieve the related videos from. To get the related videos of a video using the video reference ID,
id
must be formatted like so:ref:<reference_id>
.params
ASSOCIATIVE ARRAY
OPTIONAL
Playback API request parameters as specified in the Playback API Reference. The following properties are supported:
limit
INTEGER
OPTIONAL
The number of videos to return.
offset
INTEGER
OPTIONAL
The number of videos to skip - used to page multiple sets of videos.
ad_config_id
STRING
OPTIONAL
Include server-side ad insertion.
config_id
STRING
OPTIONAL
Include and set equal to the delivery rules id in order to have the delivery rules applied.
node
NODE
OPTIONAL
Response Node with a
response
field where the request response will be set into. If not provided (default), the response data can be accessed through bcAPI response output field.
Code Snippet
sub init()
' initialize bcAPI node reference
m.bcAPI = createObject("roSGNode", "bcLib:bcAPI")
' setup bcAPI config fields and initiate the bcAPI Task
m.bcAPI.setFields({
' ...
control: "run"
})
' observe bcAPI "response" field to retrieve the response data
' keep in mind that if a response Node isn't provided, all request responses are
' set into the bcAPI response field
m.bcAPI.observeField("response", "onResponse")
' setup the getVideos configuration and initiate it
m.bcAPI.getRelated = {
id: "<video-id>",
params: {
limit: 10,
offset: 20,
ad_config_id: "my-ad-config-id"
}
}
' OR
' create a response Node that will be used to "catch" the getRelated response data
responseNode = createObject("roSGNode", "Node")
' create an Associative Array "response" field in this Node
responseNode.addFields({ response: {} })
' observe the just added "response" field to capture the response data
responseNode.observeField("response", "onResponse")
' setup the getRelated configuration, provide the response Node and initiate the API request
m.bcAPI.getRelated = {
node: responseNode,
id: "<video-id>",
params: {
limit: 10,
offset: 20,
ad_config_id: "my-ad-config-id"
}
}
end sub
sub onResponse(ev)
response = ev.getData()
' handle the "getRelated" request response here
' response.id is "getRelated"
end sub
getPlaylist
ASSOCIATIVE ARRAY
Retrieves a Brightcove playlist metadata through Playback API.
The response object is handled as described in the request field. In this case, the response id property is always “getPlaylist“.
Possible Values:
An AssociativeArray object containing the following properties:
id
STRING
REQUIRED
Brightcove playlist ID or reference ID to be retrieved. To get a playlist using a playlist reference ID,
id
must be formatted like so:ref:<reference_id>
.params
ASSOCIATIVE ARRAY
OPTIONAL
Playback API request parameters as specified in the Playback API Reference. The following properties are supported:
limit
INTEGER
OPTIONAL
The number of videos to return.
offset
INTEGER
OPTIONAL
The number of videos to skip - used to page multiple sets of videos.
ad_config_id
STRING
OPTIONAL
Include server-side ad insertion.
config_id
STRING
OPTIONAL
Include and set equal to the delivery rules id in order to have the delivery rules applied.
Code Snippet
sub init()
' initialize bcAPI node reference
m.bcAPI = createObject("roSGNode", "bcLib:bcAPI")
' setup bcAPI config fields and initiate the bcAPI Task
m.bcAPI.setFields({
' ...
control: "run"
})
' observe bcAPI "response" field to retrieve the response data
' keep in mind that if a response Node isn't provided, all request responses are
' set into the bcAPI response field
m.bcAPI.observeField("response", "onResponse")
' setup the getPlaylist configuration and initiate it
m.bcAPI.getPlaylist = {
id: "<playlist-id>",
params: {
limit: 10,
offset: 20,
ad_config_id: "my-ad-config-id"
}
}
' OR
' create a response Node that will be used to "catch" the getPlaylist response data
responseNode = createObject("roSGNode", "Node")
' create an Associative Array "response" field in this Node
responseNode.addFields({ response: {} })
' observe the just added "response" field to capture the response data
responseNode.observeField("response", "onResponse")
' setup the getPlaylist configuration, provide the response Node and initiate the API request
m.bcAPI.getPlaylist = {
node: responseNode,
id: "<playlist-id>",
params: {
limit: 10,
offset: 20,
ad_config_id: "my-ad-config-id"
}
}
end sub
sub onResponse(ev)
response = ev.getData()
' handle the "getPlaylist" request response here
' response.id is "getPlaylist"
end sub
abort
BOOLEAN
Aborts currently ongoing requests.
If a response Node was provided in the request configuration, its response
field is set to the following value: {aborted: true}
. This allows the response handler to be notified that the request was aborted.
Possible Values:
false
no action.true
aborts currently ongoing requests.
Code Snippet
' ...
' all requests that had a response Node provided will get notified once the request is aborted
m.bcAPI.abort = true
' ...
kill
BOOLEAN
Aborts all ongoing requests and completely terminates the bcAPI Task. Once kill
is requested there is no way to bring bcAPI functionality back on, so a new bcAPI node instance would need to be created.
Since this process is asynchronous, once the bcAPI is completely terminated the ready
field is set back to false
to notify eventual observing functions about the Task termination.
Possible Values:
false
no action.true
aborts ongoing requests and terminates the bcAPI Task.
Code Snippet
' ...
' just like the "bcAPI.abort", all requests that had a response Node provided will
' get notified once the request is aborted prior to the Task termination
m.bcAPI.kill = true
' ...
Output Fields
response
ASSOCIATIVE ARRAY
Requests responses can be accessed through the response field unless a response Node was provided in the request options to capture the response metadata.
Possible Values:
The response is an Associative Array object whose properties can vary depending on the type of response it refers to:
HTTP request response
id
STRING
The request ID. If not provided in a request, contains the timestamp the request was initiated at. In a Brightcove Playback API it’s set to the specific request name.
code
INTEGER
The response HTTP status code.
headers
ASSOCIATIVE ARRAY
The response HTTP headers.
failure
STRING
An error message is applicable,
OK
in a successful request.failure
contains the GetFailureReason function.duration
FLOAT
Request duration since its initialization until a response is received.
-
body
ASSOCIATIVE ARRAY
STRING
The response body.
In a request the
body
format may depend on theforceFormat
option.In a Brightcove Playback API request the response metadata is provided in an Associative Array object.
-
request
ASSOCIATIVE ARRAY
Some data from the original request, includes the following properties:
-
url
STRING
The request URL
-
method
STRING
The request method (get, post, etc)
-
Internal error (configuration issues)
id
STRING
ID of the request that originated the error (
request
,getVideo
,getVideos
,getRelated
,getPlaylist
or the custom request ID).code
INTEGER
1
,2
or3
. The higher the number the deeper the origin of the error is.duration
FLOAT
Hardcoded to
-1
as it’s not relevant in this case.failure
STRING
The error message.
Aborted request (in a response Node only)
aborted
BOOLEAN
Hardcoded to
true
.
Code Snippet
sub init()
' initialize bcAPI node reference
m.bcAPI = createObject("roSGNode", "bcLib:bcAPI")
' setup bcAPI config fields and initiate the bcAPI Task
m.bcAPI.setFields({
' ...
control: "run"
})
' observe bcAPI "response" field to retrieve the response data
' keep in mind that if a response Node isn't provided, all request responses are
' set into the bcAPI response field
m.bcAPI.observeField("response", "onResponse")
' setup the request configuration and initiate it
m.bcAPI.request = {
data: {...}
}
' OR
' create a response Node that will be used to "catch" the request response data
responseNode = createObject("roSGNode", "Node")
' create an Associative Array "response" field in this Node
responseNode.addFields({ response: {} })
' observe the just added "response" field to capture the response data
responseNode.observeField("response", "onResponse")
' setup the request configuration, provide the response Node and initiate the request
' bcAPI.response will not get this request response
m.bcAPI.request = {
node: responseNode,
data: {...}
}
end sub
sub onResponse(ev)
response = ev.getData()
' handle request response
end sub
ready
BOOLEAN
Read-only field that indicates if the bcAPI Task is ready to process request commands or has been terminated.
A bcAPI node instance can be terminated through the following actions:
setting its
control
field tostop
setting its
kill
field is set totrue
Possible Values:
false
bcAPI
has not been complete initiated or has been completely terminated. No requests can be executed in this state.true
bcAPI
Task is ready to trigger requests
Code Snippet
sub init()
' initialize bcAPI node reference
m.bcAPI = createObject("roSGNode", "bcLib:bcAPI")
' observe the "ready" field
m.bcAPI.observeField("ready", "onReady")
' setup bcAPI config fields and initiate the bcAPI Task
m.bcAPI.setFields({
' ...
control: "run"
})
' Trigger bcAPI requests here
' The bcAPI node is able to process request commands at this point, right after its initialization.
' There's no need to wait for it to be ready as it can detect that a new request command was initiated
' ...
' terminate the bcAPI node instance.
' This will abort all ongoing requests and terminate the task, after which the ready field is set to false
m.bcAPI.kill = true
end sub
sub onReady(ev)
isReady = ev.getData()
if NOT isReady then
' the bcAPI task been terminated and cannot be used anymore
end if
end sub
Utils
The Utils node provides a set of Brightscript helping utilities that may be useful for validations or common operations.
An instance of this node can be created like so:
m.bcUtils = createObject("roSGNode", "bcLib:Utils")
Once a Utils instance is available, its functions can be accessed as follows:
' checks if the passed data is an Associative Array, in this case isAA is true
isAA = m.bcUtils.callFunc("isAA", {b: "c"})
Functions
validate
Validates passed values according to the rules provided.
Parameters:
value
DYNAMIC
REQUIRED
The value meant to be validated.
map
ASSOCIATIVE ARRAY
REQUIRED
A map of rules used to validate the provided value against. This Associative Array object contains the following properties:
type
STRING
REQUIRED
Specifies the expected value type. The following types are supported:
string
Value must be a String.number
Value must be a number (Integer, Float, Double or LongInteger).boolean
Value must be a Boolean.array
Value must be an Array.node
Value must be a roSGNode.aa
Value must be an Associative Array.<type>
If none of the previous values is recognized, it uses<type>
to support other Roku types. Please be aware that type() can return different values for the “same” type, ie: “String” vs “roString”.
required
BOOLEAN
OPTIONAL
Specifies that the value cannot be invalid if true. Default to true if not provided. Applicable to all types.
empty
BOOLEAN
OPTIONAL
Specifies that the value can be an empty String (““), Associative Array ({}) or Array ([]) if
true
.Defaults to true if not provided. Only applicable to
string
,aa
andarray
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
andarray
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
andarray
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
andnumber
types.min
INTEGER
OPTIONAL
Specifies the minimum value of
value
. Only applicable to thenumber
type.max
INTEGER
OPTIONAL
Specifies the maximum value of
value
. Only applicable to thenumber
type.null
BOOLEAN
OPTIONAL
Specifies if
value
can be0
. Only applicable to thenumber
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 themap
section are supported. Only applicable to theaa
type.subtype
STRING
OPTIONAL
Specifies the subtype (as indicated by
value.subtype()
) thatvalue
should reflect. Only applicable to thenode
type.fields
ARRAY
OPTIONAL
Specifies a list of fields that the
value
node must have (as indicated byvalue.hasField("field")
). An Array of Strings must be provided where each entry represents the name of a field. Only applicable to thenode
type.interface
STRING
OPTIONAL
Specifies the interface (as indicated by
getInterface()
) thatvalue
should reflect. Only applicable to thenode
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 withneedle
.If
needle
is not a string, the comparison is made withneedle = haystack[i]
..
needle
STRING
NUMBER
REQUIRED
The value to find in the haystack. When comparing strings, both
needle
andhaystack
are lower-cased.
Return Value
BOOLEAN
Returns true
if needle
is found in haystack
or false
otherwise.
Code Snippet
m.bcUtils = createObject("roSGNode", "bcLib:Utils")
test = m.bcUtils.callFunc("contains", "This is A tEst string", "a test")
' test = true
test = m.bcUtils.callFunc("contains", [2, "a", 5], "5")
' test = false
indexOf
Just like contains, searches for a needle in a haystack, but returns the index of the needle in the haystack if found instead.
Parameters:
haystack
STRING
ARRAY
REQUIRED
A String or Array where to search for the needle. Have in mind the following details:
If
haystack
is a string, theneedle
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 withneedle
.If
needle
is not a string, the comparison is made withneedle = haystack[i]
..
needle
STRING
NUMBER
REQUIRED
The value to find in the haystack. When comparing strings, both
needle
andhaystack
are lower-cased.
Return Value
INTEGER
-1
if needle isn't found.Index of needle in haystack. Either the
haystack
array index where needle was found or theinStr()
result ifneedle
andhaystack
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
ifvalue
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
ifvalue
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
ifvalue
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
ifvalue
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
ifvalue
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
ifvalue
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
ifvalue
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
ifvalue
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 minimummaxDepth
value is1
. 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}>"
. IfmaxDepth
has been reached, the following format is returned:“<Component: NodeType>"
.Array
Converts the Array to a string by converting each individual Array entry to a String in a recursive execution of this function. If
maxDepth
is reached, the following format is returned:“[ArrayLength]"
.List
Just like Array, converts the List to a string by converting each individual List entry to a String in a recursive execution of this function. If
maxDepth
is reached, the following format is returned:“[ListLength]"
.Associative Array
Converts the Associative Array to a string by converting each individual key value to a String in a recursive execution of this function. If
maxDepth
is reached, the following format is returned:“{[ListOfKeys]}"
.Boolean
Returns the Boolean string representation.
roDateTime
Returns the DateTime ISO string.
Any other “ro<node-name>“ nodes
Returns the following format:
“<Component: NodeType>"
.-
Any other value not mention will return an empty String.
Code Snippet
m.bcUtils = createObject("roSGNode", "bcLib:Utils")
test = m.bcUtils.callFunc("toString", 567)
' test = "567"
test2 = { one: { two: { three: { four: { five: "Hello World" } } } } }
test2 = m.bcUtils.callFunc("toString", test2, 2)
' test2 = "{\"one\":{\"two\":{[\"three\"]}}}"
toDouble
Converts a string to double.
Parameters:
value
STRING
REQUIRED
The string value to be converted into a Double value.
Return Value
DOUBLE
Returns the converted value as a Double number.
Code Snippet
m.bcUtils = createObject("roSGNode", "bcLib:Utils")
? m.bcUtils.callFunc("toDouble", "3244.34343") ' => 3244.34343#
? m.bcUtils.callFunc("toDouble", "not a number") ' => 0#
? m.bcUtils.callFunc("toDouble", "dfdfd.435454") ' => 0.435454#
? m.bcUtils.callFunc("toDouble", "0.45454454") ' => 0.45454454#
? m.bcUtils.callFunc("toDouble", "-34343.45454454") ' => -34343.45454454#
setAddFields
Adds or updates a set of properties in the specified Node. It essentially goes through the list of properties provided in the fields
parameter and:
-
If the field does not exist in the Node provided: adds the new field with the value provided.
-
If the field already exists in the Node provided: updates its value with the value provided.
The change
and focusedChild
properties are removed from the fields object, if present, before applying the fields to the Node.
Parameters:
node
NODE
REQUIRED
The Node reference which will get its fields updated
fields
ASSOCIATIVE ARRAY
REQUIRED
A set of key-value pairs representing the field names and the respective values to be added / updated in the Node provided.
Return Value
VOID
Code Snippet
m.bcUtils = createObject("roSGNode", "bcLib:Utils")
testNode = createObject("roSGNode", "ContentNode")
testNode.id = "hello world"
m.bcUtils.callFunc("setAddFields", {
id: "hello planet",
customField: "my custom field"
})
? "testNode id: " testNode.id ' => "hello planet"
? "testNode customField: " testNode.customField ' => "my custom field"
addURLParams
Adds the provided key-value pairs as query parameters into the URL provided.
Be aware that this function does not verify if query parameters already exist, it simply appends all the properties in the params
parameter to the url
value.
Parameters:
url
STRING
REQUIRED
The URL where query parameter will be added.
params
ASSOCIATIVE ARRAY
REQUIRED
A key-value object specifying the query parameter names and values to be added into
url
.
Return Value
STRING
Returns url
with the added query parameters. If, for any reason, no query parameters were added, url
is returned as is.
Code Snippet
m.bcUtils = createObject("roSGNode", "bcLib:Utils")
url = "http://my.fancy.url"
url = m.bcUtils.callFunc("addURLParams", url, {hello: "world"})
? url ' => "http://my.fancy.url?hello=world"
' running the function again with the same parameters will result in duplicated query parameters
url = m.bcUtils.callFunc("addURLParams", url, {hello: "world"})
? url ' => "http://my.fancy.url?hello=world&hello=world"
match
Search for matching substrings in a String through a regex pattern. If the matching pattern contains N parenthetical substrings, the relevant substrings are returned as an array of length N+1
, where array[0]
is again the entire match and each additional entry in the array is the match for the corresponding parenthetical expression.
Uses Roku’s roRegex component internally.
Parameters:
string
STRING
REQUIRED
The string to be searched for matching substrings.
pattern
STRING
REQUIRED
The regex pattern.
flag
STRING
OPTIONAL
Specifies the behavior flags. Empty string if not provided. Any combination of the following flags is supported:
i
Case insensitive match.m
Multiline mode. The start of line^
and end of line$
constructs match immediately following or before any newline in the subject string as well as the very start and end of the string. Normally, just the start and end of the string would match.s
Sets dot-all mode that includes newline in the.*
regular expression. This modifier is equivalent to Perl's/s
modifier.x
Sets extended mode that ignores whitespace characters except when escaped or inside a character class. Characters between an unescaped#
outside a character a character class and the next newline character, inclusive, are also ignored. This modifier is equivalent to Perl's/x
modifier.
Return Value
ARRAY
Returns an Array of matched substrings from string
. If no match was made, an empty array is returned. If a match was made, the entire match is returned in array[0]
. If there are no parenthetical substrings this is the only entry in the array.
Code Snippet
m.bcUtils = createObject("roSGNode", "bcLib:Utils")
test = m.bcUtils.callFunc("match", "abcd", "(a|(z))(bc)", "i")
' test = ["abc", "a", "", "bc"]
replace
Replaces all occurrences of a matching pattern in string with replacement String and returns the result. The replacement may contain numbered back-references to parenthetical substrings.
Keep in mind that the replace function does not use any behavior flags.
Uses Roku’s roRegex component internally.
Parameters:
string
STRING
REQUIRED
The string where occurrences of a matching
pattern
will be replaced byreplacement
.pattern
STRING
REQUIRED
The regex pattern.
replacement
STRING
REQUIRED
The string to be used to replace matches in the provided
string
.
Return Value
STRING
A string with the result of the replace operation.
Code Snippet
m.bcUtils = createObject("roSGNode", "bcLib:Utils")
test = m.bcUtils.callFunc("replace", "Abracadabra", "a", "x")
' test = "Abrxcxdxbrx"
truncate
Allows to truncate a string by the specific number of chars and set a custom truncate char.
Parameters:
string
STRING
REQUIRED
The string to check.
length
INTEGER
REQUIRED
The end characters to check.
chars
STRING
DEFAULT
Chars that will be added in the truncate position of the string. Defaults to
...
if not provided.
Return Value
STRING
Returns the truncated string.
Code Snippet
m.bcUtils = createObject("roSGNode", "bcLib:Utils")
test = m.bcUtils.callFunc("truncate", "My String", 3)
' test = "My ..."
test2 = m.bcUtils.callFunc("truncate", "My String", 2, "-")
' test2 = "My-"
test3 = m.bcUtils.callFunc("truncate", "My String", 2, "")
' test3 = "My"
toMD5
Generates the hash of a string using MD5 algorithm.
Parameters:
string
STRING
REQUIRED
The string to generate the MD5 hash from.
Return Value
STRING
Returns the string
MD5 hash.
Code Snippet
m.bcUtils = createObject("roSGNode", "bcLib:Utils")
test = m.bcUtils.callFunc("toMD5", "My String")
' test = "4545102cc40ea0a85124cf4b31574661"
toSHA1
Generates the hash of a string using SHA1 algorithm.
Parameters:
string
STRING
REQUIRED
The string to generate the SHA1 hash from.
Return Value
STRING
Returns the string
SHA1 hash.
Code Snippet
m.bcUtils = createObject("roSGNode", "bcLib:Utils")
test = m.bcUtils.callFunc("toSHA1", "My String")
' test = "c9dacbd8a688c5b310890310e14272ac11be5744"
toSHA256
Generates the hash of a string using SHA256 algorithm.
Parameters:
string
STRING
REQUIRED
The string to generate the SHA256 hash from.
Return Value
STRING
Returns the string
SHA256 hash.
Code Snippet
m.bcUtils = createObject("roSGNode", "bcLib:Utils")
test = m.bcUtils.callFunc("toSHA256", "My String")
' test = "3f9a07d83c604dba400d13df4d34566b78338804f0b3181d4e02089fe4daa7b0"
toSHA512
Generates the hash of a string using SHA512 algorithm.
Parameters:
string
STRING
REQUIRED
The string to generate the SHA512 hash from.
Return Value
STRING
Returns the string
SHA512 hash.
Code Snippet
m.bcUtils = createObject("roSGNode", "bcLib:Utils")
test = m.bcUtils.callFunc("toSHA512", "My String")
' test = "8c4b4171030e0483f46805abfa1b9..."
is4kReady
Checks if the current Roku device is capable of reproducing 4K content. The following items are verified:
Connected display resolution (must be
2160p
for 4K content playback)[Roku STB only] HDCP version (must be
2.2
for 4K content playback)Roku device video decoding capabilities (must be able to decode
hevc
andvp9
video codecs)
The Roku device is considered 4K Ready if all of these items are valid.
Parameters:
This function has no parameters.
Return Value
BOOLEAN
Returns true
if the device is able to reproduce 4K content, false
otherwise.
Code Snippet
m.bcUtils = createObject("roSGNode", "bcLib:Utils")
test = m.bcUtils.callFunc("is4kReady")
' test = true
isHDRReady
Checks if the current Roku device is capable of reproducing the specified HDR type. Uses getDisplayProperties for this purpose.
Parameters:
hdr
STRING
OPTIONAL
The HDR type to check for support. The following values are supported:
""
DEFAULT
Checks if any HDR type is supported. This is the default behavior if
hdr
is not provided.hdr10
Checks if HDR10 is supported.
hdr10plus
Checks if HDR10+ is supported.
hlg
Checks if HLG is supported.
dolbyvision
Checks if Dolby Vision is supported.
Return Value
BOOLEAN
Returns true
if the specified HDR type is supported, false
otherwise.
Code Snippet
m.bcUtils = createObject("roSGNode", "bcLib:Utils")
test = m.bcUtils.callFunc("isHDRReady", "hdr10plus")
' test = false
canPlayAudio
Checks if the current Roku device is capable of reproducing the specified audio codec. Essentially this function provides an interface for CanDecodeAudio.
Parameters:
params
ASSOCIATIVE ARRAY
REQUIRED
Specifies the audio codec to check for support. Supports the same properties as the CanDecodeAudio
audio_format
parameter.
Return Value
BOOLEAN
Returns true
if the device is able to reproduce the specified audio codec, false
otherwise. Essentially returns the value of the CanDecodeAudio return result
property.
Code Snippet
m.bcUtils = createObject("roSGNode", "bcLib:Utils")
test = m.bcUtils.callFunc("canPlayAudio", {codec: "eac3", Atmos: 1})
' test = false
Logger
The Logger node allows to configure and trigger logging messages.
The bcPlayer node already has an internal Logger node which can be configured through the bcPlayer.logLevel
field. Keep in mind that when running a Roku app in production, the bcPlayer logs should be captured through the bcPlayer.on.logOutput
event.
A Logger node can also be provided to bcAPI nodes to trigger internal logging messages.
An instance of this node can be created like so:
sub init()
' create a Logger node instance
m.bcLogger = createObject("roSGNode", "bcLib:Logger")
' set the output observe when using the "capture" mode
m.bcLogger.observeField("output", "onLog")
' set the "capture" mode so that log messages are sent into the "output" field
m.bcLogger.mode = "capture"
' minimum logging level
m.bcLogger.level = 1
m.bcLogger.callFunc("error", "My error message", <extra-details-to-log>)
end sub
sub onLog(ev)
' handle the log data here
end sub
Fields
level
INTEGER
OPTIONAL
Specifies the minimum log level. Only log messages with an equal or higher level are triggered.
Possible Values:
0
Error. Triggers Error logs only.1
Warning. Triggers Warning and Error logs only.2
Info. Triggers Info, Warning and Error logs only.3
Debug. Triggers Debug, Info, Warning and Error logs only.4
DEFAULT
Verbose. Triggers all log levels.
mode
STRING
OPTIONAL
Specifies where the log messages are sent to.
Possible values:
telnet
DEFAULT
Prints log messages in the following format:
[hh:mm:ss.ms][<level-label>]: <log-message> <optional-data>
capture
Log messages are sent to the output field.
output
ASSOCIATIVE ARRAY
Read-only field used to capture log messages data. This can be useful to transfer log data to an external logging component.
Only applicable if mode is set to capture
.
Possible values:
Provides an Associative Array object with the following properties:
level
INTEGER
Specifies the log message level.
time
INTEGER
Specifies the log message timestamp (in seconds).
message
STRING
Specifies the log message.
params
DYNAMIC
Specifies extra parameters some log messages might provide. This can be any data type, usually a string or an Associative Array.
invalid
if no extra parameters are provided.
Functions
The following functions allow log messages to be triggered from the Logger node.
error
Triggers an error log message (level 0).
Parameters:
message
STRING
REQUIRED
Specifies the log message.
params
DYNAMIC
OPTIONAL
Specifies the log message.
Code Snippet
m.bcLogger = createObject("roSGNode", "bcLib:Logger")
m.bcLogger.callFunc("error", "my error message", <optional-data>)
warn
Triggers a warning log message (level 1).
Parameters:
message
STRING
REQUIRED
Specifies the log message.
params
DYNAMIC
OPTIONAL
Specifies any useful data to be logged.
Code Snippet
m.bcLogger = createObject("roSGNode", "bcLib:Logger")
m.bcLogger.callFunc("warn", "my warning message", <optional-data>)
info
Triggers an info log message (level 2).
Parameters:
message
STRING
REQUIRED
Specifies the log message.
params
DYNAMIC
OPTIONAL
Specifies any useful data to be logged.
Code Snippet
m.bcLogger = createObject("roSGNode", "bcLib:Logger")
m.bcLogger.callFunc("info", "my informational message", <optional-data>)
debug
Triggers a debug log message (level 3).
Parameters:
message
STRING
REQUIRED
Specifies the log message.
params
DYNAMIC
OPTIONAL
Specifies any useful data to be logged.
Code Snippet
m.bcLogger = createObject("roSGNode", "bcLib:Logger")
m.bcLogger.callFunc("debug", "my debug message", <optional-data>)
verbose
Triggers a verbose log message (level 4).
Parameters:
message
STRING
REQUIRED
Specifies the log message.
params
DYNAMIC
OPTIONAL
Specifies any useful data to be logged.
Code Snippet
m.bcLogger = createObject("roSGNode", "bcLib:Logger")
m.bcLogger.callFunc("verbose", "my verbose message", <optional-data>)
Dialog
Dialog provides a StandardDialog node with extended customization options. Since Dialog extends the native StandardDialog, all its fields are accessible through Dialog as well.
Once a Dialog node is instanced and configured, it can be shown by assigning it to the dialog
field of the app's Scene node.
Dialog component can be initialized like so:
sub init()
' create a Dialog node instance
m.dialog = createObject("roSGNode", "bcLib:Dialog")
' set up its fields
m.dialog.setFields({ ... })
' assign it to the app Scene "dialog" field to show it
m.top.getScene().dialog = m.dialog
end sub
Fields
Besides the native fields of StandardDialog, Dialog provides a set of custom fields meant to streamline the creation and setup of a Dialog window.
theme
ASSOCIATIVE ARRAY
OPTIONAL
Allows to set up the Dialog theme colors. The properties provided in theme are reflected in the StandardDialog palette field.
Possible values
-
Supports all StandardDialog palette field properties. If not provided, Roku default colors are used.
Code Sinippet
m.dialog = createObject("roSGNode", "bcLib:Dialog")
m.dialog.theme = {
DialogBackgroundColor: "#29292900",
DialogTextColor: "#D1D1D100",
DialogFocusColor: "#B9323200"
}
m.top.getScene().dialog = m.dialog
titleConfig
ASSOCIATIVE ARRAY
OPTIONAL
Allows to customize the Dialog title area.
Possible values:
Supports all StdDlgTitleArea fields plus the following custom properties:
-
fontSize
INTEGER
OPTIONAL
Specifies the Dialog title font size. If not provided, the default StdDlgTitleArea font size is used.
-
fontUrl
STRING
OPTIONAL
Specifies the Dialog title font URL. If not provided, the default StdDlgTitleArea font URL is used.
-
align
STRING
OPTIONAL
Specifies the Dialog title text horizontal alignment. The following values are supported:
left
DEFAULT
right
center
Code Sinippet
m.dialog = createObject("roSGNode", "bcLib:Dialog")
m.dialog.titleConfig = {
primaryTitle: "My Dialog",
primaryIcon: "pkg:/my/dialog/icon.png",
align: "center"
}
content
ARRAY
OPTIONAL
Allows to customize the Dialog content area.
Possible values:
Supports an Array where each entry represents a component in the Dialog content area. Any combination of the following items is supported:
-
STRING
Adds a StdDlgTextItem node to the Dialog content area. The provided string specifies its
text
field. -
ASSOCIATIVE ARRAY
Adds the specified component to the Dialog content area. The
type
property value defines what type of component will be added as well as the other properties specific to that component. The following sets of properties are supported, per component type:- Text component (StdTextItem)
-
type
STRING
REQUIRED
Specifies the type of the component,
text
for a StdDlgTextItem component. -
text
STRING
OPTIONAL
Specifies the StdDlgTextItem text field value.
-
style
STRING
OPTIONAL
Specifies the StdDlgTextItem
namedTextStyle
field value. If not provided, normal is used. -
align
STRING
OPTIONAL
Specifies the text horizontal alignment. The following values are supported:
left
DEFAULT
right
center
-
- Progress component
-
type
STRING
REQUIRED
Specifies the type of the component,
progress
for a StdDlgProgressItem component. -
text
STRING
OPTIONAL
Specifies the StdDlgProgressItem
text
field value. -
interval
INTEGER
OPTIONAL
Specifies the internal BusySpinner node
spinInterval
field value. -
counterclockwise
BOOLEAN
OPTIONAL
Specifies if the internal BusySpinner node should rotate in the counter-clockwise direction. Set to
false
if not specified. -
size
NUMBER
OPTIONAL
Specifies the
width
andheight
values of the internal BusySpinner node. -
url
STRING
OPTIONAL
Specifies the Poster node
url
of the internal BusySpinner node. Thesize
property is required for theurl
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
-
- Text component (StdTextItem)
Code Sinippet
m.dialog = createObject("roSGNode", "bcLib:Dialog")
m.dialog.content = [
"My Pretty Dialog",
{
type: "text",
text: "My bold and centered Pretty Dialog"
style: "bold",
align: "center"
},
{
type: "multistyle",
text: "My <p>Pretty</p> Dialog"
styles: {
default: {
fontSize: 34
fontUri: "font:SystemFontFile"
color: "#EFEFEFFF"
},
p: {
fontSize: 42
fontUri: "font:SystemFontFile"
color: "#00FF00FF"
}
},
align: "center"
}
]
m.top.getScene().dialog = m.dialog
The code snippet above produces the following Dialog content:
sidecard
ASSOCIATIVE ARRAY
OPTIONAL
Allows to set up the Dialog side card area.
Possible values:
-
invalid
removes the current side card if present. -
An Associative Array containing any of the StdDlgSideCardArea fields plus the following custom properties:
-
content
ASSOCIATIVE ARRAY
REQUIRED
Specifies the Dialog side card contents. Any combination of the following items is supported:
-
ASSOCIATIVE ARRAY
An Associative Array object specifying the name of a Node and its fields. The following properties are required:
node
STRING
REQUIRED
Specifies the name of the Node that should be added into the Dialog side card.
fields
ASSOCIATIVE ARRAY
REQUIRED
Specifies the fields of the Node and its values.
-
NODE
A Node reference. This Node will be added as is to the side card content area.
-
-
Code Sinippet
m.dialog = createObject("roSGNode", "bcLib:Dialog")
m.dialog.setFields({
titleConfig: {
primaryTitle : "My Pretty Dialog"
},
content: [
"Once upon a time a pretty Dialog"
],
sidecard: {
extendToDialogEdge: true,
horizAlign: "left",
width: 300,
content: [
{
node: "Poster",
fields: {
width: 300,
height: 300,
uri: "https://images.unsplash.com/photo-1553095066-5014bc7b7f2d?q=80&w=300&h=300&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxzZWFyY2h8Mnx8d2FsbCUyMGJhY2tncm91bmR8ZW58MHx8MHx8fDA%3D"
}
},
{
node: "Label",
fields: {
text: "Fancy",
horizAlign: "center",
width: 300,
translation: [0, 180]
}
}
]
}
})
m.top.getScene().dialog = m.dialog
The code snippet above produces the following Dialog content:
buttons
ARRAY
OPTIONAL
Allows to set up the buttons of the Dialog.
Since Dialog extends a StandardDialog, its buttons selection and focus events can be accessed through the buttonSelected
and buttonFocused
fields.
Possible values:
An Array where each item is mapped into a StdDlgButton. Any combination of the following items is supported:
-
A String Value
STRING
Adds a StdDlgButton node with its
text
field set to the text provided. -
An Associative Array object
ASSOCIATIVE ARRAY
Allows for some extra StdDlgButton customization options. The following properties are supported:
-
text
STRING
OPTIONAL
Specifies the button text.
-
disabled
BOOLEAN
OPTIONAL
Specifies if the button should be disabled. A disabled button cannot be focused or selected. If not provided, the default value is
false
. -
align
STRING
OPTIONAL
Specifies the button text horizontal alignment. The following values are supported:
-
left
DEFAULT
right
center
-
-
closeDialog
BOOLEAN
OPTIONAL
Specifies if this button should close the Dialog when selected. If not provided, the default value is
false
.
-
Code Sinippet
m.dialog = createObject("roSGNode", "bcLib:Dialog")
m.dialog.setFields({
titleConfig: {
primaryTitle: "My Pretty Dialog"
},
buttons: [
"Pretty",
{
text: "Test",
disabled: false,
align: "center",
closeDialog: true
},
{
text: "Dialog",
disabled: true,
align: "right",
}
]
})
m.top.getScene().dialog = m.dialog
The code snippet above produces the following Dialog content: