SPB TV Player
Basics
To use player, you will need to reference at least 3 files from your html page:
- player.css
- dash.all.min.js
- player.all.js
- hls.min.js - only in case if you will need to play HLS streams
The only entry point is function spbtvplayer(id, options).
First argument is the id of div element where all player-related elements will be created.
Second argument is object with options to configure player.
Types of options
There are three "levels" of options:
- global
- instance
- stream
Global options affect all players in current window. Instance options are specific for each instance of player. Stream options are for stream-related parameters (that can change every time you play new stream).
Both global and stream options can be passed as sub-items of instance options.
Global options are initialized only once during lifetime of current web page. They can be passed to spbtvplayer function either separately (in this case you will need to set id to null) or together with instance options. All future attempts to set global options will be ignored.
On the other hand, stream options are passed to function that sets stream source url for player. But you can also configure their default values by adding them to instance options.
Objects
If id passed to spbtvplayer function is a string, then the function will return special "player" object.
"Player" object is the main object that is used to access player functionality.
player = spbtvplayer('some_id', {});
player.afterInitialize(readyFunc);
function readyFunc() {
}
If id passed to spbtvplayer is undefined, then object with global static functions is returned.
spbtvplayer().getPlayerVersion()
Global functions
Global static functions object has the following methods:
- getPlayerVersion - returns string with player version
- getProtocolAndDrm - reports supported protocol/drm pair to provided callback function
More details
getProtocolAndDrm(needDrm, callback, options)
- needDrm - informs player whether you will need to play drm-protected content or not
- callback(protocol, drm, codecs) - callback function that is called after required information is available
- options - similar to options configured for player
{
codecs: {
h264: true,
h265: false,
vp9: false,
av1: false
},
tweaks: {
forceNative: null,
forceHls: false
}
}
Player methods
"Player" object has the following methods:
- afterInitialize - register callback function that will be called after player is initialized (it will be called immediately if player is already initialized)
- isInitialized - check if player is initialized
- getProtocol - get supported streaming protocol name
- getDrmSystem - get supported drm system name
- isHlsSupported - check if HLS protocol is supported
- getVideoCodecs - get list of supported video codecs for dash protocol (only among those that were enabled in config)
- attachSource - set stream url and stream options
- play - start/resume playing
- pause - pause playing
- getPaused - get paused state
- getIsLive - get live streaming flag
- seek - seek stream to specific position, in seconds
- getCurrentTime - get current stream position, in seconds
- getDuration - get current stream duration, in seconds
- getAbsoluteCurrentTime - get current utc unixtime for live streams
- getAbsoluteTimeRange - get utc start/end range for live streams
- getTimeshiftAvailable - check if timeshift is available
- getVideoQualityList - get array with information about available video qualities
- getSelectedVideoQuality - get index of currently selected video quality (-1 for auto)
- getPlayingVideoQuality - get index of currently playing video quality (-1 if unknown)
- setSelectedVideoQuality - set index of video quality to play (-1 for auto)
- getAudioTrackList - get array of available audio tracks
- getCurrentAudioTrack - get index of currently selected audio track
- setCurrentAudioTrack - set index of audio track to play
- getSubtitlesTrackList - get array of available subtitles tracks
- getCurrentSubtitlesTrack - get index of currently selected subtitles track (-1 for disabled)
- setCurrentSubtitlesTrack - set index of subtitles track to display (-1 to disable)
- setSelectionStartPos - mark current position as selection start
- setSelectionEndPos - mark current position as selection end
- getSelectionRange - get currently selected range
- getZoomButtonVisible - get zoom button visibility
- getZoomModeEnabled - check if zoom mode is enabled
- setZoomModeEnabled - enable/disable zoom mode (boolean argument)
- setVolume - set audio volume
- getVolume - get audio volume
- mute - mute audio
- unmute - unmute audio
- getMuted - get muted state
- getBufferLength - get length in seconds of buffered data
- getNetworkBandwidth - get current network bandwidth in kbit/s
- getBufferingState - wheither or not playback is stalled due to buffering
- getCurrentVideoInfo - get information about currently playing video track
- getControlbarVisible - get visibility state of control bar
- getAdIsPlaying - player is currently loading/playing ads
- cancelAdPlayback - cancel currently playing advertisement(s)
- addEventListener - add listener of specific event
- removeEventListener - remove listener of event
- destroy - destroy "player" object
More details
getProtocol() possible return values:
- dash
- hls
- mss
getDrmSystem() returns one of these strings:
- none
- playready
- widevine
- fairplay
attachSource(url, streamOpts)
- url - url of media stream
- streamOpts - stream-specific options. overrides defaults, provided during player initialization
getCurrentVideoInfo() returns object with the following fields (or null if player is not initialized yet):
- width - width of the video
- height - height of the video
- bitrate - bitrate of the video
Events
"Player" object has the following events:
- destroyed - object was destroyed
- sourceAttached - new stream source was set
- canplay - player is ready to play video
- play - video playback started/resumed
- pause - video playback paused
- ended - video playback finished (played until end)
- error - video playback error
- timeupdate - current stream position changed
- timeshiftUpdate - timeshift availability changed
- volumechange - audio volume changed
- bufferLengthUpdate - buffer length changed
- bufferingUpdate - buffering state changed
- qualityChange - current video quality changed
- trackChange - current audio/subtitles track changed
- zoomButtonChange - update visibility of zoom button
- zoomModeChange - update state of zoom mode
- timeNotify - reached stream/wall-clock position configured in
timeNotifysection of options - adRequested - before ad loading is initiated
- adStarted - ad block started
- adFinished - ad block finished successfully
- adError - ad finished with error
- adItemStarted - one ad in ad block started
- adItemFinished - one ad in ad block finished successfully
- adItemError - one ad in ad block finished with error
- adImpression - ad impression happened
- disableAdsClick - user clicked disable ads button
- logoClick - user clicked on logo button
- controlbarShow - control bar is shown
- controlbarHide - control bar is hidden
- toolboxStartSel - toolbox start selection button was clicked
- toolboxEndSel - toolbox end selection button was clicked
- toolboxProcessSel - toolbox process selection button was clicked
More details
Event functions have only one argument that is object with event-specific members.
All of them have member of name type that contains event name.
Event-specific members are listed below:
error:
- error - string, specifying error type. Possible values:
network,drmandother.
trackChange:
- mediaType -
audioorsubtitles
zoomButtonChange:
- visible - boolean value indicating if button is currently visible or not
zoomModeChange:
- enabled - boolean value indicating if zoom mode is enabled
timeNotify:
- notificationType -
streamfor stream time orwallfor elapsed wall clock time - requestedTime - timestamp from config
- id - id from config
- currentTime - current stream position or elapsed wall clock time
adImpression:
- adId - id of advertisement being played from top-level VAST
logoClick:
- button - type of logo button that was clicked, possible values: 'toolbar', 'player'
Global options
{
uiLanguage: null,
chromecastAppId: null,
localizationPath: null,
localizationObj: null
}
- uiLanguage - string with two-letter language name to use in UI
- chromecastAppId - string with app id to use for chromecast (enables chromecast feature if specified)
- localizationPath - path where localization files are located (default - autodetect, empty string to disable)
- localizationObj - object with key/value localization (have priority over file-based localization)
Instance options
{
features: {
api: false,
drm: false,
ads: false,
heartbeat: false,
metrics: false
},
apiConfig: {
clientId: null,
channelId: null,
movieId: null,
episodeId: null,
newsId: null,
apiHost: null,
urlGetParams: null
},
uiConfig: {
initAsLive: false,
focusAtInit: true,
focusReasons: {
playPause: false,
buttonClick: true,
fullscreenChange: true
},
autoshowToolbox: true,
emptyPoster: false,
hideControls: false
},
adConfig: {
adInfo: true,
adNotification: 'Ads allow us to show this video legally and free',
topLine: null,
bottomLine: null,
minAdHeight: 225,
adjustFontSize: true,
precacheVAST: false,
initCountdown: true,
showDisableAds: false,
autoPause: false,
autoResume: false,
showMarkers: true,
debugLogs: false,
disableVPAID: false,
delayImpressions: false
},
controls: {
contextMenu: {
enable: true
},
prevButton: {
availability: null,
action: null
},
nextButton: {
availability: null,
action: null
},
rewindButton: {
enable: true,
amount: 30
},
forwardButton: {
enable: true,
amount: 30
},
zoomButton: {
enable: false
},
qualityMenu: {
showBitrate: true,
showWidth: false
},
editing: {
enable: false
},
largePlayButton: true,
bufferingSpinner: true,
continueWatching: {
enable: true,
timeout: 15,
init: null,
destroy: null
},
startOver: {
enable: true,
timeout: 15,
init: null,
destroy: null
},
nextPopup: {
enable: true,
timeout: 15,
init: null,
destroy: null,
tick: null
},
previewPopup: {
imageCallback: null
},
logoButton: {
toolbar: {
enable: false,
icon: null,
title: null,
clickUrl: null
},
player: {
enable: false,
position: 'topright',
icon: null,
title: null,
clickUrl: null,
initialPause: 0,
showDuration: 0,
pauseBetween: 0,
showCount: 0
}
}
},
playback: {
autoNext: false,
getChromecastMediaInfo: null,
supportTimeshift: true,
forceHttpsWhenMixed: false,
delayedLoad: false,
prePlayVideoElement: false
},
timeNotify: {
stream: [ { time: null, id: null } ],
wall: [ { time: null, id: null } ]
},
codecs: {
h264: true,
h265: false,
vp9: false,
av1: false
},
tweaks: {
forceNative: null,
forceHls: false,
resumeReloadsLive: false
},
debug: {
playerLogs: false
},
startupUrl: {
dash: null,
hls: null,
mss: null
},
globalOpts: {
},
streamOpts: {
}
}
-
features.api - enable rosing api for live channels
-
features.drm - enable if player at some point will be required to play streams with drm
-
features.ads - enable if player will need to show advertisement
-
features.heartbeat - enable if player will need to send heartbeats
-
features.metrics - enable metrics feature
-
apiConfig.clientId - client id for rosing api
-
apiConfig.channelId - channel id for rosing api
-
apiConfig.movieId - movie id for rosing api
-
apiConfig.episodeId - episode id for rosing api
-
apiConfig.newsId - news id for rosing api
-
apiConfig.apiHost - host name for rosing api
-
apiConfig.urlGetParams - pre-formatted string with GET parameters to append to stream url when using rosing api
-
uiConfig.initAsLive - initialize player UI as player of live streams at startup (as opposed to dynamically switch to this mode after providing stream url, which is default behaviour)
-
uiConfig.focusAtInit - set keyboard focus to player after initialize
-
uiConfig.focusReasons.playPause - focus to player when play/pause is requested
-
uiConfig.focusReasons.buttonClick - focus to player after interaction with play/pause button or seekbar
-
uiConfig.focusReasons.fullscreenChange - focus to player after entering/exiting fullscreen
-
uiConfig.autoshowToolbox - automatically show toolbox at startup if toolbox-related features are enabled
-
uiConfig.emptyPoster - show empty poster if no image is provided
-
uiConfig.hideControls - do not show player controls
-
adConfig.adInfo - show text "Advertisement" during advertisement
-
adConfig.adNotification - text for notification displayed during advertisement
-
adConfig.topLine - display mode for top line of ad controls. possible values: 'hide' - completely remove, 'over' - controls are above ads, but with their own background, 'transparent' - above ads, without background
-
adConfig.bottomLine - display mode for bottom line of ad controls. possible values: same as for topLine.
-
adConfig.minAdHeight - minimum ad height. top/bottom lines will be automatically switched to 'transparent'/'hide' mode if there is not enough container height
-
adConfig.adjustFontSize - enable auto-reducing of font size for countdown/notification/etc if there is not enough space
-
adConfig.precacheVAST - load all vast wrappers and documents (without media) in advance
-
adConfig.initCountdown - show ads player initialization/timeout countdown
-
adConfig.showDisableAds - show disable ads button
-
adConfig.autoPause - auto-pause ads when page is inactive
-
adConfig.autoResume - try to auto-resume ads after return to page
-
adConfig.showMarkers - show mid-roll markers on scrubbar
-
adConfig.debugLogs - enable additional logs for debugging
-
adConfig.disableVPAID - ignore VPAID ads
-
adConfig.delayImpressions - delay sending impression trackings until play event
-
controls.contextMenu.enable - enable player context menu
-
controls.prevButton.availability - callback function to check that need or not to show "previous video" button
-
controls.prevButton.action - function that is called when previous button is clicked
-
controls.nextButton.availability - callback function to check that need or not to show "next video" button
-
controls.nextButton.action - function that is called when next button is clicked
-
controls.rewindButton.enable - show rewind button
-
controls.rewindButton.amount - amount of seconds that rewind button rewinds
-
controls.forwardButton.enable - show forward button
-
controls.forwardButton.amount - amount of seconds that forward button skips
-
controls.zoomButton.enable - show video zoom button when applicable
-
controls.qualityMenu.showBitrate - show bitrates in quality selection menu
-
controls.qualityMenu.showWidth - show video width in quality selection menu
-
controls.editing.enable - enable controls for seekbar range selection
-
controls.largePlayButton - show overlay with large play button when paused
-
controls.bufferingSpinner - show spinner when awaiting buffering
-
controls.continueWatching.enable - enable "continue watching" popup button (only for vod streams)
-
controls.continueWatching.timeout - how long to show "continue watching" (in seconds)
-
controls.continueWatching.init - function for custom initialization of "continue watching" button
-
controls.continueWatching.destroy - function for custom cleanup for "continue watching" button
-
controls.startOver.enable - enable "start over" popup button (only for live streams)
-
controls.startOver.timeout - how long to show "start over" (in seconds)
-
controls.startOver.init - function for custom initialization of "start over" button
-
controls.startOver.destroy - function for custom cleanup for "start over" button
-
controls.nextPopup.enable - enable "next video" popup button
-
controls.nextPopup.timeout - duration in seconds of countdown for "next video" (set to NaN to disable countdown)
-
controls.nextPopup.init - function for custom initialization of "next video" button
-
controls.nextPopup.destroy - function for custom cleanup for "next video" button
-
controls.nextPopup.tick - callback function that is called every second of "next video" countdown
-
controls.previewPopup.imageCallback - callback function that returns url for scrubbar preview popup
-
controls.logoButton.toolbar.enable - enable logo button on toolbar
-
controls.logoButton.toolbar.icon - url with custom icon for toolbar logo button
-
controls.logoButton.toolbar.title - custom title for toolbar logo button
-
controls.logoButton.toolbar.clickUrl - url to open when toolbar logo button is clicked
-
controls.logoButton.player.enable - enable logo button on player
-
controls.logoButton.player.position - position of logo button on player, possible values: 'topleft', 'topright', 'bottomleft', 'bottomright'
-
controls.logoButton.player.icon - url with custom icon for player logo button
-
controls.logoButton.player.title - custom title for player logo button
-
controls.logoButton.player.clickUrl - url to open when player logo button is clicked
-
controls.logoButton.player.initialPause - pause between initial showing of player logo button, in seconds
-
controls.logoButton.player.showDuration - how long to show player logo button, in seconds, 0 = forever
-
controls.logoButton.player.pauseBetween - how long to wait between showing of player logo button, in seconds
-
controls.logoButton.player.showCount - how many times to show player logo button, 0 = indefinitely
-
playback.autoNext - automatically call "next video" callback after current video is finished
-
playback.getChromecastMediaInfo - callback that returns media information to configure chromecast receiver (posters, title, etc)
-
playback.supportTimeshift - enable timeshift mode when timeshift is available
-
playback.forceHttpsWhenMixed - patch stream url from http to https when page itself is https
-
playback.delayedLoad - do not load stream until play button is clicked
-
playback.prePlayVideoElement - in case of autoplay initiate play on video element immediately when attaching stream url, not after preload
-
timeNotify.stream - stream positions at which will be fired
timeNotifyevent with typestream -
timeNotify.wall - wall clock time offsets from start of playback at which will be fired
timeNotifyevent with typewall -
codecs - specify what codecs to try when detecting MSE availability
-
tweaks.forceNative - force usage of native player (even if it is not detected as supported), possible values: 'hls', 'mss'
-
tweaks.forceHls - initialzie player in hls mode
-
tweaks.resumeReloadsLive - reload live stream after resume
-
debug.playerLogs - enable dash.js logs
-
startupUrl.dash - automatically set this stream url on startup (for case of DASH protocol)
-
startupUrl.hls - automatically set this stream url on startup (for case of HLS protocol)
-
startupUrl.mss - automatically set this stream url on startup (for case of MSS protocol)
-
globalOpts - global options
-
streamOpts - stream options
More details
getChromecastMediaInfo(url, okCallback, errCallback) should call okCallback(info) on success and errCallback() in case of failure.
Format of info object:
{
type: 'episode', // 'film', 'channel'
url: 'https://stream-url',
title: 'media title',
subtitle: 'media subtitle', // for film and channel
seriesTitile: 'series title', // for episode
seriesSubtitile: 'series subtitle', // for episode
seasonNumber: 0, // for episode
episodeNumber: 0, // for episode
images: [
{
url: 'https://image-url-0',
width: 1920,
height: 1080
},
{
url: 'https://image-url-1',
width: 260,
height: 150
}
]
}
imageCallback(percent, url) should return url with jpeg image.
- percent - preview position in video
- url - currently playing stream
Stream options
{
autoplay: false,
continuePosition: 0,
endPosition: 0,
startOverPosition: 0,
externalSubtitles: {
url: null,
lang: 'und'
},
drmConfig: {
widevine: {
proxy_url: null
},
fairplay: {
certificate_url: null,
ksm_url: null,
ksm_protocol: null
},
playready: {
la_url: null
}
},
posterUrl: null,
adConfig: {
url: null,
getUrl: null,
preCount: 1,
resumeCount: 0,
midRoll: {
timeToFirst: NaN,
timeToNext: NaN,
count: 0,
subCount: 1
},
vmapUrl: null,
maxPrepareTime: 0,
proxyUrl: null
},
heartbeat: {
url: null,
interval: 4
},
metrics: {
apiHost: null,
apiUrl: null,
interval: 10,
params: {
application_id: null,
application_version: null,
user_type: null,
user_id: null,
resource_uid: null,
resource_type: null,
watch_session_id: null
}
}
}
-
autoplay - automatically start stream playing
-
continuePosition - stream position in seconds where "continue watching" button will seek
-
endPosition - stream position in seconds when "next video" popup will be shown (negative value means offset from video end)
-
startOverPosition - offset from the end of live stream to start-over time
-
externalSubtitles.url - url to srt subtitles in case of hds stream (unused, will be removed/repurposed)
-
externalSubtitles.lang - three-letter language code for subtitles
-
drmConfig.widevine.proxy_url - url of widevine proxy
-
drmConfig.fairplay.certificate_url - url with fairplay client certificate
-
drmConfig.fairplay.ksm_url - url of fairplay ksm
-
drmConfig.fairplay.ksm_protocol - protocol to use with ksm server (possible values: 'base64', 'binary')
-
drmConfig.playready.la_url - url of playready license server
-
posterUrl - url to image that will be used as poster before stream playback started
-
adConfig.url - url from where to download vast document for advertisement
-
adConfig.getUrl - callback function that will be used to get ads url when necessary. description below
-
adConfig.preCount - number of consecutive pre-roll ads (url will be requested each time)
-
adConfig.resumeCount - number of consecutive resume-roll ads
-
adConfig.midRoll.timeToFirst - time from start of video until first mid-roll in seconds
-
adConfig.midRoll.timeToNext - time between mid-rolls in seconds
-
adConfig.midRoll.count - number of mid-rolls
-
adConfig.midRoll.subCount - number of ads in one mid-roll
-
adConfig.vmapUrl - use vmap xml from this url
-
adConfig.maxPrepareTime - override default initial max prepare time (in seconds)
-
adConfig.proxyUrl - proxy prefix for media urls
-
heartbeat.url - base url for heartbeat (will be enriched with some parameters)
-
heartbeat.interval - interval in seconds between two consecuitive heartbeats
-
metrics.apiHost - hostname of metrics server
-
metrics.apiUrl - full url for metrics requests (have priority over apiHost)
-
metrics.interval - interval in seconds for sending periodic metrics updates
-
metrics.params - configurable data for api v2
More details
adConfig getUrl(params) should return url to vast.
params have the following members:
- width - container width
- height - container height
- index - index of ad in block
- type - 'preroll', 'resumeroll', 'midroll'
Examples
See *.html files in src directory.
Standalone Ads player
Need to include the following files:
- player.css
- ads_player.all.js
Entry point is function spbtvadsplayer(id, options).
Interfacing with ads player is similar to usual player.
Options
{
adInfo: true,
adNotification: 'Ads allow us to show this video legally and free',
topLine: null,
bottomLine: null,
minAdHeight: 225,
adjustFontSize: true,
precacheVAST: false,
initCountdown: true,
showDisableAds: false,
bufferingSpinner: true,
getUrl: null,
count: 1,
maxPrepareTime: 0,
proxyUrl: null,
audioVolume: -1,
autoplay: true,
autoPause: false,
autoResume: false,
assistedAutoplay: false,
debugLogs: false,
disableVPAID: false,
delayImpressions: false,
globalOpts: {
}
}
- audioVolume - try to change ad video volume. value from 0 to 1. -1 means default.
- assistedAutoplay - rely on externally-initiated play command instead of autoplay
Events
- adRequested
- adStarted
- adFinished
- adError
- adItemStarted
- adItemFinished
- adItemError
- adImpression
- adClick - user has clicked on advertisement
- disableAdsClick
- urlLoad - vpaid iframe loaded another url
- assistedAutoplay - fired instead of autoplaying vast contents if assistedAutoplay option is enabled
Android Ads player
params
{
url: null,
urlParams: {
replaceWidth: null,
replaceHeight: null
},
count: 1,
maxPrepareTime: 0,
proxyUrl: null,
audioVolume: -1,
showDisableAds: false,
bufferingSpinner: true,
assistedAutoplay: false,
disableVPAID: false,
sendLogEvents: false
}
- url - url to download ad
- urlParams.replaceWidth - string that will be found in url and replaced with ad player width
- urlParams.replaceHeight - string that will be found in url and replaced with ad player height
- count - number of ads to play
- maxPrepareTime
- proxyUrl
- audioVolume
- showDisableAds
- bufferingSpinner
- assistedAutoplay
- disableVPAID
- sendLogEvents - generate
playerLogevents for log messages