PlayerManager Module

Creates PlayerResource objects, which are used to load and configure video sources independent of a component. This method was created specifically when you want your application to render the same video player to multiple surfaces. This means that for any video, you can create a player and pass it around to multiple screens in your application. With the PlayerManager module, you can avoid the overhead of re-initializing the stream and the creation of many stream requests!

Note that a video player can render to only one surface at a time.

PlayerManager handles the lifecycle of your app’s player resources. A PlayerResource stores a unique internal tag that ties it to a native player resource. You can configure the native player resource, via the methods on a PlayerResource object. To render the video, you must use either a VideoSurface or a VideoSurfaceRef component, but the video player resource is not dependent on, nor affected by, these components.

The following methods are supported with the PlayerManager module:

The following properties are supported with the PlayerResource object:

The following methods are supported with the PlayerResource object:

Example

The following example shows PlayerManager in use with a VideoSurfaceRef. You can alternatively use VideoSurfaceRef instead.

import React from "react";
import { PlayerManager, VideoSurface } from "@youi/react-native-youi";
import { View } from "react-native";

// Each player resource must be created with a unique tag
const VIDEO_TAG = "UNIQUE_VIDEO_TAG";
const App = () => {
  const ref = React.useRef()
  const [resource, setResource] = React.useState(null)

  React.useEffect(()=>{
    // Ensure the resource exists
    let myPlayerResource = PlayerManager.create(VIDEO_TAG);
    setResource(myPlayerResource)
    return () => {
      // Frees the player resource
      // Automatically removes the `playing` listener that wasn't manually cleared
      PlayerManager.destroy(myPlayerResource.tag);
    }
  },[])

  React.useEffect(()=>{
    if (!ref.current || !resource) return;
    resource.loadSource({
      uri: 'https://bitdash-a.akamaihd.net/content/sintel/hls/playlist.m3u8',
      type: 'HLS'
    });
    // Ensure your code creates the resource BEFORE setting
    // the component's player to the resource's tag
    ref.current.setPlayer(VIDEO_TAG)
    let readyListener = resource.addEventListener('ready', () => {
      resource.play();
      readyListener.remove();
    });

    let playListener = resource.addEventListener('playing', () => {
      playListener.remove();
    });
  },[ref.current, resource])

  return (
    <VideoSurface
      style={{width:300, height:200}}
      ref={ref}
    />
  );
}

PlayerManager Methods

create

Creates a player resource native-side, and returns a JavaScript reference. Any configuration you need to do on the resource can be done on this returned reference. A string is supplied as a tag to the resource and uniquely identifies the native player resource.

Definition

create(resourceTag) -> PlayerResource

Parameters

Name Type Required Description
resourceTag string Yes Unique and non-empty string to identify the created player resource.

destroy

Destroys the native-side resource associated with the provided resourceTag, and the JavaScript-side reference is invalidated. Use of a player resource reference after destroy is called on it is a no-op.

Definition

destroy(resourceTag) -> void

Parameters

Name Type Required Description
resourceTag string Yes Unique and non-empty string to identify the target player resource.

get

Performs a lookup in the JavaScript references held by the PlayerManager that match the provided resource tag. If the resource doesn’t exist, null will be returned.

Definition

get(resourceTag) -> PlayerResource

Parameters

Name Type Required Description
resourceTag string Yes Unique and non-empty string to identify the target player resource.

PlayerResource Properties

tag

The internal tag of the resource you provided when you created it. The returned tag is used as a link to the native-side resource. When the PlayerManager destroys the resource, this tag is be cleared, since no native-side resource is tied to the reference anymore.

PlayerResource Methods

addEventListener

Adds a listener for player events. Returns a subscription object to clean up the listener.

Definition

addEventListener(eventName, listener) -> object

Parameters

Name Type Required Description
eventName string Yes PlayerEventName
listener function Yes Callback when the event is triggered.

PlayerEventName

Name Callback Parameter Description
audioBitrateChange {tag: string, bitrateKbps: float} Invoked when the audio bitrate has changed. May be emitted at any point. The supplied bitrate is in kbps.
availableAudioTracksChange {tag: string, tracks: [{id: number, name: string, language: string, valid: boolean}]} Signals that the available audio tracks for the current media have changed. May be emitted at any point.
availableClosedCaptionsTracksChange {tag: string, tracks: [{id: number, name: string, language: string}]} Signals that the available closed caption tracks for the current media have changed. May be emitted at any point.
bufferingEnd {tag: string} Invoked when player buffering has ended. An application can clear a buffering indicator, if one has been displayed, when this signal is emitted. The player is either in a playing or paused state depending on the state the player was in prior to buffering. Currently not supported for the Roku target platform.
bufferingStart {tag: string} Invoked when player buffering has started. An application can display a buffering indicator when this signal is emitted. Currently not supported for the Roku target platform.
currentTimeUpdate {tag: string, currentTime: number} Provides the current time of the video, in milliseconds. Emitted every 100ms by default, but this threshold can be configured using setCurrentTimeUpdateThreshold.
durationChange {tag: string, duration: number} Invoked when the duration of the loaded video media has changed. Typically occurs after loading new video media. The supplied duration is in milliseconds.
error {tag: string, error: {errorCode: string, nativePlayerErrorCode: string, message: string}} Invoked when the player reports an error. When using ExoPlayer with Android, the value for nativePlayerErrorCode will always be empty.
finalize {tag: string} Invoked once the player has shut down and been cleaned up. This signal is sent on stop(). However, in order for finalize to be triggered, the video player must be finished preparing.
pause {tag: string} Invoked when playback has paused.
playbackComplete {tag: string} Invoked when the playback of the currently loaded video media has completed. After this signal is emitted the player is in the paused state.
playing {tag: string} Invoked when playback has begun - either the initial playback or a resume after the paused or buffering states.
preparing {tag: string} Invoked when the player has started preparing a video for playback. Occurs only when the target platform supports the provided video format. Currently not supported for the Roku target platform.
ready {tag: string} Invoked when the native player is ready to be interacted with and information about the player can be queried. Currently not supported for the Roku target platform.
totalBitrateChange {tag: string, bitrateKbps: float} Invoked when the combined video and audio bitrate has changed. May be emitted at any point. The supplied bitrate is in kbps.
videoBitrateChange {tag: string, bitrateKbps: float} Invoked when the video bitrate has changed. May be emitted at any point. The supplied bitrate is in kbps.

getStatistics

Returns a promise with an object containing player statistics.

Notes

  • Currently not supported for the Roku target platform.

Definition

getStatistics() -> Promise<Object>

Returns

Data Type
audioBitrateKbps number
bufferLengthMs number
defaultAudioBitrateKbps number
defaultTotalBitrateKbps number
defaultVideoBitrateKbps number
framesPerSecond number
isLive boolean
minimumBufferLengthMs number
totalBitrateKbps number
videoBitrateKbps number

loadSource

Load either a remote URL or a local file resource.

Definition

loadSource(src) -> void

Parameters

Name Type Required Description
src {type: string, uri: Object, headers: Object, drmScheme: string, drmInfo: Object} Yes Video source to load.

drmScheme and drmInfo

drmScheme drmInfo Type Notes
fairplay null See FairPlayDRMHandler Module
istreamplanet_fairplay null  
none null This is the default.
playready string  
widevine_modular {licenseAcquisitionUrl: string, headers: Array<{ key: string, value: string }> }  
widevine_modular_custom_request {licenseAcquisitionUrl: string, headers: Array<{ key: string, value: string }> } See WidevineCustomRequestDRMHandler Module

pause

Pauses video playback.

Definition

pause() -> void

play

Starts playback of the native player, or resumes if the player is paused. The video must be in the ready state first.

Definition

play() -> void

removeAllListeners

Removes all listeners for the player resource or, optionally, all the listeners for a given event on a player resource.

Definition

removeAllListeners(eventName?) -> void

Parameters

Name Type Required Description
eventName string No PlayerEventName. If provided, all listeners registered for this event on the resource will be removed.

removeEventListener

Removes a listener for a player event.

Definition

removeEventListener(eventName, listener) -> void

Parameters

Name Type Required Description
eventName string Yes PlayerEventName
listener function Yes Callback to remove. Must be registered for the event name provided.

seek

Seeks the video to a specific position in the video media.

Returns a promise object. If the seek operation is successful, the returned promise will include the new stream position, in milliseconds. If the seek operation fails, the promise rejection will include the current stream position, in milliseconds.

Notes

  • The video must be in the ready state before calling seek.
  • When seeking backwards from playback complete, the player must remain paused.

Definition

seek(positionInMs) -> Promise<number>

Parameters

Name Type Required Description
seek number Yes The desired stream position, in milliseconds.

setBufferLength

Customize the video playback buffer length.

Notes

  • Currently supported for Android.
  • Set the buffer length before calling loadSource. Otherwise, setting the buffer length has no effect on current playback.

Definition

setBufferLength(bufferLength) -> void

Parameters

Name Type Required Description
bufferLength {min: number, max: number} Yes min: The minimum buffer length, in milliseconds. The video player will not let the buffer length fall below this value.
max: The maximum buffer length, in milliseconds. The video player will not let the buffer length exceed this value.

setMaxBitrate

Sets the maximum bitrate to the number specified, in bits per second. The player then uses this value when streaming from an adaptive media source. By default, no bitrate restriction is applied.

Notes

  • If maxBitrate is set during playback, it won’t take effect until content that’s already been buffered has played back.
  • Setting maxBitrate to 0 removes any bitrate restrictions.
  • For Tizen, maxBitrate must be set before preparing the media.
  • Currently not supported for Roku. For Roku, set the MaxBandwidth metadata attribute before preparing media and starting playback.

Definition

setMaxBitrate(bitsPerSecond) -> void

Parameters

Name Type Required Description
bitsPerSecond number Yes The maximum bitrate, in bits per second.

setCurrentTimeUpdateThreshold

Sets how often the player event currentTimeUpdate is fired. The default threshold is 100ms.

Note: This method sets the minimum threshold. The actual time between updates may be greater depending on the underlying player.

Definition

setCurrentTimeUpdateThreshold(currentTimeUpdateThreshold) -> void

Parameters

Name Type Required Description
currentTimeUpdateThreshold number Yes How often the event currentTimeUpdate should be fired, in milliseconds.

setMuted

Configures the muted property of the video. Defaults to false.

Definition

setMuted(isMuted) -> void

Parameters

Name Type Required Description
isMuted boolean No True if the video should be muted.

setSelectedAudioTrack

Switches the video player’s audio to the track indicated by the given ID. If the video is playing, playback will not be stopped during the switch.

Definition

setSelectedAudioTrack(id) -> void

Parameters

Name Type Required Description
id number Yes The ID of the desired audio track.

setSelectedClosedCaptionsTrack

Switches the video player’s Closed Captions to the track indicated by the given ID. If the video is playing, playback will not be stopped during the switch.

Definition

setSelectedClosedCaptionsTrack(id) -> void

Parameters

Name Type Required Description
id number No The ID of the desired Closed Captions track. Omitting the ID or passing null disables closed captioning.

setStartTime

Configures the start time of the video stream, in milliseconds. By default, VOD starts at 0 and a live stream starts from the live head. This should be set before loadSource is called.

Definition

setStartTime(millis) -> void

Parameters

Name Type Required Description
millis number Yes Start time of the video, in milliseconds.

setUserAgent

Sets the User Agent to be used by the player for requests on manifests and video segments.

Notes

  • Currently supported for Android, PS4, Roku Cloud Solution, and XBox One.
  • Set the User Agent before calling loadSource. Otherwise, setting the User Agent has no effect on current playback.
  • To reset to default, set the user agent to an empty string (""). The default User Agent varies per platform.

Limitations for Roku Cloud Solution

  • Once a custom User Agent header is set, the Roku native player caches it and uses it for all video requests. Once the device has been powered off or the app has been reinstalled, the default User Agent header is restored, until you set a custom value again. You can replace one custom User Agent header with another between videos, but it’s not possible to revert to the default header unless the device is powered off or the app is reinstalled.
  • For some videos, the initial request uses the custom header, but segment fetches use the default. There is currently no workaround for this issue.

Definition

setUserAgent(userAgent) -> void

Parameters

Name Type Required Description
userAgent string Yes The User Agent.

stop

Stops video playback. Allows users to switch between multiple videos and to unload media.

Definition

stop() -> void