# PRESTOplay for Web Apps 6.37.0 API reference

PRESTOplay for Web Apps is the HTML5 video player SDK by Castlabs. It plays DASH, HLS and Smooth Streaming with Widevine, PlayReady and FairPlay DRM in browsers, on smart TVs and on Chromecast.

The manual has guides for DRM, ads, smart TVs and the components; its plain-text index for LLMs is https://docs.castlabs.com/prestoplay/web/llms.txt and its full text https://docs.castlabs.com/prestoplay/web/llms-full.txt.

Links to other API entries are written as their long names, e.g. `clpp.Player#open` for the instance method `open` of `clpp.Player`. Every API page below starts with a heading of that name.

## Install

Install the SDK from NPM (https://www.npmjs.com/package/@castlabs/prestoplay):

```sh
npm install @castlabs/prestoplay@6.37.0
```

Everything is in the `clpp` namespace. Features are split into components which must be imported before the player is created, e.g. `@castlabs/prestoplay/cl.mse` for MSE playback, `@castlabs/prestoplay/cl.dash` for DASH and `@castlabs/prestoplay/cl.hls` for HLS. A player without the component for a stream cannot play it.

```js
import { clpp } from '@castlabs/prestoplay';
import '@castlabs/prestoplay/cl.mse';
import '@castlabs/prestoplay/cl.dash';

const player = new clpp.Player('video', { license: '<license key>' });
player.on(clpp.events.ERROR, e => console.error(e.detail));
await player.open({ source: 'https://example.com/manifest.mpd', autoplay: true });
```

The stylesheet of the player is `@castlabs/prestoplay/clpp.styles.css` and the TypeScript declarations ship with the package as `typings.d.ts`. The getting started guide of the manual for LLMs is https://docs.castlabs.com/prestoplay/web/getting-started.txt.

## clpp (namespace)

The primary namespace.

### Static properties

#### clpp.version

Type: `string`

The version of the SDK.

#### clpp.name

Type: `string`

The SDK name.

### Static methods

#### clpp.configure

```ts
configure(configuration: clpp.SdkConfiguration)
```

Set global SDK configuration.

Parameters:

- `configuration` (`clpp.SdkConfiguration`): The SDK configuration that applies to all players.

#### clpp.install

```ts
install(component: function)
```

Install a component in order to extend player capabilities.

Make sure to call this function before creating any instances of `clpp.Player`, ideally at the beginning of the script, otherwise it may not work as expected.

Components can be uninstalled using `clpp.uninstall`.

Parameters:

- `component` (`function`): Component constructor.

Example:

```js
// Install HLS
clpp.install(clpp.hls.HlsComponent);
// Install DASH
clpp.install(clpp.dash.DashComponent);

// The player now has the capability to play HLS and DASH content.
const player = new clpp.Player(...);
player.open(...);
```

#### clpp.uninstall

```ts
uninstall(component: function)
```

Uninstall a component in order to take away player capabilities.

It is recommended to never call this function, unless you have a specific need to disable some component and take away the corresponding player capabilities.

If you want to call this function, make sure to do so after destroying all instances of `clpp.Player`, otherwise it may not work as expected.

Components can be installed using `clpp.install`.

Parameters:

- `component` (`function`): Component constructor

Example:

```js
player1.destroy();

// Uninstall HLS
clpp.uninstall(clpp.hls.HlsComponent);

// player2 no longer has the capability to play HLS content.
const player2 = new clpp.Player(...);
player2.open(...);
```

## clpp.Player (class)

Extends: `clpp.EventTarget`. Inherited members are documented there.

Constructor:

```ts
new clpp.Player(element: HTMLMediaElement | string, opt_configuration?: clpp.ConstructorPlayerConfiguration, opt_viewConfiguration?: clpp.PlayerSurfaceConfiguration)
```

The Castlabs player.

Configure the player with `clpp.ConstructorPlayerConfiguration`, pass it the Castlabs license key and any other configurations which will be applied to all playback sessions.

Specify video element and its parent container element.

Parameters:

- `element` (`HTMLMediaElement | string`): The media element or the ID of the media element.
- `opt_configuration` (`clpp.ConstructorPlayerConfiguration`, optional): The global player configuration. It must not contain the `source` attribute.
- `opt_viewConfiguration` (`clpp.PlayerSurfaceConfiguration`, optional): The global player view configuration.

Throws:

- `clpp.Error` with different codes

  - `clpp.Error.Code.NO_ELEMENT` if no element is provided
  - `clpp.Error.Code.INVALID_LICENSE` if no license was provided in the configuration. **Note** that this does not check the license for validity yet. The license validation is an async process and you must make sure that you attach an error listener to the player instance as early as possible to get a callback about the invalid license.

Example: Create the player and pass it initial configuration.

```js
const videoEl = document.getElementById('video');
const containerEl = videoEl.parentElement;
const player = new clpp.Player(videoEl, {
   license: '[your_license_key]',
   viewerId: '[viewer_id]'
}, { containerEl });
```

### Static methods

#### clpp.Player.registerPlugin

```ts
registerPlugin(factory: clpp.PlayerPluginFactory)
```

Registers a player plugin factory.

Parameters:

- `factory` (`clpp.PlayerPluginFactory`): The player plugin factory.

### Methods

#### clpp.Player#addEventListener

```ts
addEventListener(type: string, listener: clpp.EventCallback)
```

Register an event listener. You can listen to PRESTOplay events as well as HTMLMediaElement events coming from the underlying video or audio element.

Parameters:

- `type` (`string`): The event name.
- `listener` (`clpp.EventCallback`): The callback function.

Example: Listen to PRESTOplay buffering event.

```js
player.addEventListener(clpp.events.BUFFERING_STARTED, callback);
```

Example: Listen to HTMLMediaElement time update event.

```js
player.addEventListener('timeupdate', callback);
```

#### clpp.Player#on

```ts
on(name: string, callback: clpp.EventCallback, opt_callbackScope?: Record<string, unknown>): clpp.EventCallback
```

Adds an event listener for the given event. Optionally, scope can be passed in, in which case the callback function will be bound/executed in the given scope.

This method returns a reference to the callback for convenient removal of the listener via `off()` (`clpp.Player#off`).

Parameters:

- `name` (`string`): The event name.
- `callback` (`clpp.EventCallback`): The callback function.
- `opt_callbackScope` (`Record<string, unknown>`, optional): Optional callback scope.

Returns: `clpp.EventCallback` - The callback function.

Example: Listen to state change (PRESTOPlay player event)

```js
const listener = player.on(clpp.events.STATE_CHANGED, event => {
    const state = event.detail.currentState;
    const previousState = event.detail.previousState;
    // ...
  });
  // ...
  player.off(clpp.events.STATE_CHANGED, listener);
```

Example: Listen to timeupdate (HTML5 media event)

```js
const listener = player.on('timeupdate', () => {
     // ...
  });
  // ...
  player.off('timeupdate', listener);
```

#### clpp.Player#one

```ts
one(name: string, callback: clpp.EventCallback, opt_callbackScope?: Record<string, unknown>): clpp.EventCallback
```

Adds a one time event listener for the given event. The listener will be removed once the event was triggered. Otherwise it works the same as `on()` (`clpp.Player#on`).

Parameters:

- `name` (`string`): The event name.
- `callback` (`clpp.EventCallback`): The callback function.
- `opt_callbackScope` (`Record<string, unknown>`, optional): Optional callback scope.

Returns: `clpp.EventCallback` - The callback function.

Example: Listen to fist timeupdate (HTML5 media event)

```js
const listener = player.one('timeupdate', () => {
     // first timeupdate
  });
```

#### clpp.Player#off

```ts
off(name: string, callback: clpp.EventCallback): boolean
```

Remove an event listener.

Parameters:

- `name` (`string`): The event name.
- `callback` (`clpp.EventCallback`): The callback function.

Returns: `boolean` - True if the listener was removed.

Example: Remove a listener

```js
const listener = player.on(clpp.events.STATE_CHANGED, () => {});
  ...
  player.off(clpp.events.STATE_CHANGED, listener);
```

#### clpp.Player#removeEventListener

```ts
removeEventListener(type: string, listener: clpp.EventCallback)
```

Remove an event listener.

Parameters:

- `type` (`string`): The event name.
- `listener` (`clpp.EventCallback`): The callback function.

Example: Remove listener to PRESTOplay buffering event.

```js
player.removeEventListener(clpp.events.BUFFERING_STARTED, callback);
```

Example: Remove listener to HTMLMediaElement time update event.

```js
player.removeEventListener('timeupdate', callback);
```

#### clpp.Player#getPlugin

```ts
getPlugin(id: string): clpp.PlayerPlugin | null
```

Get player plugin by ID.

Parameters:

- `id` (`string`): The ID of the plugin.

Returns: `clpp.PlayerPlugin | null` - The player plugin that was registered with the given ID or null if not found.

#### clpp.Player#getSurface

```ts
getSurface(): clpp.IPlayerSurface
```

Get the player surface. Player surface is the underlying media element plus its container.

Returns: `clpp.IPlayerSurface` - The player surface.

#### clpp.Player#getConfiguration

```ts
getConfiguration(): clpp.PlayerConfiguration
```

Get the player configuration.

Returns: `clpp.PlayerConfiguration` - The player configuration.

#### clpp.Player#getDrmInfo

```ts
getDrmInfo(): clpp.DrmInfo | null
```

Get the DRM info for the currently loaded source.

Returns: `clpp.DrmInfo | null` - The DRM info of the currently loaded source or null if player is idle.

#### clpp.Player#release

```ts
release(): Promise<void>
```

Release resources held by the player. The player can load another source after it was released.

The player automatically calls release under the hood on every `open()` (`clpp.Player#open`).

Returns: `Promise<void>` - A promise that resolved once all resources of the player are released.

#### clpp.Player#stop

```ts
stop(): Promise<void>
```

Stop the player.

Returns: `Promise<void>` - A promise that resolves when the player is stopped.

#### clpp.Player#destroy

```ts
destroy(): Promise<void>
```

Destroy the player. It will not be usable after it is destroyed.

Returns: `Promise<void>` - A promise that resolves once the player is fully destroyed.

#### clpp.Player#open

```ts
open(configuration: string | clpp.Source | Array<string> | Array<clpp.Source> | clpp.PlayerConfiguration): Promise<void>
```

Load a stream.

You may load content by passing a `string`, a `clpp.Source`, an array of sources or player configuration. In case of player configuration it must not contain the `license` attribute.

If multiple sources are passed to the `open` method, the player will play the first source which is playable on that platform. Please refer to the examples below for more details.

If the player is already playing another source, it will release itself first before loading the new source.

Parameters:

- `configuration` (`string | clpp.Source | Array<string> | Array<clpp.Source> | clpp.PlayerConfiguration`): The URL, source, list of sources or player configuration describing the content to load.

Returns: `Promise<void>` - A promise that resolves when the content is loaded, or rejects with a `clpp.Error` if loading fails.

Example: Passing a string

```js
player.open('http://example.com/manifest.mpd');
```

Example: Passing a clpp.Source object

```js
player.open({
  url: 'http://example.com/manifest.mpd',
  type: clpp.Type.DASH
});
```

Example: Passing an array

```js
player.open([
  // By passing an array, player will load first content that it is able
  // to load on given platform (i.e. we cannot load protected DASH on
  // Safari). You can mix strings and clpp.Source objects here.
  {
    url: 'http://example.com/manifest.mpd',
    type: clpp.Type.DASH,
    drmProtected: true
  },
  {
    url: 'http://example.com/manifest.m3u8',
    type: clpp.Type.HLS,
    drmProtected: true
  },
  'http://example.com/other.mp4'
]);
```

Example: Passing configuration

```js
player.open({
  // under source prop you may pass your manifest URL in all possible ways
  // as before: string, clpp.Source object or array of strings /
  // clpp.Source objects.
  source: 'http://example.com/manifest.mpd',

  // Other configuration options. Passing them allows to extend/modify
  // initial configuration passed during player's initialization.
  startTime: 4,
  preferredTextLanguage: 'en'
});
```

#### clpp.Player#play

```ts
play(): Promise<void>
```

Start playback.

The `autoplay` (`clpp.BasePlayerConfiguration#autoplay`) option may be used to configure the player to automatically start playback after `open()` (`clpp.Player#open`).

Returns: `Promise<void>` - A promise that resolves if starting playback was successful.

Throws:

- `clpp.Error` When the call is blocked by browser [autoplay policies](https://developer.mozilla.org/en-US/docs/Web/Media/Guides/Autoplay).

#### clpp.Player#pause

```ts
pause(): Promise<unknown>
```

Pause playback.

Returns: `Promise<unknown>` - A promise that resolves if pausing playback was successful.

#### clpp.Player#getTrackManager

```ts
getTrackManager(): clpp.TrackManager | null
```

Returns the track manager.

Returns: `clpp.TrackManager | null` - Track manager or `null` if doesn't exist yet.

#### clpp.Player#getBufferInfo

```ts
getBufferInfo(opt_type?: clpp.Track.Type | string): clpp.BufferInfo
```

Get info about buffered time ranges.

Parameters:

- `opt_type` (`clpp.Track.Type | string`, optional): Optional track type. If provided and supported by the platform, this returns the buffer info for the given track type. If this is not supported by the platform, the total time range will be returned instead.

Returns: `clpp.BufferInfo` - The current buffered time ranges.

#### clpp.Player#getState

```ts
getState(): clpp.Player.State
```

Gets player/playback state.

Returns: `clpp.Player.State` - Current state of the player.

#### clpp.Player#getPlaybackState

```ts
getPlaybackState(): clpp.PlayerState
```

Gets internal player/playback state.

Warning: This method exposes the common API player state model, but it is not yet fully functional across all PRESTOplay SDK components. Use `clpp.Player#getState` and `clpp.Player.State` instead.

Returns: `clpp.PlayerState` - Current internal state of the player.

#### clpp.Player#isEnded

```ts
isEnded(): boolean
```

Returns true if playback ended, false otherwise.

Returns: `boolean` - True if playback reached the end of the content.

#### clpp.Player#isPaused

```ts
isPaused(): boolean
```

Returns true if playback is paused, false otherwise.

Returns: `boolean` - True if playback (or the currently playing ad) is paused.

#### clpp.Player#getPosition

```ts
getPosition(): number
```

Get current playhead position in seconds.

Returns: `number` - The current playhead position in seconds.

#### clpp.Player#setPosition

```ts
setPosition(time: number): Promise<void>
```

Set player position in seconds.

To get seekable range call `getSeekRange()` (`clpp.Player#getSeekRange`).

Parameters:

- `time` (`number`): The time in seconds to seek to.

Returns: `Promise<void>` - A promise that resolves when the seek is done, or rejects if the player cannot seek in its current state.

#### clpp.Player#getPresentationStartTime

```ts
getPresentationStartTime(): number | null
```

Gets the presentation start time. Returns the presentation start time in UNIX Epoch time (seconds elapsed since the Unix epoch) or `null` if the stream is not live or the presentation start time is not available.

This value should be consistent with the live DASH stream's `MPD@availabilityStartTime`, or in the case of HLS, values calculated if the [EXT-X-PROGRAM-DATE-TIME](https://datatracker.ietf.org/doc/html/rfc8216#section-4.3.2.6) tag is present in the playlist.

*Note:* Unix time is a date and time representation. It measures time by the number of seconds that have elapsed since 00:00:00 UTC on 1 January 1970, the Unix epoch, without adjustments made due to leap seconds. More information can be found on [Unix time - Wikipedia](https://en.wikipedia.org/wiki/Unix_time).

Returns: `number | null` - The presentation start time in UNIX Epoch time (seconds elapsed since the Unix epoch) or `null` if the stream is not live or the presentation start time is not available.

#### clpp.Player#getSeekRange

```ts
getSeekRange(): clpp.SeekRange
```

Gets the time range (in seconds) where it is allowed to seek. If the player has not loaded content, this will return a range from 0 to 0.

Returns: `clpp.SeekRange` - The seekable range with `start` and `end` in seconds.

#### clpp.Player#getTimelineOffset

```ts
getTimelineOffset(): clpp.TimelineOffset | null
```

Returns the timeline offset for live HLS streams when MSE Player is used. The timeline offset is based on the value of the EXT-X-PROGRAM-DATE-TIME tag.

Returns: `clpp.TimelineOffset | null` - timeline offset in case of a live HLS stream played with the MSE Player if the playlist contains the EXT-X-PROGRAM-DATE-TIME tag, otherwise null.

#### clpp.Player#getVolume

```ts
getVolume(): number | null
```

Get the current volume level.

On Tizen the `http://tizen.org/privilege/tv.audio` privilege needs to be enabled in order to control volume.

Returns: `number | null` - The current volume level.

#### clpp.Player#setVolume

```ts
setVolume(volume: number)
```

Change the audio volume level.

Use `volume` (`clpp.BasePlayerConfiguration#volume`) configuration to configure the initial volume level.

On Tizen the `http://tizen.org/privilege/tv.audio` privilege needs to be enabled in order to control volume.

On iOS this has no effect, volume is controlled on system level.

Parameters:

- `volume` (`number`): A value between 0 and 1.

#### clpp.Player#getDuration

```ts
getDuration(): number
```

Get content duration in seconds.

Returns: `number` - The duration of the loaded content in seconds or -1 if the player is idle. For live streams the duration is `Infinity`.

#### clpp.Player#getAdsManager

```ts
getAdsManager(): clpp.ads.IAdsManager | null
```

Get the ads manager.

The ads manager is available after `open()` (`clpp.Player#open`) is resolved.

Returns: `clpp.ads.IAdsManager | null` - The ads manager or null if not available.

#### clpp.Player#namespace

```ts
namespace(): string
```

Returns player ID.

Returns: `string` - The name of the player.

#### clpp.Player#isPlayingAd

```ts
isPlayingAd(): boolean
```

Returns true if the current content being displayed is an ad.

Returns: `boolean` - True if an ad is playing.

#### clpp.Player#getRate

```ts
getRate(): number
```

Get speed of the playback, as a multiple of normal speed. 1 means normal speed, 2 means double speed etc.

Returns: `number` - The speed at which the video is being played.

#### clpp.Player#setRate

```ts
setRate(rate: number, opt_mode?: clpp.SpeedUpMode)
```

Set playback speed.

Parameters:

- `rate` (`number`): The playback rate.
- `opt_mode` (`clpp.SpeedUpMode`, optional): The speed-up mode to use during trick play. Only works with MSE player.

Example: Play at double speed.

```js
player.setRate(2);
```

Example: Play at half speed.

```js
player.setRate(0.5);
```

Example: Play at normal speed.

```js
player.setRate(1);
```

Example: Play at double speed backwards.

```js
player.setRate(-2);
```

Example: Play at double speed, using seek mode.

```js
player.setRate(2, clpp.SpeedUpMode.SEEK);
```

#### clpp.Player#isMuted

```ts
isMuted(): boolean
```

Returns true if the audio is muted.

On Tizen the `http://tizen.org/privilege/tv.audio` privilege needs to be enabled in order to control volume.

Returns: `boolean` - True if audio is muted, false if not.

#### clpp.Player#setMuted

```ts
setMuted(muted: boolean)
```

Mute and unmute the player.

Use `muted` (`clpp.BasePlayerConfiguration#muted`) configuration to configure the initial muted state.

On Tizen the `http://tizen.org/privilege/tv.audio` privilege needs to be enabled in order to control volume.

Parameters:

- `muted` (`boolean`): True to mute the player, false to unmute.

#### clpp.Player#getNetworkEngine

```ts
getNetworkEngine(): clpp.net.NetworkEngine
```

Get the network engine.

Returns: `clpp.net.NetworkEngine` - The network engine used by this player to make requests.

#### clpp.Player#setNetworkEngine

```ts
setNetworkEngine(engine: clpp.net.NetworkEngine)
```

Set the network engine.

Parameters:

- `engine` (`clpp.net.NetworkEngine`): The network engine.

#### clpp.Player#getTextDisplayer

```ts
getTextDisplayer(): clpp.ITextDisplayer | null
```

Get the text displayer.

Returns: `clpp.ITextDisplayer | null` - The text displayer rendering subtitles, or `null` if the player has not been initialized.

#### clpp.Player#isLive

```ts
isLive(): boolean
```

Returns true for live presentations. False for VOD.

Returns: `boolean` - True if the loaded content is a live stream.

#### clpp.Player#getStats

```ts
getStats(): clpp.Stats | null
```

Returns statistics and information about the current state of the player.

Returns: `clpp.Stats | null` - The playback statistics, or `null` if no content is loaded.

#### clpp.Player#getSources

```ts
getSources(): Array<clpp.Source> | null
```

Current sources.

Returns: `Array<clpp.Source> | null` - Sources passed to `open()` (`clpp.Player#open`).

#### clpp.Player#getCurrentSource

```ts
getCurrentSource(): clpp.Source | null
```

Get the source loaded by the player.

Returns: `clpp.Source | null` - Loaded source or null if player is idle.

#### clpp.Player#getEffectiveUrl

```ts
getEffectiveUrl(): string | null
```

Get the effective URL which the stream is loaded from.

It is the URL of the current source, unless it was changed by a plugin or by a redirect of the manifest request or by other means in which case it returns the new value. Every change is announced by the `EFFECTIVE_URL_CHANGED` (`clpp.events#EFFECTIVE_URL_CHANGED`) event.

Redirects are only detected by MSE player.

Returns: `string | null` - The effective URL, or null if no stream is loaded.

#### clpp.Player#getTimelineCues

```ts
getTimelineCues(): Array<clpp.TimelineCue>
```

Returns an array of timeline cues.

Returns: `Array<clpp.TimelineCue>` - The timeline cues (e.g. DASH events, HLS date ranges) of the loaded content, or an empty array if no content is loaded.

#### clpp.Player#resetAbr

```ts
resetAbr()
```

Reset the ABR history and switch again to automatically selected bandwidth/quality.

#### clpp.Player#setDrmCustomDataModifier

```ts
setDrmCustomDataModifier(modifier: function)
```

Sets a modifier for DRM custom data.

This modifier can be used to enable AirPlay of DRM-protected streams with upfront authorization tokens where it is necessary to generate and provide a new auth token for the AirPlay session.

The AirPlay plugin must be enabled, otherwise the modifier callback won't trigger at all.

Parameters:

- `modifier` (`function`): The callback which can adjust DRM custom data before the upcoming license acquisition.

Example: Generate a new upfront auth token for AirPlay session

```js
player.setDrmCustomDataModifier(async customData => {
  customData.authToken = await generateNewAuthToken();
});
```

#### clpp.Player#setCdnErrorCallback

```ts
setCdnErrorCallback(callback: function | null)
```

**Applies to:** mse

Sets the CDN error callback.

The callback is triggered when network error occurs during trying to download a segment or manifest. If player cannot download a segment or a manifest several times (according to attempt parameters specified in configuration) this callback can be used to provide an alternative manifest to silently switch to it. CDN error callback currently works for MSE playback, thus cannot be used for HLS on Safari.

Parameters:

- `callback` (`function | null`): A function that receives the failing manifest URL and the error, and resolves to an alternative manifest URL. Pass `null` to remove a previously set callback.

Example: Supply fallback manifest URL

```js
player.setCdnErrorCallback(async (manifest, error) => {
  if (error.code === clpp.Error.Code.TIMEOUT) {
    // Custom business logic.
    const newUrl = await findAnAlternative(manifest);
    return newUrl;
  }
});
```

#### clpp.Player#load

```ts
load(configuration: string | clpp.Source | Array<string> | Array<clpp.Source> | clpp.PlayerConfiguration): Promise<void>
```

**Deprecated.** Use `clpp.Player#open` instead.

Tell the player to load given content.

Parameters:

- `configuration` (`string | clpp.Source | Array<string> | Array<clpp.Source> | clpp.PlayerConfiguration`): The URL, source, list of sources or player configuration describing the content to load.

Returns: `Promise<void>` - A promise that resolves when the content is loaded.

#### clpp.Player#use

```ts
use(component: function)
```

**Deprecated.** Use `clpp.install` instead.

Registers specified component to player in order to extend its capabilities.

Note that this method may not work correctly in combination with multiple instances of `clpp.Player`. For that scenario please use `clpp.install` instead.

Parameters:

- `component` (`function`): Component constructor

Example:

```js
const player = new clpp.Player(...);
player.use(clpp.smooth.SmoothComponent);
// The player can now play Smooth Streaming content
```

#### clpp.Player#remove

```ts
remove(component: function): boolean
```

**Deprecated.** Use `clpp.uninstall` instead.

Removes a specified component from the player.

Please note that this operation will only run if the player has been released or is in IDLE state.

Note that this method may not work correctly in combination with multiple instances of `clpp.Player`. For that scenario please use `clpp.uninstall` instead.

Parameters:

- `component` (`function`): Component constructor

Returns: `boolean` - Return true if the component was successfully removed, otherwise false.

Example:

```js
const player = new clpp.Player(...);
player.use(clpp.smooth.SmoothComponent);
player.open('https://example.com/smooth/Manifest');
...
player.release().then(function () {
  player.remove(clpp.smooth.SmoothComponent);
  player.use(clpp.dash.DashComponent);
  player.open('https://example/dash/manifest.mpd');
});
```

#### clpp.Player#getPlayerState

```ts
getPlayerState(): clpp.PlayerState
```

**Deprecated.** Use `clpp.Player#getPlaybackState` instead.

Gets internal player/playback state.

Warning: This method exposes the common API player state model, but it is not yet fully functional across all PRESTOplay SDK components. Use `clpp.Player#getState` and `clpp.Player.State` instead.

Returns: `clpp.PlayerState` - Current internal state of the player.

#### clpp.Player#seek

```ts
seek(time: number): Promise<void>
```

**Deprecated.** Use `clpp.Player#setPosition` instead.

Seeks to a position in seconds.

Parameters:

- `time` (`number`): The time in seconds to seek to

Returns: `Promise<void>` - A promise that resolves when the seek is done.

#### clpp.Player#getPlaybackRate

```ts
getPlaybackRate(): number
```

**Deprecated.** use `getRate` instead.

Returns the playback speed.

Returns: `number` - the speed which the video is being played

#### clpp.Player#setPlaybackRate

```ts
setPlaybackRate(rate: number, opt_mode?: clpp.SpeedUpMode)
```

**Deprecated.** Use `setRate` instead.

Set playback speed.

Parameters:

- `rate` (`number`): The rate
- `opt_mode` (`clpp.SpeedUpMode`, optional): The speedUpMode to use during trick play

#### clpp.Player#getLoadedSource

```ts
getLoadedSource(): clpp.Source | null
```

**Deprecated.** use `clpp.Player#getCurrentSource` instead.

Returns source loaded by player.

Returns: `clpp.Source | null` - Loaded source.

## clpp.PlayerConfiguration (typedef)

Extends: `clpp.BasePlayerConfiguration`. Inherited members are documented there.

Configuration for playback of a specific source, typically these are settings for DRM, remote text tracks, thumbnails or ads.

Properties:

- `source` (`clpp.Source | string | Array<clpp.Source> | Array<string>`): Video or audio source file.

## clpp.BasePlayerConfiguration (typedef)

The configuration properties shared by both `clpp.PlayerConfiguration` and `clpp.ConstructorPlayerConfiguration`.

Properties:

- `id` (`string`, optional): A unique ID is required for `ScPlaylist` (`clpp.playlist.ScPlaylist`).
- `autoplay` (`boolean`, optional), default `false`: If true, playback starts automatically on `open()` (`clpp.Player#open`), if false `open()` (`clpp.Player#open`) loads the source and keeps it paused. Use this instead of the HTML [autoplay](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/autoplay) attribute.

  Before configuring this please make sure you are familiar with browser [autoplay policies](https://developer.mozilla.org/en-US/docs/Web/Media/Guides/Autoplay) which might block autoplay in order to improve user experience.
- `pauseWhenInBackground` (`boolean`, optional), default `false`: On smart TVs if true, playback will pause when the application goes into background. Playback will resume again when the application goes into foreground.
- `enableHtmlCue` (`boolean`, optional), default `true`: Enable custom HTML-based renderer for subtitles with rich support for subtitle formats. The `cl.htmlcue.js` module must be loaded for this to take effect. HTML-based renderer works on all platforms except for iOS where only native rendering of subtitles is supported due to browser limitations.

  When disabled native browser API is used for rendering of subtitles which may have limited support for subtitle formats and styling.

  Related: `htmlcue` (`clpp.BasePlayerConfiguration#htmlcue`), `hlssmpte` (`clpp.BasePlayerConfiguration#hlssmpte`), `textStyle` (`clpp.BasePlayerConfiguration#textStyle`), `remoteTextTracks` (`clpp.BasePlayerConfiguration#remoteTextTracks`), `ttml` (`clpp.BasePlayerConfiguration#ttml`).
- `lowLatencyMode` (`boolean`, optional), default `false`: **Applies to:** mse Enable low-latency mode to optimize for fast startup, low latency and playback on the live edge for low-latency-enabled streams.

  This is an experimental feature.
- `preferredAudioLanguage` (`string | Array<string>`, optional): Language code of the preferred audio track language.

  Pass in an array to define fallback language codes.
- `preferredTextLanguage` (`string | Array<string>`, optional): Language code of the preferred text track language.

  Pass in an array to define fallback language codes.
- `preferredAudioRole` (`string`, optional), default `"main"`: In DASH configure the role (urn:mpeg:dash:role:2011) to auto-select audio tracks by.
- `preferredTextRole` (`string`, optional): In DASH configure the role (urn:mpeg:dash:role:2011) to auto-select text tracks by.
- `preferredAudioChannelCount` (`number`, optional), default `2`: **Applies to:** mse The preferred number of audio channels.
- `preferredAudioCodec` (`string | Array<string>`, optional): **Applies to:** mse The preferred audio codecs in case multiple encodings are available in the manifest.

  By default the most efficient codecs are selected based on bandwidth. Use this option to override the default selection.

  The selection is based on prefix match on the base codec name (e.g. 'mp4a').

  Pass in an array of preferred codecs to define fallback options in order of preference (e.g. `['opus', 'mp4a']`).
- `preferredVideoCodec` (`string | Array<string>`, optional): **Applies to:** mse The preferred video codecs in case multiple encodings are available in the manifest.

  By default the most efficient codecs are selected based on bandwidth. Use this option to override the default selection.

  The selection is based on prefix match on the base codec name (e.g. 'avc1').

  Pass in an array of preferred codecs to define fallback options in order of preference (e.g. `['hvc1', 'vp9']`).
- `preferSpatialAudio` (`boolean`, optional), default `false`: **Applies to:** mse Enable to prefer spatial audio tracks in automatic track selection.
- `preferForcedSubtitles` (`boolean`, optional), default `false`: **Deprecated.** Enable to prefer forced text tracks in automatic track selection.
- `volume` (`number`, optional): Initial value of audio volume. Accepts values between 0 and 1.

  To control volume during playback call `setVolume()` (`clpp.Player#setVolume`).

  On Tizen the `http://tizen.org/privilege/tv.audio` privilege needs to be enabled in order to control volume.

  On iOS this has no effect, volume is controlled on system level.
- `muted` (`boolean`, optional), default `false`: Initial mute setting for audio.

  To mute and unmute the player during playback call `setMuted()` (`clpp.Player#setMuted`).
- `forceWaitForTracks` (`boolean`, optional), default `false`: **Applies to:** safari On Safari with native player `open()` (`clpp.Player#open`) may get resolved before tracks are discovered. Enable this to force the player to wait for tracks before resolving `open()` (`clpp.Player#open`).

  This is disabled by default in order to optimize load time.
- `loop` (`boolean`, optional), default `false`: Play the source in a loop. When it ends it immediately starts again from the beginning.
- `startTime` (`number`, optional): Set the playback start position in seconds.

  By default VOD streams start from the beginning from position 0 and live streams start from the end of seek range aka "live edge" in order to show the latest part of live stream.

  Setting a value for live streams requires previous knowledge of the timestamps of the DVR window at tune-in time.
- `suggestedPresentationDelay` (`number`, optional): **Applies to:** mse How many seconds behind the live edge should playback position be kept in live streams. This is analogous to `MPD@suggestedPresentationDelay` in DASH.

  By default a reasonable delay is applied based on the DASH manifest, HLS playlist or MSS manifests.

  This option allows a client-side override of the delay value.
- `sendPlaybackSessionIdHeader` (`boolean`, optional), default `false`: **Deprecated.** Has no effect. Use `mse.sendPlaybackSessionIdHeader` instead (see `clpp.MseConfiguration`) to add the X-Playback-Session-Id HTTP header to playback requests.
- `forceXhr` (`boolean`, optional), default `false`: Use XHR API to make HTTP(S) requests instead of Fetch API. By default Fetch API is selected if supported by platform.
- `manifest` (`clpp.ManifestConfiguration`, optional): **Applies to:** mse Configuration related to DASH manifests, HLS playlists and MSS manifests.
- `abr` (`clpp.AbrConfiguration`, optional): **Applies to:** mse Configuration of Adaptive Bitrate Streaming (ABR).
- `drm` (`clpp.DrmConfiguration`, optional): Configuration of Digital Rights Management (DRM).
- `drmResolver` (`clpp.DrmConfigurationResolver`, optional): **Applies to:** mse The DRM configuration resolver.

  This may be useful in very particular scenarios where the app mixes content from multiple origins and different content needs different DRM configuration. In those cases the resolver may be used to decide on DRM configuration based on the content of the manifest.
- `streaming` (`clpp.StreamingConfiguration`, optional): **Applies to:** mse Configuration of streaming.
- `mediaSource` (`clpp.MediaSourceConfiguration`, optional): **Applies to:** mse Configuration related to Media Source Extensions (MSE).

  Related: `mse` (`clpp.BasePlayerConfiguration#mse`)
- `restrictions` (`clpp.Restrictions`, optional): **Applies to:** mse Configure restrictions of tracks by video resolution or bandwidth.
- `thumbnails` (`clpp.ThumbnailsConfiguration`, optional): Configuration of thumbnails.
- `conviva` (`clpp.ConvivaConfiguration`, optional): Configuration of Conviva analytics plugin.
- `ima` (`clpp.ImaConfiguration`, optional): Configuration of Google IMA ads plugin (CSAI).

  Related: `freewheel` (`clpp.BasePlayerConfiguration#freewheel`), `ads` (`clpp.BasePlayerConfiguration#ads`), `simid` (`clpp.BasePlayerConfiguration#simid`)
- `ads` (`clpp.AdsConfiguration`, optional): **Applies to:** mse Configuration of ads, mainly for SGAI.

  Related: `ima` (`clpp.BasePlayerConfiguration#ima`), `freewheel` (`clpp.BasePlayerConfiguration#freewheel`), `simid` (`clpp.BasePlayerConfiguration#simid`)
- `yospace` (`clpp.YospaceConfiguration`, optional): Configuration of Yospace ad management plugin.
- `npaw` (`clpp.NpawConfiguration`, optional): Configuration of NPAW analytics plugin.
- `youbora` (`clpp.YouboraConfiguration`, optional): **Deprecated.** Youbora v6 plugin configuration.

  Use `npaw` (`clpp.BasePlayerConfiguration#npaw`) option instead, it is a newer version of the same plugin.
- `vimond` (`clpp.VimondConfiguration`, optional): **Deprecated.** Vimond plugin configuration.
- `adobe` (`clpp.AdobeConfiguration`, optional): **Deprecated.** Adobe analytics plugin configuration.
- `broadpeak` (`clpp.BroadpeakConfiguration`, optional): Configuration of Broadpeak analytics plugin.
- `remoteTextTracks` (`Array<clpp.RemoteTextTrack>`, optional): Text tracks to side-load.

  Related: `htmlcue` (`clpp.BasePlayerConfiguration#htmlcue`), `hlssmpte` (`clpp.BasePlayerConfiguration#hlssmpte`), `textStyle` (`clpp.BasePlayerConfiguration#textStyle`), `ttml` (`clpp.BasePlayerConfiguration#ttml`)
- `tizen` (`clpp.TizenConfiguration`, optional): Configuration for Tizen (Samsung TV).
- `textStyle` (`clpp.TextStyleConfiguration`, optional): Configuration of CSS styling of subtitles.

  Related: `htmlcue` (`clpp.BasePlayerConfiguration#htmlcue`), `hlssmpte` (`clpp.BasePlayerConfiguration#hlssmpte`), `remoteTextTracks` (`clpp.BasePlayerConfiguration#remoteTextTracks`), `ttml` (`clpp.BasePlayerConfiguration#ttml`)
- `trickPlay` (`clpp.TrickPlayConfiguration`, optional): **Applies to:** mse Configuration of trick play (fast-forwarding, rewinding, scrubbing, etc).
- `freewheel` (`clpp.FreeWheelConfiguration`, optional): Configuration of FreeWheel ads (CSAI).

  Related: `ima` (`clpp.BasePlayerConfiguration#ima`), `ads` (`clpp.BasePlayerConfiguration#ads`), `simid` (`clpp.BasePlayerConfiguration#simid`)
- `muxdata` (`clpp.MuxDataConfiguration`, optional): Configuration of Mux Data analytics.
- `htmlcue` (`clpp.HtmlCueConfiguration`, optional): Configuration of HTML-based rendering of subtitles.

  Related: `hlssmpte` (`clpp.BasePlayerConfiguration#hlssmpte`), `textStyle` (`clpp.BasePlayerConfiguration#textStyle`), `remoteTextTracks` (`clpp.BasePlayerConfiguration#remoteTextTracks`), `ttml` (`clpp.BasePlayerConfiguration#ttml`)
- `hlssmpte` (`clpp.HlsSmpteConfiguration`, optional): **Applies to:** safari Configuration of SMPTE-TT subtitles in HLS.

  Related: `htmlcue` (`clpp.BasePlayerConfiguration#htmlcue`), `textStyle` (`clpp.BasePlayerConfiguration#textStyle`), `remoteTextTracks` (`clpp.BasePlayerConfiguration#remoteTextTracks`), `ttml` (`clpp.BasePlayerConfiguration#ttml`)
- `ttml` (`clpp.TtmlConfiguration`, optional): Configuration of TTML subtitles.

  Related: `htmlcue` (`clpp.BasePlayerConfiguration#htmlcue`), `hlssmpte` (`clpp.BasePlayerConfiguration#hlssmpte`), `textStyle` (`clpp.BasePlayerConfiguration#textStyle`), `remoteTextTracks` (`clpp.BasePlayerConfiguration#remoteTextTracks`),
- `chromecast` (`clpp.ChromecastConfiguration`, optional): **Applies to:** chromecast Configuration of Chromecast.
- `connectivityCheck` (`clpp.ConnectivityCheckConfiguration`, optional): Configuration of connectivity checker, which is used is used to monitor network connectivity.
- `vr` (`clpp.VrConfiguration`, optional): Configuration of virtual reality (VR) and 360 video plugin.
- `mse` (`clpp.MseConfiguration`, optional): **Applies to:** mse Configuration of MSE-based playback.

  Related: `mediaSource` (`clpp.BasePlayerConfiguration#mediaSource`)
- `safari` (`clpp.SafariConfiguration`, optional): **Applies to:** safari Configuration of Safari-based playback for HLS.
- `simid` (`clpp.SimidConfiguration`, optional): Configuration of SIMID ads.

  Related: `ima` (`clpp.BasePlayerConfiguration#ima`), `freewheel` (`clpp.BasePlayerConfiguration#freewheel`), `ads` (`clpp.BasePlayerConfiguration#ads`)
- `playlist` (`clpp.PlaylistConfiguration`, optional): **Applies to:** mse `ScPlaylist` (`clpp.playlist.ScPlaylist`) configuration.
- `cmsd` (`clpp.CmsdConfiguration`, optional): Configuration of Common Media Server Data (CMSD).

  See `cmcd` (`clpp.BasePlayerConfiguration#cmcd`) for CMCD.
- `contentSteering` (`clpp.ContentSteeringConfiguration`, optional): Configuration of content steering.
- `cmcd` (`clpp.CmcdConfiguration`, optional): Configuration of Common Media Client Data (CMCD).

  See `cmsd` (`clpp.BasePlayerConfiguration#cmsd`) for CMSD.

## clpp.ConstructorPlayerConfiguration (typedef)

Extends: `clpp.BasePlayerConfiguration`. Inherited members are documented there.

Configuration applied to every playback session, typically these are settings such as autoplay, preferred language, text style, streaming or ABR configuration.

Properties:

- `license` (`string`): The Castlabs license key.
- `viewerId` (`string`, optional): A unique identifier of a viewer. Its format may be arbitrary, but it must be unique for each viewer.

  This is mandatory if your Castlabs license requires it.

## clpp.Source (typedef)

A single playback source

Properties:

- `url` (`string`): The source URL to your Manifest.
- `type` (`clpp.Type`, optional): The source type.
- `drmProtected` (`boolean`, optional): Set to true for DRM protected content.
- `name` (`string`, optional): A human readable asset name.
- `isLive` (`boolean`, optional): Set to true for live content.
- `videoMimeType` (`string`, optional): Video mime type. Relevant for HLS while casting.
- `audioMimeType` (`string`, optional): Audio mime type. Relevant for HLS while casting.

## clpp.events (namespace)

Events triggered by `clpp.Player`.

### Events

#### clpp.events.ERROR

Event name: `error`

Triggered on error events.

The detail will contains the `clpp.Error` that exposes the reason for the buffering start.

Event properties:

- `detail` (`clpp.Error`): The error that caused this event

Example: Listen to errors.

```js
player.on(clpp.events.ERROR, function (e) {
  const error = e.detail;
  console.log('Player error with code' + error.code);
});
```

#### clpp.events.LOADEDMETADATA

Event name: `loadedmetadata`

Triggered when video meta data are loaded

#### clpp.events.BUFFERING_ENDED

Event name: `bufferingended`

Triggered when player finishes buffering.

Event properties:

- `detail` (`clpp.events.BufferingDetails`): The details include the reason for buffering and the time it took to finish buffering.

Example: Listen to the end of buffering.

```js
player.on(clpp.events.BUFFERING_ENDED, function (e) {
  const detail = e.detail;
  const reason = detail.reason;
  const bufferedTimeMS = detail.bufferedTimeMS;
  console.log('reason:', reason);
  console.log('bufferedTimeMS:', bufferedTimeMS);
});
```

#### clpp.events.BUFFERING_STARTED

Event name: `bufferingstarted`

Triggered when player starts buffering.

Event properties:

- `detail` (`clpp.events.BufferingDetails`): The details include the reason for buffering.

Example: Listen to buffering event.

```js
player.on(clpp.events.BUFFERING_STARTED, function (e) {
  const detail = e.detail;
  const reason = detail.reason;
  console.log('reason:', reason);
});
```

#### clpp.events.EFFECTIVE_URL_CHANGED

Event name: `effective-url-changed`

Triggered when the effective URL of the stream changes, i.e. when the stream starts being loaded from another URL. The new URL is returned by `getEffectiveUrl()` (`clpp.Player#getEffectiveUrl`).

Example: Listen to changes of effective URL

```js
player.on(clpp.events.EFFECTIVE_URL_CHANGED, function () {
  console.log('The stream is loaded from', player.getEffectiveUrl());
});
```

#### clpp.events.STATE_CHANGED

Event name: `statechanged`

Triggered when player changes the state.

The event provides `clpp.events.StateChangeDetails` in the `detail` property.

Event properties:

- `detail` (`clpp.events.StateChangeDetails`): Object that contains the details about the state change.

Example: Listen to changes in player state.

```js
player.on(clpp.events.STATE_CHANGED, function (e) {
  const detail = e.detail;
  const currentState = detail.currentState;
  const previousState = detail.previousState;
  const timeSinceLastStateChangeMS = detail.timeSinceLastStateChangeMS;
  console.log('currentState:', currentState);
  console.log('previousState:', previousState);
  console.log('timeSinceLastStateChangeMS:', timeSinceLastStateChangeMS);
});
```

#### clpp.events.PLAYER_STATE_CHANGED

Event name: `playerstatechanged`

Triggered when player or user changes the internal PlayerState value.

Warning: This event exposes the common API player state model, but it is not yet fully functional across all PRESTOplay SDK components. Use `clpp.events.STATE_CHANGED` and `clpp.Player.State` instead.

The event provides `clpp.events.PlayerStateChangeDetails` in the `detail` property.

Event properties:

- `detail` (`clpp.events.PlayerStateChangeDetails`): Object that contains the details about the player state change.

#### clpp.events.AUDIO_TRACK_CHANGED

Event name: `audiotrackchanged`

Triggered when player or user changes the currently selected audio track.

#### clpp.events.TEXT_TRACK_CHANGED

Event name: `texttrackchanged`

Triggered when player or user changes the currently selected text track.

#### clpp.events.VIDEO_TRACK_CHANGED

Event name: `videotrackchanged`

Triggered when the selected video rendition is changed. Note that this is not necessarily triggered when the currently playing video track is changed. It is triggered when a video track is selected to be downloaded and appended to the buffer either manually or via the ABR algorithm. If you are interested in the currently playing rendition, the one that is on screen, listen to the `clpp.events.BITRATE_CHANGED` event instead.

Event properties:

- `details` (`clpp.events.VideoTrackChangeDetails`): Object that contains information about the now selected video track as well as the reason, i.e. manual vs ABR, why the track was selected.

#### clpp.events.BITRATE_CHANGED

Event name: `bitratechanged`

Triggered when the currently playing video rendition changes.

Event properties:

- `detail` (`clpp.events.BitrateChangeDetails`): Object that contains the details about the currently playing rendition. Note that the details *might* have a reference to the underlying `Track` (`clpp.Track`) if it could be matched. The same is true for bitrate information. This information might not always be provided though.

#### clpp.events.TRACKS_ADDED

Event name: `tracksadded`

Triggered when player adds new tracks.

#### clpp.events.TRACKS_REMOVED

Event name: `tracksremoved`

Triggered when player removes tracks.

#### clpp.events.LOAD_START

Event name: `loadstart`

Triggered when the player started to load the source.

#### clpp.events.RELEASING

Event name: `releasing`

Triggered when the player and its components are about to be released

#### clpp.events.RELEASED

Event name: `released`

Triggered when the player and its components are released

#### clpp.events.VIDEO_BUFFER_CHANGED

Event name: `videobufferchanged`

Triggered when a video segment is appended or removed

#### clpp.events.AUDIO_BUFFER_CHANGED

Event name: `audiobufferchanged`

Triggered when an audio segment is appended or removed

#### clpp.events.DRM_SESSION_CREATED

Event name: `drmsessioncreated`

Triggered when the players DRM session is created.

Event properties:

- `keySystem` (`clpp.drm.KeySystem`): The selected key system.

#### clpp.events.DRM_SESSION_UPDATE

Event name: `drmsessionupdate`

Triggered when the players DRM session is updated.

Event properties:

- `keySystem` (`clpp.drm.KeySystem`): The selected key system.
- `expirationTime` (`number`): The minimum expiration time of all loaded licenses or Infinity.
- `expectedRenewalTime` (`number`): The time at which a license renewal can be expected or NaN

#### clpp.events.DRM_SESSION_PERSISTED

Event name: `drmsessionpersisted`

Triggered when the DRM session for the load content has been successfully persisted.

Event properties:

- `offlineId` (`string`): The associated offlineId.

#### clpp.events.DRM_RENEWAL_STARTED

Event name: `drmrenewalstarted`

Triggered when the DRM session sends a license renewal request

Event properties:

- `keySystem` (`clpp.drm.KeySystem`): The selected key system.
- `expirationTime` (`number`): The minium expiration time of all loaded licenses or Infinity.

#### clpp.events.DRM_EXPIRATION_UPDATE

Event name: `drmexpirationupdate`

Triggered when the DRM session expiration time is updated.

Event properties:

- `expirationTime` (`number`): The minium expiration time (timestamp in milliseconds) of all loaded licenses or Infinity.

#### clpp.events.DRM_LICENSE_REQUESTED

Event name: `drmlicenserequested`

Triggered when a DRM license request is sent to the server.

Event properties:

- `delay` (`number`): Number of seconds by which the request was delayed.

#### clpp.events.AUTOPLAY_NOT_ALLOWED

Event name: `autoplaynotallowed`

Triggered when an attempt to autoplay the media was blocked by the platform.

#### clpp.events.PLAY

Event name: `play`

Triggered on play request, as a result of the play() method, or the autoplay config.

#### clpp.events.SEEKING

Event name: `seeking`

Triggered when a seek operation begins. This event is passed directly from video element.

#### clpp.events.SEEKED

Event name: `seeked`

Triggered when a seek operation completes. This event is passed directly from video element.

#### clpp.events.USER_SEEKING

Event name: `user-seeking`

Triggered when a seek operation begins is performed by an user.

#### clpp.events.USER_SEEKED

Event name: `user-seeked`

Triggered when a seek operation completes is performed by an user.

#### clpp.events.ADS_TIMELINE_CHANGED

Event name: `ads-timeline-changed`

Triggered when ad cue points were updated.

Event properties:

- `adsTimeline` (`clpp.ads.IAdsTimeline`): The ad cue points.

#### clpp.events.AD_LOADED

Event name: `ad-loaded`

Triggered when ad metadata were loaded.

Event properties:

- `ad` (`clpp.ads.IAd`): The active ad.

#### clpp.events.AD_BREAK_STARTED

Event name: `ad-break-started`

Triggered when an ad pod started.

Event properties:

- `ad` (`clpp.ads.IAd`): The active ad.
- `id` (`string`, optional): The ID of the ad break. In case of HLS interstitials this is the ID of the date range.

#### clpp.events.AD_STARTED

Event name: `ad-started`

Triggered when an ad started.

Event properties:

- `ad` (`clpp.ads.IAd`): The active ad.

#### clpp.events.AD_BUFFERING

Event name: `ad-buffering`

Triggered when an ad has stalled playback to buffer.

Event properties:

- `ad` (`clpp.ads.IAd`): The active ad.

#### clpp.events.AD_PROGRESS

Event name: `ad-progress`

Triggered when the ad's current time value changes.

Event properties:

- `ad` (`clpp.ads.IAd`): The active ad.

#### clpp.events.AD_FIRST_QUARTILE

Event name: `ad-first-quartile`

Triggered when the first quartile was successfully played out.

Event properties:

- `ad` (`clpp.ads.IAd`): The active ad.

#### clpp.events.AD_MIDPOINT

Event name: `ad-midpoint`

Triggered when the second quartile was successfully played out.

Event properties:

- `ad` (`clpp.ads.IAd`): The active ad.

#### clpp.events.AD_THIRD_QUARTILE

Event name: `ad-third-quartile`

Triggered when the third quartile was successfully played out.

Event properties:

- `ad` (`clpp.ads.IAd`): The active ad.

#### clpp.events.AD_PAUSED

Event name: `ad-paused`

Triggered when an ad was paused.

Event properties:

- `ad` (`clpp.ads.IAd`): The active ad.

#### clpp.events.AD_RESUMED

Event name: `ad-resumed`

Triggered when an ad was resumed.

Event properties:

- `ad` (`clpp.ads.IAd`): The active ad.

#### clpp.events.AD_SKIPPED

Event name: `ad-skipped`

Triggered when an ad was skipped.

Event properties:

- `ad` (`clpp.ads.IAd`): The active ad.

#### clpp.events.AD_CLICKED

Event name: `ad-clicked`

Triggered when an ad was clicked.

Event properties:

- `ad` (`clpp.ads.IAd`): The active ad.

#### clpp.events.AD_IMPRESSION

Event name: `ad-impression`

Triggered when the impression URL has been pinged.

Event properties:

- `ad` (`clpp.ads.IAd`): The active ad.

#### clpp.events.AD_COMPLETED

Event name: `ad-completed`

Triggered when an ad was played to the end.

Not triggered if an ad was skipped or an error occurred.

Event properties:

- `ad` (`clpp.ads.IAd`): The active ad.

#### clpp.events.AD_STOPPED

Event name: `ad-stopped`

Triggered when an ad ended.

#### clpp.events.AD_BREAK_STOPPED

Event name: `ad-break-stopped`

Triggered when an ad pod ended.

Event properties:

- `id` (`string`, optional): The ID of the ad break. In case of HLS interstitials this is the ID of the date range.

#### clpp.events.AD_HLS_ASSET_LIST_REQUEST

Event name: `ad-hls-asset-list-request`

Triggered when the X-ASSET-LIST request is sent.

#### clpp.events.AD_HLS_ASSET_LIST_RESPONSE

Event name: `ad-hls-asset-list-response`

Triggered when the X-ASSET-LIST response is received.

#### clpp.events.AD_HLS_RESOLVED

Event name: `ad-hls-resoled`

Triggered when the X-ASSET-LIST response is received or when X-ASSET-URI is preloaded.

Event properties:

- `id` (`string`): ID of the EXT-X-DATERANGE tag.
- `detail` (`clpp.interstitial.AssetListResponse`): The X-ASSET-LIST response, or for X-ASSET-URI a response synthesized from the date range, with its X-AD-CREATIVE-SIGNALING decoded.

#### clpp.events.SIMID_CREATIVE_STARTED

Event name: `simid-creative-started`

Triggered when a SIMID Ad started.

#### clpp.events.SIMID_CREATIVE_STOPPED

Event name: `simid-creative-stopped`

Triggered when a SIMID Ad stopped.

#### clpp.events.CASTING_STARTED

Event name: `castingstarted`

Triggered when casting started.

#### clpp.events.CASTING_ENDED

Event name: `castingended`

Triggered when casting ended.

#### clpp.events.CAST_STATUS_CHANGED

Event name: `caststatuschanged`

Triggered when status of cast receiver changed.

#### clpp.events.CAST_VISIBILITY_CHANGED

Event name: `castvisibilitychanged`

Triggered when the cast receiver app goes into the background, or from background back to foreground.

Event properties:

- `visible` (`boolean`): true if receiver app is in the foreground, false if it is in the background.

#### clpp.events.AIRPLAY_STATUS_CHANGED

Event name: `airplay-status-changed`

Triggered when status of AirPlay availability changed.

Event properties:

- `canCast` (`boolean`): True if AirPlay available; False otherwise.

#### clpp.events.AIRPLAY_CASTING_STARTED

Event name: `airplay-casting-started`

Triggered when a media element starts AirPlay playback.

#### clpp.events.AIRPLAY_CASTING_ENDED

Event name: `airplay-casting-ended`

Triggered when a media element stops AirPlay playback.

#### clpp.events.TIMELINE_CUE_ADDED

Event name: `timeline-cue-added`

Triggered when a new cue has been added to the timeline.

Event properties:

- `detail` (`clpp.TimelineCue`): The added cue

#### clpp.events.TIMELINE_CUE_ENTER

Event name: `timeline-cue-enter`

Triggered when a timeline cue is entered.

Event properties:

- `detail` (`clpp.TimelineCue`): The cue

#### clpp.events.TIMELINE_CUE_EXIT

Event name: `timeline-cue-exit`

Triggered when a timeline cue is exited.

Event properties:

- `detail` (`clpp.TimelineCue`): The cue

#### clpp.events.TIMELINE_CUES_CHANGED

Event name: `timeline-cues-changed`

Triggered when timeline cues have changed.

#### clpp.events.MPD_TYPE_CHANGED

Event name: `mpd-type-changed`

Triggered when a MPD type has changed from dynamic to static.

Note: You can also listen to the `clpp.events.LIVE_TURNED_STATIC` event instead.

#### clpp.events.LIVE_TURNED_STATIC

Event name: `live-turned-static`

Triggered when a live stream turned in to a static stream.

In HLS this happens when EXT-X-ENDLIST appears in the playlist and the playlist stops updating. In DASH this happens when the type attribute of MPD turns from "dynamic" to "static" and the manifest stops updating.

#### clpp.events.VIMOND_RESPONSE

Event name: `vimond-response`

Triggered when there is a response from Vimond Session API.

Event properties:

- `detail` (`clpp.net.Response`): The response.

#### clpp.events.PLAYLIST_ITEM_CHANGED

Event name: `playlist-item-changed`

Triggered when the current playlist item has been changed.

Event properties:

- `item` (`clpp.PlaylistItem`, optional): The current playlist item.

#### clpp.events.PLAYLIST_MODIFIED

Event name: `playlist-modified`

Triggered when a playlist item has been added, removed or moved.

#### clpp.events.SC_PLAYLIST_TIMELINE_CHANGED

Event name: `sc-playlist-timeline-changed`

Triggered when a new timeline window has been added to the timeline of a single-controller playlist, or when the duration of an existing timeline window changes.

#### clpp.events.SC_PLAYLIST_ITEM_CHANGED

Event name: `sc-playlist-item-changed`

Triggered when the currently active/selected item of a single-controller playlist changes.

Event properties:

- `id` (`string`): ID of the newly active item.

#### clpp.events.SC_PLAYLIST_ENDED

Event name: `sc-playlist-ended`

Triggered when playback reaches the end of the last item of a single-controller playlist, or if `playlist.endTime` is configured then it's triggered when the end time is reached.

#### clpp.events.SC_PLAYLIST_LIVE_TURNED_STATIC

Event name: `sc-playlist-live-turned-static`

Triggered when the last item of the playlist is an EVENT stream and it turns from dynamic to static.

#### clpp.events.CDN_SWITCH_SUCCESS

Event name: `cdn-switch-success`

Triggered when CDN switch was successful.

Event properties:

- `newManifest` (`string`): new manifest url.

#### clpp.events.ONLINE_STATUS_CHANGED

Event name: `online-status-changed`

Online status changed.

Event properties:

- `online` (`boolean`): is online

#### clpp.events.CMSD_EVENT

Event name: `cmsd-event`

Triggered when CMSD headers were detected as part of a network response.

Event properties:

- `dynamicValues` (`Array<clpp.events.CmsdDynamic>`, optional): Headers are expressed as lists and are typically added by each node that is participating in the delivery. Values are ordered from origin to edge. For the player, typically the **last** item in the list is the most relevant.
- `staticValues` (`clpp.events.CmsdStatic`, optional): Keys whose values persist over multiple requests for the object.

#### clpp.events.YOSPACE_SESSION_STARTED

Event name: `yospace-session-started`

Triggered by the Yospace plugin when the Yospace session has been created.

Event properties:

- `detail` (`YospaceAdManagement.Session`): The [Yospace playback session](https://developer.yospace.com/sdk-documentation/javascript/api/yosdk/latest/Session.html).

#### clpp.events.YOSPACE_SESSION_ENDED

Event name: `yospace-session-ended`

Triggered by the Yospace plugin when the Yospace session has been shut down.

Event properties:

- `detail` (`YospaceAdManagement.Session`): The [Yospace playback session](https://developer.yospace.com/sdk-documentation/javascript/api/yosdk/latest/Session.html).

#### clpp.events.DESTROYING

Event name: `destroying`

**Deprecated.** This event will be removed in v7.

Triggered when the player and its components are about to be destroyed

#### clpp.events.DESTROYED

Event name: `destroyed`

**Deprecated.** This event will be removed in v7.

Triggered when the player and its components are destroyed

## clpp.Error (class)

Extends: `window.Error`. Inherited members are documented there.

Constructor:

```ts
new clpp.Error(severity: clpp.Error.Severity, category: clpp.Error.Category, code: clpp.Error.Code, opt_data?: Object | string, opt_error?: unknown, opt_svtaCode?: number)
```

The castlabs error class that is thrown by all SDK components. This is also the error that is returned in `clpp.events#ERROR` events.

The error class exposes a `code` (`clpp.Error#code`) and a `category` (`clpp.Error#category`) that identify the problem. See the full `list of error codes` (`clpp.Error.Code`).

Some error might also contain additional information in their `data` (`clpp.Error#data`) property.

Create a new Error.

Parameters:

- `severity` (`clpp.Error.Severity`): The severity
- `category` (`clpp.Error.Category`): The error category
- `code` (`clpp.Error.Code`): The error code
- `opt_data` (`Object | string`, optional): Optional data. If this is a string, it will become part of the error message. The opt_data can contain a 'message' property, which will be used as the error message
- `opt_error` (`unknown`, optional): Optional cause. This will be available as the cause for this error.
- `opt_svtaCode` (`number`, optional): Optional SVTA code.

Example: Throw a simple error with a message.

```js
throw new clpp.Error(
    clpp.Error.Severity.FATAL,
    clpp.Error.Category.PLAYER,
    clpp.Error.Code.CANNOT_LOAD_SOURCE,
    'Unknown file extension');
```

Example: Throw an error with a message and metadata.

```js
throw new clpp.Error(
    clpp.Error.Severity.FATAL,
    clpp.Error.Category.PLAYER,
    clpp.Error.Code.CANNOT_LOAD_SOURCE,
    {
       message: 'Multiple sources not supported!',
       sources,
    });
```

### Properties

#### clpp.Error#severity

Type: `clpp.Error.Severity`

The error severity.

#### clpp.Error#category

Type: `clpp.Error.Category`

The error category.

#### clpp.Error#code

Type: `clpp.Error.Code`

The error code.

#### clpp.Error#svtaCode

Type: `number`

The SVTA error code.

#### clpp.Error#data

Type: `unknown`

Optional data that was provided when the error was raised. This might be an empty object if no addition data was provided. Otherwise the data provided here is specific to the error.

#### clpp.Error#cause

Type: `unknown`

Optional cause. If known, this refers to the original error that caused this error to be thrown.

## clpp.Error.Code (enum)

Enum for error codes.

Values:

- `UNSUPPORTED_SCHEME` = `1000`: A network request was made using an unsupported URI scheme.

  The `data` (`clpp.Error#data`) property contains an object with the following properties:
  - `data.url` (`string`): The URL of the failed request
- `BAD_HTTP_STATUS` = `1001`: An HTTP network request returned an HTTP status that indicated a failure.

  The `data` (`clpp.Error#data`) property contains an object with the following properties:
  - `data.url` (`string`): The URL of the failed request
  - `data.status` (`number`): The status code of the failed request
  - `data.responseText` (`string`, optional): The response text
  - `data.headers` (`Record<string, string>`, optional): The response headers
  - `data.request` (`clpp.net.Request`, optional): The request
  - `data.response` (`clpp.net.Response`, optional): The response
- `HTTP_ERROR` = `1002`: An HTTP network request was made but no response was received. There are several different reasons why this may occur. It could be caused by CORS, an SSL problem, the browser being offline or a mixed content error. See the [chapter on Errors](https://demo.castlabs.com/docs/errors) for more info.

  Additionally, there are two special cases, when no response is received, but a different error code will be used instead. Error code `1003` is used for network timeouts, and code `7001` is used when the request is aborted by the player itself.

  The `data` (`clpp.Error#data`) property contains an object with the following properties:
  - `data.url` (`string`): The URL of the failed request
  - `data.status` (`number`): The status code of the failed request. When no HTTP connection was established, this can be `0` or `-1`.
  - `data.request` (`clpp.net.Request`): The request
  - `data.error` (`unknown`, optional): The underlying error, when the request was made with the fetch plugin. The same error is also set as the `cause` (`clpp.Error#cause`).
- `TIMEOUT` = `1003`: A network request timed out.

  The `data` (`clpp.Error#data`) property contains an object with the following properties:
  - `data.url` (`string`): The URL of the failed request
  - `data.request` (`clpp.net.Request`): The request
- `MALFORMED_DATA_URI` = `1004`: A network request was made with a malformed data URI.

  The `data` (`clpp.Error#data`) property contains an object with the following properties:
  - `data.uri` (`string`): The URL of the malformed data request
- `REQUEST_MODIFIER_ERROR` = `1006`: A request modifier threw an error. The `cause` (`clpp.Error#cause`) contains the original error.
- `RESPONSE_MODIFIER_ERROR` = `1007`: A response modifier threw an error. The `cause` (`clpp.Error#cause`) contains the original error.
- `MALFORMED_TEST_URI` = `1008`: A testing network request was made with a malformed URI. This error is only used by unit and integration tests.
- `MALFORMED_URL` = `1011`: A network request was made with a malformed URL.

  The `data` (`clpp.Error#data`) property contains an object with the following properties:
  - `data.url` (`string`): The URL that failed to parse
  - `data.base` (`string`, optional): Optional base URL used during parsing
- `INVALID_TEXT_HEADER` = `2000`: The text parser failed to parse a text stream due to an invalid header.
- `INVALID_TEXT_CUE` = `2001`: The text parser failed to parse a text stream due to an invalid cue.
- `UNABLE_TO_DETECT_ENCODING` = `2003`: Was unable to detect the encoding of the response text.  Suggest adding byte-order-markings to the response data.
- `BAD_ENCODING` = `2004`: The response data contains invalid Unicode character encoding.
- `INVALID_XML` = `2005`: The XML parser failed to parse an xml stream, or the XML lacks mandatory elements for TTML.
- `INVALID_MP4_TTML` = `2007`: MP4 segment does not contain TTML.
- `INVALID_MP4_VTT` = `2008`: MP4 segment does not contain VTT.
- `FETCH_OR_APPEND_ERROR` = `2010`: An error occurred while fetching or appending a text stream.

  The `data` (`clpp.Error#data`) is the underlying exception or Error object.
- `INVALID_MP4` = `2011`: MP4 lacks mandatory elements for VTT & TTML.
- `TEXT_PARSER_MISSING` = `2012`: Unable to find a text parser which can handle the given mime type. Please check whether the TTML or VTT module was imported.
- `THUMBNAILS_FAILED_TO_LOAD` = `2013`: Thumbnail file(s) failed to load.
- `THUMBNAIL_ERROR` = `2014`: Thumbnail-related error.
- `BUFFER_READ_OUT_OF_BOUNDS` = `3000`: Some component tried to read past the end of a buffer.  The segment index, init segment, or PSSH may be malformed.
- `JS_INTEGER_OVERFLOW` = `3001`: Some component tried to parse an integer that was too large to fit in a JavaScript number without rounding error.  JavaScript can only natively represent integers up to 53 bits.
- `EBML_OVERFLOW` = `3002`: The EBML parser used to parse the WebM container encountered an integer, ID, or other field larger than the maximum supported by the parser.
- `EBML_BAD_FLOATING_POINT_SIZE` = `3003`: The EBML parser used to parse the WebM container encountered a floating- point field of a size not supported by the parser.
- `MP4_SIDX_WRONG_BOX_TYPE` = `3004`: The MP4 SIDX parser found the wrong box type. Either the segment index range is incorrect or the data is corrupt.

  The following properties of the error are exposed in the `data` (`clpp.Error#data`) object:
  - `data.url` (`string`): The URL of the request to the erroneous SIDX.
  - `data.byteRange` (`string`): The byte range of the request to the erroneous SIDX, if it was made with an HTTP range request.
  - `data.size` (`number`): The full size of the data of the erroneous SIDX in bytes.
  - `data.sampleData` (`string`): A sample of the erroneous data found instead of the expected SIDX box, in the form of a comma-separated decimal byte string representation of the extracted binary data sample. The default sample size is 1024 bytes or the full size of the data if it is smaller than that. This approach helps prevent bloating the error logs.
- `MP4_SIDX_INVALID_TIMESCALE` = `3005`: The MP4 SIDX parser encountered an invalid timescale. The segment index data may be corrupt.
- `MP4_SIDX_TYPE_NOT_SUPPORTED` = `3006`: The MP4 SIDX parser encountered a type of SIDX that is not supported.
- `WEBM_CUES_ELEMENT_MISSING` = `3007`: The WebM Cues parser was unable to locate the Cues element. The segment index data may be corrupt.
- `WEBM_EBML_HEADER_ELEMENT_MISSING` = `3008`: The WebM header parser was unable to locate the Ebml element. The init segment data may be corrupt.
- `WEBM_SEGMENT_ELEMENT_MISSING` = `3009`: The WebM header parser was unable to locate the Segment element. The init segment data may be corrupt.
- `WEBM_INFO_ELEMENT_MISSING` = `3010`: The WebM header parser was unable to locate the Info element. The init segment data may be corrupt.
- `WEBM_DURATION_ELEMENT_MISSING` = `3011`: The WebM header parser was unable to locate the Duration element. The init segment data may be corrupt or may have been incorrectly encoded. Duration information in WebM DASH content is required.
- `WEBM_CUE_TRACK_POSITIONS_ELEMENT_MISSING` = `3012`: The WebM Cues parser was unable to locate the Cue Track Positions element. The segment index data may be corrupt.
- `WEBM_CUE_TIME_ELEMENT_MISSING` = `3013`: The WebM Cues parser was unable to locate the Cue Time element. The segment index data may be corrupt.
- `MEDIA_SOURCE_OPERATION_FAILED` = `3014`: A MediaSource operation failed.

  The `data` (`clpp.Error#data`) property contains an object with the following properties:
  - `data.mediaError` (`number`): The MediaError code from the video element.
- `MEDIA_SOURCE_OPERATION_THREW` = `3015`: A MediaSource operation threw an exception.

  The `data` (`clpp.Error#data`) property contains an object with the following properties:
  - `data.mediaError` (`Error`): The exception that was thrown
- `VIDEO_ERROR` = `3016`: The video element reported an error.

  The `data` (`clpp.Error#data`) property contains an object with the following properties:
  - `data.code` (`number`): a MediaError code from the video element.
  - `data.extendedError` (`string | undefined`): On Edge & IE, this is a Microsoft extended error code in hex. Note that the native playback engine reports this as `data.extended` instead.
- `QUOTA_EXCEEDED_ERROR` = `3017`: A MediaSource operation threw QuotaExceededError and recovery failed. The content cannot be played correctly because the segments are too large for the browser/platform. This may occur when attempting to play very high quality, very high bitrate content on low-end devices.

  The `data` (`clpp.Error#data`) property contains an object with the following properties:
  - `data.type` (`string`): The type of content which caused the error.
- `TRANSMUXING_FAILED` = `3018`: Mux.js did not invoke the callback signifying successful transmuxing.
- `MP4_PARSER_ERROR` = `3019`: General error raised by the MP4 parser or entities that process MP4 data.
- `MEDIA_LOAD_ERROR` = `3100`: An error occurred while loading media. The detail property contains the URL of the media or manifest segment that failed to load. This error is posted when the player has no detailed information about the actual failure.
- `INVALID_TRACK_TYPE` = `3101`: An error raised when the requested track type is invalid. Valid track types must be one of `clpp.Track.Type`.
- `MEDIA_DECRYPTION_ERROR` = `3103`: A media segment could not be decrypted. This can happen e.g for HLS + AES-128 content.
- `PAUSE_FAILED` = `3201`: An error raised when the player fails to be paused.
- `UNABLE_TO_GUESS_MANIFEST_TYPE` = `4000`: The Player was unable to guess the manifest type based on file extension or MIME type. To fix, try one of the following:

  - Set an explicit type in the `clpp.Source` when calling `clpp.Player#open`.
  - Rename the manifest so that the URI ends in a well-known extension.
  - Configure the server to send a recognizable Content-Type header.
  - Configure the server to accept a HEAD request for the manifest.

  The `data` (`clpp.Error#data`) property contains an object with the following properties:
  - `data.url` (`string`): The URL to the manifest
- `DASH_INVALID_XML` = `4001`: The DASH Manifest contained invalid XML markup.
- `DASH_NO_SEGMENT_INFO` = `4002`: The DASH Manifest contained a Representation with insufficient segment information.
- `DASH_EMPTY_ADAPTATION_SET` = `4003`: The DASH Manifest contained an AdaptationSet with no Representations.
- `DASH_EMPTY_PERIOD` = `4004`: The DASH Manifest contained an Period with no AdaptationSets.
- `DASH_WEBM_MISSING_INIT` = `4005`: The DASH Manifest does not specify an init segment with a WebM container.
- `DASH_UNSUPPORTED_CONTAINER` = `4006`: The DASH Manifest contained an unsupported container format.
- `DASH_PSSH_BAD_ENCODING` = `4007`: The embedded PSSH data has invalid encoding.
- `DASH_NO_COMMON_KEY_SYSTEM` = `4008`: There is an AdaptationSet whose Representations do not have any common key-systems.
- `DASH_MULTIPLE_KEY_IDS_NOT_SUPPORTED` = `4009`: Having multiple key IDs per Representation is not supported.
- `DASH_CONFLICTING_KEY_IDS` = `4010`: The DASH Manifest specifies conflicting key IDs.
- `UNPLAYABLE_PERIOD` = `4011`: The manifest contains a period with no playable streams. Either the period was originally empty, or the streams within cannot be played on this browser or platform.
- `RESTRICTIONS_CANNOT_BE_MET` = `4012`: There exist some streams that could be decoded, but restrictions imposed by the application or the key system prevent us from playing.  This may happen under the following conditions:

  - The application has given restrictions to the Player that restrict at least one content type completely (e.g. no playable audio).
  - The key system has imposed output restrictions that cannot be met (such as HDCP) and there are no unrestricted alternatives.
- `NO_PERIODS` = `4014`: No valid periods were found in the manifest.  Please check that your manifest is correct and free of typos.
- `HLS_PLAYLIST_HEADER_MISSING` = `4015`: HLS playlist doesn't start with a mandatory #EXTM3U tag.
- `INVALID_HLS_TAG` = `4016`: HLS tag has an invalid name that doesn't start with '#EXT'

  The `data` (`clpp.Error#data`) property contains an object with the following properties:
  - `data.invalidTag` (`string`): The invalid tag.
- `HLS_INVALID_PLAYLIST_HIERARCHY` = `4017`: HLS playlist has both Master and Media/Segment tags.
- `DASH_DUPLICATE_REPRESENTATION_ID` = `4018`: A Representation has an id that is the same as another Representation in the same Period.  This makes manifest updates impossible since we cannot map the updated Representation to the old one.
- `HLS_MULTIPLE_MEDIA_INIT_SECTIONS_FOUND` = `4020`: HLS manifest is invalid because multiple #EXT-X-MAP tags were found attached to the same segment.
- `HLS_COULD_NOT_GUESS_MIME_TYPE` = `4021`: HLS parser was unable to guess mime type of a stream.
- `HLS_REQUIRED_ATTRIBUTE_MISSING` = `4023`: One of the required attributes was not provided. HLS manifest is invalid.
- `HLS_REQUIRED_TAG_MISSING` = `4024`: One of the required tags was not provided. HLS manifest is invalid.

  The `data` (`clpp.Error#data`) property contains an object with the following properties:
  - `data.missingTag` (`string`, optional): The name of the missing tag, if absent check the error message instead.
- `HLS_COULD_NOT_GUESS_CODECS` = `4025`: HLS parser was unable to guess codecs of a stream.

  The `data` (`clpp.Error#data`) property contains an object with the following properties:
  - `data.codecList` (`Array<string>`): The list of all codecs for the variant.
- `HLS_KEYFORMATS_NOT_SUPPORTED` = `4026`: HLS parser has encountered encrypted content with unsupported KEYFORMAT attributes.
- `DASH_UNSUPPORTED_XLINK_ACTUATE` = `4027`: The manifest parser only supports xlink links with xlink:actuate="onLoad".
- `DASH_XLINK_DEPTH_LIMIT` = `4028`: The manifest parser has hit its depth limit on xlink link chains.
- `HLS_COULD_NOT_PARSE_SEGMENT_START_TIME` = `4030`: HLS parser was unable to parse segment start time from the media.
- `CONTENT_UNSUPPORTED_BY_BROWSER` = `4032`: The content container or codecs are not supported by this browser. For example, this could happen if the content is WebM, but your browser does not support the WebM container, or if the content uses HEVC, but your browser does not support the HEVC codec.  This can also occur for multicodec or multicontainer manifests if none of the codecs or containers are supported by the browser.
- `SMOOTH_INVALID_MANIFEST_XML` = `4033`: Microsoft smooth streaming invalid manifest XML.
- `SMOOTH_EMPTY_PRESENTATION` = `4034`: Microsoft smooth streaming empty presentation i.e. no stream were found
- `SMOOTH_MEDIA_PROCESSING_ERROR` = `4035`: The Smooth Streaming plugin experienced an error while processing media data.

  The `data` (`clpp.Error#data`) property is the underlying error object.
- `SMOOTH_INVALID_VERSION` = `4036`: The smooth streaming manifest version is invalid.
- `SMOOTH_INVALID_FRAGMENT_METADATA` = `4037`: The Smooth Streaming parser found an invalid `StreamFragmentElement`. Invalid here means that it didn't complied with the specs.
- `SMOOTH_REQUIRED_ATTRIBUTE_MISSING` = `4038`: One of the required attributes was not provided. Smooth Streaming manifest is invalid.
- `SMOOTH_TRUNCATED_MEDIA_FILE` = `4039`: A media segment could not be processed because it's truncated.

  The `data` (`clpp.Error#data`) property is the underlying error object.
- `CANNOT_ADD_EXTERNAL_TEXT_TO_LIVE_STREAM` = `4040`: External text tracks cannot be added to live streams.
- `HLS_MSE_ENCRYPTED_TS_NOT_SUPPORTED` = `4041`: Due to limitations of the MSE API Fairplay-protected MPEG-TS is not supported.
- `HLS_PLAYLIST_NOT_UTF8` = `4042`: HLS playlist cannot be parsed because it is not encoded in UTF-8.
- `HLS_PLAYLIST_EMPTY` = `4043`: HLS media playlist does not contain any media segments.
- `HLS_INVALID_VALUE` = `4044`: Some tag or attribute value in the HLS playlist is invalid.
- `HLS_DISCONTINUITY_NOT_SUPPORTED` = `4045`: Encountered a complex HLS playlist with discontinuities. Discontinuity in HLS is not fully supported yet, only certain simple playlists are supported.
- `HLS_INCOMPATIBLE_PLAYLIST_UPDATE` = `4047`: The content of the media playlist is incompatible with new content after an update.
- `HLS_DISJOINT_PLAYLISTS` = `4048`: Media playlists for selected tracks in live represent disjoint time ranges and therefore cannot be played together.
- `INVALID_STREAMS_CHOSEN` = `5005`: This can happen when there is multi-Period content where one Period is video+audio and another is video-only or audio-only.  We don't support this case because it is incompatible with MSE.
- `STREAMING_ERROR` = `5006`: An error occurred while streaming the content.
- `NO_RECOGNIZED_KEY_SYSTEMS` = `6000`: The manifest indicated protected content, but the manifest parser was unable to determine what key systems should be used.
- `REQUESTED_KEY_SYSTEM_CONFIG_UNAVAILABLE` = `6001`: None of the requested key system configurations are available.  This may happen under the following conditions:

  -  Configuration for the target system is missing.
  -  The key system is not supported.
  -  The key system does not support the features requested (e.g. persistent state).
  -  A user prompt was shown and the user denied access.
  -  The key system is not available from unsecure contexts. (ie. requires HTTPS) See [https://goo.gl/EEhZqT](https://goo.gl/EEhZqT).
  -  In case of Widevine this issue may be resolved by setting the flags distinctiveIdentifierRequired and/or persistentStateRequired to either true of false depending on the platform, see [DRM docs](https://demo.castlabs.com/docs/drm#cdm-configuration) for more details. Try [CDM probe page](https://demo.castlabs.com/cdm) to check which CDMs and CDM configurations are supported by your browser. Note that the use of distinctive identifiers may present [privacy concerns](https://www.w3.org/TR/encrypted-media/#identifier-requirements).
- `FAILED_TO_CREATE_CDM` = `6002`: The browser found one of the requested key systems, but it failed to create an instance of the CDM for some unknown reason.

  The errors cause might contain the original error if there was one thrown by the browser.

  The `data` (`clpp.Error#data`) property contains an object with the following properties:
  - `data.browserError` (`string`): The error message string from the browser.
- `FAILED_TO_ATTACH_TO_VIDEO` = `6003`: The browser found one of the requested key systems and created an instance of the CDM, but it failed to attach the CDM to the video for some unknown reason.
- `INVALID_SERVER_CERTIFICATE` = `6004`: The CDM rejected the server certificate supplied by the application. The certificate may be malformed or in an unsupported format.

  The player will try to recover from such an error automatically if this happened with a pre-configured server certificate. In that case this error will be posted as a recoverable error. However, if the certificate returned by the DRM backend could not be loaded, a fatal error will be posted.
- `FAILED_TO_CREATE_SESSION` = `6005`: The CDM refused to create a session for some unknown reason.

  The `data` (`clpp.Error#data`) property contains an object with the following properties:
  - `data.browserError` (`string`, optional): The error message string from the browser.
- `FAILED_TO_GENERATE_LICENSE_REQUEST` = `6006`: The CDM was unable to generate a license request for the init data it was given. The init data may be malformed or in an unsupported format.

  `clpp.Error#cause` contains a reference to the original error.
- `LICENSE_REQUEST_FAILED` = `6007`: The license request failed. This could be a timeout, a network failure, or a rejection by the server. The `cause` (`clpp.Error#cause`) contains the underlying network error.

  The `data` (`clpp.Error#data`) property contains an object with the following properties:
  - `data.url` (`string`): The URL of the failed request
  - `data.status` (`number`, optional): The status code of the failed request. Absent when the request timed out.
  - `data.response` (`clpp.net.Response`, optional): The response, if one was received
  - `data.headers` (`Record<string, string>`, optional): The response headers
  - `data.drmTodayErrorCode` (`string`, optional): DRMToday error code
  - `data.drmTodayErrorMessage` (`string`, optional): DRMToday error message
- `LICENSE_RESPONSE_REJECTED` = `6008`: The license response was rejected by the CDM.  The server's response may be invalid or malformed for this CDM.

  The `data` (`clpp.Error#data`) property contains an object with the following properties:
  - `data.browserError` (`string`): The error message string from the browser.
- `ENCRYPTED_CONTENT_WITHOUT_DRM_INFO` = `6010`: The manifest does not specify any DRM info, but the content is encrypted. Either the manifest or the manifest parser are broken.
- `NO_LICENSE_SERVER_GIVEN` = `6012`: No license server was given for the key system signaled by the manifest. A license server URI is required for every key system.
- `OFFLINE_SESSION_REMOVED` = `6013`: A required offline session was removed. The content is not playable.
- `EXPIRED` = `6014`: The license has expired. This is triggered when all keys in the key status map have a status of 'expired'.
- `REQUESTED_DRM_ENVIRONMENT_UNAVAILABLE` = `6015`: The requested DRM environment is unavailable. This happens if you configure this player to use a DRM environment that hasn't be register with the player. Please make sure the configured DRM environment is actually added to player before using it. For more details see [https://bit.ly/3piaFqf](https://bit.ly/3piaFqf)
- `INIT_DATA_TRANSFORM_ERROR` = `6016`: An error was thrown while executing the init data transformation.

  The `data` (`clpp.Error#data`) property contains the original error.
- `CERTIFICATE_REQUEST_FAILED` = `6100`: The DRM certificate request failed. The `cause` (`clpp.Error#cause`) of the error will contain an error of the `clpp.Error.Category#NETWORK` category with more information about the failed request.

  The `data` (`clpp.Error#data`) property contains an object with the following properties:
  - `data.url` (`string`): The URL of the failed request
  - `data.status` (`number`, optional): The status code of the failed request. Absent when the request timed out.
  - `data.response` (`clpp.net.Response`, optional): The response, if one was received
  - `data.headers` (`Record<string, string>`, optional): The response headers
  - `data.drmTodayErrorCode` (`string`, optional): DRMToday error code
  - `data.drmTodayErrorMessage` (`string`, optional): DRMToday error message
- `NO_CONTENT_ID` = `6101`: Raised specifically by Fairplay DRM when the extracted content ID is an empty string. Check your implementation of `extractContentId` (`clpp.drm.LicenseModifiers#extractContentId`) for `clpp.FairplayDrmSystem` or HLS #EXT-X-KEY:URI content.
- `SERVER_CERTIFICATE_REQUIRED` = `6102`: A server certificate wasn't given when it is required.  FairPlay requires setting an explicit server certificate in the configuration.
- `EXTRACT_CONTENT_ID_MODIFIER_ERROR` = `6103`: An extractContentId modifier threw an error. Check your implementation of `extractContentId` (`clpp.drm.LicenseModifiers#extractContentId`) for `clpp.FairplayDrmSystem`.
- `FAILED_TO_PERSIST_SESSION` = `6200`: Raised when an attempt to persist a media key session failed.
- `FAILED_TO_REMOVE_SESSION` = `6201`: Raised when an attempt to remove a offline media key session failed.
- `INVALID_SESSION_STORAGE_IMPLEMENTATION` = `6202`: Raised when trying to use and invalid session storage implementation.
- `LOAD_INTERRUPTED` = `7000`: The call to `player.open()` (`clpp.Player#open`) was interrupted by a call to `player.release()` (`clpp.Player#release`) or another call to `player.open()` (`clpp.Player#open`).
- `OPERATION_ABORTED` = `7001`: An internal error which indicates that an operation was aborted. For example the load promise might be rejected with this error when another load call has been executed.

  The `data` (`clpp.Error#data`) property contains an object with the following properties:
  - `data.url` (`string`, optional): The URL of the aborted request
  - `data.request` (`clpp.net.Request`, optional): The request
- `CANNOT_LOAD_SOURCE` = `7003`: The player could not load the configured `clpp.Source`. Either the player is missing some capabilities (e.g. from one or more unloaded player components/plugins) or it's limited by the current platform.
- `MEDIA_ELEMENT_NOT_FOUND` = `7004`: Player failed to initialize because no Media Element with the provided ID was found.
- `INVALID_MEDIA_ELEMENT` = `7005`: Player failed to initialize because Media Element is invalid.

  E.g. it is not an HTMLMediaElement.
- `INVALID_CONTAINER_ELEMENT` = `7006`: Player failed to initialize because container element passed via the `containerEl` option is not valid.

  E.g. it is not a direct parent of the video element.
- `INVALID_ARGUMENT` = `7007`: Error raised when a method is passed an invalid argument.
- `WRONG_ORDER_OF_OPERATIONS` = `7008`: Error raised when two methods which depend on each other are called in the wrong order.
- `NOT_SUPPORTED` = `7009`: Error raised when calling a method which is not supported or passing arguments or a configuration of arguments that are not supported. This may also be platform dependent.
- `INVALID_CONFIGURATION` = `7100`: The provided `clpp.PlayerConfiguration` is invalid.
- `INVALID_LICENSE` = `7101`: The provided `license` (`clpp.ConstructorPlayerConfiguration#license`) does not exist or is invalid.
- `NO_ELEMENT` = `7102`: No DOM element or element ID was provided when initializing the player.
- `USER_ID_NOT_PROVIDED` = `7103`: Error raised when viewer ID is mandatory for the supplied license but it has not been provided.

  Viewer ID should be supplied via the `viewerId` (`clpp.ConstructorPlayerConfiguration#viewerId`) config. In case when DRMtoday DRM is used the viewer ID is automatically taken from the `drm.customData.userId` (`clpp.DrmConfiguration`) config.
- `KEY_LOAD_ERROR` = `7104`: Error raised when a key required to decrypt a media segment could not be loaded (e.g. AES key).
- `TIZEN_INTERNAL_ERROR` = `7200`: An internal (AVPlay) tizen error occurred.

  Please, refer to this link for more details about the nature of the error.

  The `data` (`clpp.Error#data`) property contains an object with the following properties:
  - `data.tizenerror` (`string | Object`): The AVPlay event type that reported the error, or the original error object.
- `CAF_INTERNAL_ERROR` = `7300`: An internal Chromecast CAF receiver error.

  Please refer to [CAF description](https://developers.google.com/cast/docs/caf_receiver/error_codes) for detailed info.

  The `data` (`clpp.Error#data`) property contains an object with the following properties:
  - `data.detailedErrorCode` (`number`): CAF error code.
  - `data.error` (`Error | Object`): original error.
  - `data.reason` (`string`): error reason.
- `INTERNAL_CAST_ERROR` = `8000`: An internal Cast Sender error.

  The `data` (`clpp.Error#data`) property contains an object with the following properties:
  - `data.detailedErrorCode` (`string`): Sender error code.
  - `data.details` (`Object`, optional): error details.
  - `data.reason` (`string`, optional): error reason.
- `CAST_API_NOT_READY` = `8001`: Cast API is not ready. Please check is Cast SDK included and does browser support SDK.
- `NO_RECEIVERS_AVAILABLE` = `8002`: Error indicating receivers are not currently available.
- `ALREADY_CASTING` = `8003`: Already casting error.
- `NO_CAST_SESSION` = `8004`: Cannot perform action as required cast session is not available.
- `CONVIVA_SDK_NOT_LOADED` = `9000`: This error is raised when trying to use the Castlabs Conviva analytics plugin without loading the Conviva SDK script.
- `CONVIVA_INVALID_CONFIGURATION` = `9001`: The provided conviva analytics configuration is invalid.
- `CONVIVA_RUNTIME_ERROR` = `9002`: Miscellaneous conviva plugin runtime error.
- `GL_CONTEXT_ERROR` = `9003`: Error code that indicates that the player was trying to initialize a WebGL context and failed.
- `GL_SHADER_ERROR` = `9004`: Error code that indicates that the player not able to compile a shader.
- `YOUBORA_SDK_MISSING` = `9100`: Youbora plugin is loaded, but required SDK has not been included.
- `YOUBORA_INVALID_CONFIGURATION` = `9101`: Passed configuration is insufficient to configure Youbora properly. Check if required fields, like `accountCode`, are passed.
- `YOUBORA_SDK_VERSION_NOT_SUPPORTED` = `9102`: The version of the provided Youbora SDK is not supported.
- `VIMOND_INVALID_CONFIGURATION` = `9200`: Passed configuration is insufficient to configure Vimond properly. Check if required fields, like `playServiceResponse`, are passed.
- `VIMOND_SESSION_ERROR` = `9201`: Generic Vimond Player Session error.

  The `data` (`clpp.Error#data`) property contains `clpp.net.Response`. If the service is unreachable then the `data.status` is -1.
- `MUXDATA_INVALID_CONFIGURATION` = `9300`: Passed configuration is insufficient to configure Mux Data properly. Check if required fields, like `envKey`, are passed.
- `MUX_SDK_MISSING` = `9301`: Mux data plugin is loaded, but required SDK has not been included.
- `MUXDATA_INIT_ERROR` = `9302`: An error occurred during the Mux Data session initialization.
- `IMA_SDK_MISSING` = `10000`: IMA SDK, required for ad insertion, has not been included on the page.
- `IMA_INVALID_CONFIGURATION` = `10001`: The provided IMA configuration is invalid.
- `IMA_UNSUPPORTED_PLATFORM` = `10002`: Cannot currently run IMA on given platform (i.e. platform does not support multiple video elements).
- `AD_ERROR` = `10003`: The ads manager failed when playing an ad.

  The `data` (`clpp.Error#data`) property contains an object with the following properties:
  - `data.errorType` (`clpp.ads.ErrorType`, optional): The type of the error.
- `SIMID_CONTAINER_MISSING` = `10100`: Triggered when no container could be found to add a SIMID creative.
- `BROADPEAK_SDK_MISSING` = `11000`: Broadpeak SDK has not been included on the page.
- `BROADPEAK_SESSION_ERROR` = `11001`: An error occurred when creating Broadpeak session.
- `FREEWHEEL_SDK_MISSING` = `12000`: FreeWheel SDK has not been included on the page.
- `FREEWHEEL_INVALID_CONFIGURATION` = `12001`: The provided FreeWheel configuration is invalid.
- `CONTENT_TRANSFORMATION_FAILED` = `14000`: The streaming engine failed when applying content workarounds.
- `SESSIONS_INVALID_CONFIGURATION` = `15000`: Passed configuration is insufficient to configure PRESTOplay Sessions properly. Check if required fields, like `apiUrl`, are passed.

## clpp.AbrConfiguration (typedef)

The `abr` (`clpp.BasePlayerConfiguration#abr`) subsection of player configuration.

Configuration of Adaptive Bitrate Streaming (ABR).

ABR is a feature of the player which allows it to automatically switch between video renditions based on network conditions in order to save bandwidth in low-bandwidth environments and provide smooth viewing experience.

Properties:

- `enabled` (`boolean`, optional), default `true`: Enable ABR.
- `defaultBandwidthEstimate` (`number`, optional): The default bandwidth estimate in bits per second (bps).

  This value is used for initial video track selection when there is no bandwidth estimation yet calculated by the player.
- `restrictions` (`clpp.Restrictions`, optional): Track restrictions to apply to ABR selection. Any track that fails to meet these restrictions will be ignored by the ABR algorithm.

  It is still possible to select the restricted tracks programatically via `setVideoTrack()` (`clpp.TrackManager#setVideoTrack`).

  If no tracks meet these restrictions the player will fall back to lowest resolution or bandwidth.
- `initialRestrictions` (`clpp.Restrictions`, optional): Track restrictions used for initial ABR selection at startup.

  This can be used e.g. in DRM multi-key scenarios, to ensure that the first selected track will be playable on any platform.
- `switchInterval` (`number`, optional), default `8`: The minimum amount of time that must pass between ABR rendition switches, in seconds.

  Beware of setting this value too low as it might degrade viewing experience.
- `bandwidthUpgradeTarget` (`number`, optional), default `0.85`: The fraction of the estimated bandwidth which we should try to use when upgrading.
- `bandwidthDowngradeTarget` (`number`, optional), default `0.95`: The largest fraction of the estimated bandwidth we should use. We should downgrade to avoid this.
- `useSwitchIntervalForInitialSwitch` (`boolean`, optional), default `false`: By default ABR algorithm switches video quality as soon as there is enough data to do it, initially ignoring `switchInterval` (`clpp.AbrConfiguration#switchInterval`) value.

  Pass in true to always honor `switchInterval` (`clpp.AbrConfiguration#switchInterval`).
- `useCmsd` (`boolean`, optional), default `true`: Enable the use of Common Media Server Data (CMSD) to make ABR decisions.

  It uses the `estimatedThroughputKbps (etp)` for bandwidth estimate and `maxSuggestedBitrateKbps (mb)` for maximum bandwidth limit.

## clpp.AdsConfiguration (typedef)

The `ads` (`clpp.BasePlayerConfiguration#ads`) subsection of player configuration.

Configuration for SGAI.

Properties:

- `hls` (`clpp.HlsAdsConfiguration`, optional): Configuration for HLS interstitial ads.
- `dash` (`clpp.DashAdsConfiguration`, optional): Configuration for DASH alternative MPD event ads.

## clpp.BroadpeakConfiguration (typedef)

The `broadpeak` (`clpp.BasePlayerConfiguration#broadpeak`) subsection of player configuration.

Configuration of Broadpeak analytics plugin.

Properties:

- `analyticsAddress` (`string`, optional): The address of the analytics server to send metrics to.
- `nanoCDNHost` (`string`, optional): LAN IP address of a gateway which hosts nanoCDN. It can also be a list of hosts separated by a comma (e.g. "192.168.1.1,192.168.10.1").
- `broadpeakDomainNames` (`string`, optional), default `""`: Tells Broadpeak SDK which stream URLs should be considered Broadpeak content and Broadpeak analytics session should be started for them. This is done based on domain names.

  The value can be:

  - simple value, e.g. "cdn.broadpeak.com"
  - comma separated list, e.g. "cdn.broadpeak.com,cdn2.broadpeak.com""
  - "*", meaning all domains are Broadpeak content
  - "", meaning no domains are Broadpeak content

  Example: "cdn.broadpeak.com" Broadpeak session will be started for all sources coming from "cdn.broadpeak.com" domain, sources from other domains are ignored by the Broadpeak plugin, they are played by the player without Broadpeak session.
- `uuid` (`string`, optional): The Unique User Identifier.
- `customParameters` (`Record<string, string>`, optional): Custom session parameters. Their meaning is defined by your Broadpeak setup.
- `sessionOptions` (`clpp.BroadpeakSessionOptions`, optional): Broadpeak streaming session options.
- `adParameters` (`Record<string, string>`, optional): Ad parameters for SSAI. These are key/value pairs for personalizing server-side inserted ads (SSAI). Their meaning is defined by your Broadpeak/ad server setup.

  To send ad parameters enable SSAI `adTracking` (`clpp.BroadpeakConfiguration#adTracking`).
- `adTracking` (`boolean`, optional), default `false`: Enable SSAI ad tracking.

## clpp.BroadpeakSessionOptions (typedef)

Type: `Record<string, any>`

Broadpeak streaming session options passed to SmartLib. Use StreamingSessionOptions constants as keys. See [Broadpeak session options docs](https://delivery-platform.broadpeak.tv/smartlib/public/advanced-features/session-options).

Example: Configure Broadpeak session options

```js
const player = new clpp.Player('video', {
  ...
  broadpeak: {
    sessionOptions: {
      [StreamingSessionOptions.GDPR_PREFERENCE]: StreamingSessionOptions.GDPR_CLEAR,
      [StreamingSessionOptions.SESSION_KEEPALIVE_FREQUENCY]: 5000,
    },
  },
  ...
});
```

## clpp.BufferInfo (class)

Constructor:

```ts
new clpp.BufferInfo(opt_delegate?: TimeRanges, opt_type?: 'total' | 'video' | 'audio' | 'text')
```

Buffer info represents ranges of buffered media both separately for each media track (video, audio and text) as well as the total overlap.

It can be used to check how much media is buffered and whether enough media is buffered to start or resume playback from a give position on the timeline.

This API is similar to [TimeRanges](https://developer.mozilla.org/en-US/docs/Web/API/TimeRanges).

Create a new instance.

Parameters:

- `opt_delegate` (`TimeRanges`, optional): Optional delegate. If specified ranges from the delegate will be returned
- `opt_type` (`'total' | 'video' | 'audio' | 'text'`, optional), default `total`: Optional type

### Methods

#### clpp.BufferInfo#start

```ts
start(index: number): number
```

Returns the time offset at which a specified time range begins.

Parameters:

- `index` (`number`): The range number to return the starting time for.

Returns: `number` - The time offset in seconds at which a specified time range begins

Throws:

- `clpp.Error` if the requested index is out of range

#### clpp.BufferInfo#end

```ts
end(index: number): number
```

Returns the time offset at which a specified time range ends.

Parameters:

- `index` (`number`): The range number to return the ending time for.

Returns: `number` - The time offset in seconds at which a specified time range ends

Throws:

- `clpp.Error` if the requested index is out of range

#### clpp.BufferInfo#bufferStart

```ts
bufferStart(): number | null
```

Gets the first timestamp in buffer.

Returns: `number | null` - The first buffered timestamp, in seconds, if |buffered| is non-empty; otherwise, return null.

#### clpp.BufferInfo#bufferEnd

```ts
bufferEnd(): number | null
```

Gets the last timestamp in buffer.

Returns: `number | null` - The last buffered timestamp, in seconds, if |buffered| is non-empty; otherwise, return null.

#### clpp.BufferInfo#isBuffered

```ts
isBuffered(time: number, opt_includeGaps?: boolean, opt_smallGapLimit?: number): boolean
```

Determines if the given time is inside a buffered range.

The default behavior includes gaps, meaning if the playhead is in a gap, it is considered buffered.

Parameters:

- `time` (`number`): time in seconds
- `opt_includeGaps` (`boolean`, optional), default `true`: If false, gaps will not be included, meaning if the time is in a gap it will be considered un-buffered. The default is to consider gaps as buffered.
- `opt_smallGapLimit` (`number`, optional), default `0`: If there is a small gap between the position and the buffer start, consider it as buffered

Returns: `boolean` - `true` if the given time is buffered.

#### clpp.BufferInfo#bufferedAheadOf

```ts
bufferedAheadOf(time: number, opt_includeGaps?: boolean): number
```

Computes how far ahead of the given timestamp is buffered. By default this does not include gaps, hence only the amount of real buffered data is returned.

Parameters:

- `time` (`number`): The time in seconds to measure the buffer from.
- `opt_includeGaps` (`boolean`, optional), default `false`: If true, gaps will be included in the calculation.

Returns: `number` - The number of seconds buffered, in seconds, ahead of the given time.

## clpp.ChromecastConfiguration (typedef)

**Experimental:** may change without a major release.

The `chromecast` (`clpp.BasePlayerConfiguration#chromecast`) subsection of player configuration.

Chromecast configuration.

Properties:

- `useSenderAbrConfig` (`boolean`, optional), default `false`: Pass sender `ABR configuration` (`clpp.AbrConfiguration`) to the receiver.
- `useSenderStreamingConfig` (`boolean`, optional), default `false`: Pass sender `streaming configuration` (`clpp.StreamingConfiguration`) to the receiver.

## clpp.CmcdConfiguration (typedef)

The `cmcd` (`clpp.BasePlayerConfiguration#cmcd`) subsection of player configuration.

Common Media Client Data (CMCD) configuration.

Properties:

- `enabled` (`boolean`, optional), default `false`: Enable CMCD.

  This is disabled by default to avoid adding headers or query parameters to HTTP requests, because that might cause some servers to reject the requests.
- `version` (`1`, optional), default `1`: The only available version is 1. Support for CMCD v2 is coming soon.
- `sessionId` (`string`, optional): Session ID to be sent in the CMCD headers. If undefined, the player will generate a session ID.
- `contentId` (`string`, optional): A unique string identifying the current content. Maximum length is 64 characters. This value is consistent across multiple different sessions and devices and is defined and updated at the discretion of the service provider.
- `rtpMultiplier` (`number`, optional), default `5`: A coefficient which multiplies the value of requested maximum throughput (rtp) property. If rtpMultiplier=1 the value of rtp is calculated by the SDK as the min value needed to avoid buffering.
- `deliveryMode` (`'query' | 'headers'`, optional), default `'headers'`: Defines how CMCD data is transmitted. Use 'query' to send data via URL query parameter or 'headers' to send it via HTTP headers.

## clpp.CmsdConfiguration (typedef)

The `cmsd` (`clpp.BasePlayerConfiguration#cmsd`) subsection of player configuration.

Common Media Server Data (CMSD) configuration.

Properties:

- `enabled` (`boolean`, optional), default `true`: Enable CMSD.

## clpp.CodecSwitchingStrategy (enum)

Codec switching strategy is configuration for streams which contain tracks encoded by multiple codecs.

Values:

- `PREVENT` = `prevent`: Play only tracks with the same codec, one codec is selected and any tracks with a different codec are ignored.
- `SMOOTH` = `smooth`: Play tracks with different codecs.

  **Note:** Some devices expose the `MediaSource.changeType()` API but are known to have unreliable support, which can lead to issues like playback hanging after the `changeType()` request. `SMOOTH` is therefore currently disabled on **all smart TV / CTV platforms** (Tizen, webOS, Hisense, Chromecast); on those devices the player falls back to `PREVENT` regardless of this setting. Edge on Windows is also known to be problematic and may be added to the exclusion list in the future.

## clpp.CompanionSdk (typedef)

The purpose of companion SDK info is to be able to send info about react-native SDK to our analytics

Properties:

- `name` (`string`): Companion SDK name
- `version` (`string`): Companion SDK version

## clpp.ConnectivityCheckConfiguration (typedef)

The `connectivityCheck` (`clpp.BasePlayerConfiguration#connectivityCheck`) subsection of player configuration.

Connectivity checker configuration.

This allows you to set up an independent endpoint for connectivity check which is pinged periodically in order to determine network connectivity of the device.

Properties:

- `url` (`string`): Connectivity check URL.
- `attemptParameters` (`clpp.net.AttemptParameters`, optional): Attempt parameters.
- `method` (`string`, optional), default `"HEAD"`: HTTP method to use for ping.

## clpp.ContentSteeringConfiguration (typedef)

The `contentSteering` (`clpp.BasePlayerConfiguration#contentSteering`) subsection of player configuration.

Configuration of Content Steering.

DASH is supported.

Properties:

- `enabled` (`boolean`, optional), default `true`: **Applies to:** dash Enable content steering.
- `attemptParameters` (`clpp.net.AttemptParameters`, optional): Retry parameters for Content Steering server requests.

## clpp.ConvivaConfiguration (typedef)

The `conviva` (`clpp.BasePlayerConfiguration#conviva`) subsection of player configuration.

Conviva analytics plugin configuration.

For Conviva type definitions and constants see [Conviva documentation](https://docs.conviva.ai/sensor/javascript/javascript-constants-metadata/).

Properties:

- `customerKey` (`string`): Unique customer key provided by Conviva.
- `viewerId` (`string`): The viewer identifier. This should be unique for each user.
- `serviceUrl` (`string`, optional): The Conviva Touchstone service URL for validation purposes.

  Touchstone is Conviva's validation tool, use this to test the Conviva integration and then unset it.
- `defaultResource` (`string`, optional): The default video server resource name to report. A resource is the origin server or CDN of the video.

  Used when Conviva cannot automatically infer the resource name from stream URL.

  Examples: EDGECONVIVA SDKT-1, AKAMAI-FREE, LEVEL3-PREMIUM...
- `enableAdInsights` (`boolean`, optional), default `false`: Enable to report ad analytics.
- `customTags` (`Record<string, unknown>`, optional): Custom metadata.

  The keys have to be set up in the your Conviva account to show up in reports.
- `playerName` (`string`, optional), default `'CastlabsPlayer'`: Player name that will be reported to Conviva.
- `deviceType` (`string`, optional): Device type. Should be one of the values defined in [Conviva.Constants.DeviceType](https://docs.conviva.ai/sensor/javascript/javascript-constants-metadata/).

  By default the value is derived from `userAgent`.
- `deviceCategory` (`string`, optional): Device category. Should be one of the values defined in [Conviva.Constants.DeviceCategory](https://docs.conviva.ai/sensor/javascript/javascript-constants-metadata/).

  By default the value is derived from `userAgent`.
- `deviceBrand` (`string`, optional): Device brand.

  By default the value is derived from `userAgent`.
- `deviceMetadata` (`Record<string, unknown>`, optional): Device metadata to pass directly to Conviva. The keys of the object are defined in [Conviva.Constants.DeviceMetadata](https://docs.conviva.ai/sensor/javascript/javascript-constants-metadata/).

  By default device metadata is derived from `userAgent`.
- `connectionType` (`'WiFi' | 'Ethernet' | '2G' | '3G' | '4G' | 'OTHER'`, optional): Type of internet connection.
- `convivaSdkLogLevel` (`number`, optional), default `Conviva.Constants.LogLevel.NONE`: Conviva SDK log level. Should be one of the values defined in [Conviva.Constants.LogLevel](https://docs.conviva.ai/sensor/javascript/javascript-constants-metadata/).

Example: Set device metadata for Conviva analytics.

```js
conviva: {
    deviceMetadata: {
      [Conviva.Constants.DeviceMetadata.TYPE]: Conviva.Constants.DeviceType.SMARTTV,
      [Conviva.Constants.DeviceMetadata.CATEGORY]: Conviva.Constants.DeviceCategory.LG_TV,
      [Conviva.Constants.DeviceMetadata.BRAND]: 'LG',
      [Conviva.Constants.DeviceMetadata.MANUFACTURER]: 'LG',
      [Conviva.Constants.DeviceMetadata.MODEL]: 'UJ701V',
      [Conviva.Constants.DeviceMetadata.OS_NAME]: 'WebOS',
      [Conviva.Constants.DeviceMetadata.OS_VERSION]: '3.5',
    }
  }
```

## clpp.DashAdsConfiguration (typedef)

Configuration for DASH alternative MPD event ads.

Properties:

- `enable` (`boolean`, optional), default `true`: Enable support for DASH alternative MPD events.

## clpp.DrmConfiguration (typedef)

The `drm` (`clpp.BasePlayerConfiguration#drm`) subsection of player configuration.

Configuration of digital rights management (DRM), used to play protected content with any DRM key system supported by the platform.

This configuration focuses on the client-side aspects of DRM and CDM configuration.

DRM provider configuration such as license server, server certificate etc. is defined via `DrmEnvironment` (`clpp.drm.DrmEnvironment`). The SDK comes with built-in environment for DRMtoday and several other providers. To configure a new DRM environment call `registerDrmEnvironment()` (`clpp.drm.registerDrmEnvironment`).

Properties:

- `env` (`string`): Name of DRM environment to use. Configure the name of a built-in environment or a custom one registered via `registerDrmEnvironment()` (`clpp.drm.registerDrmEnvironment`).

  Built-in environments are: 'DRMtoday', 'DRMtoday_STAGING' and 'HeaderDrm'.

  Import module `cl.onboard` in order to enable the 'DRMtodayOnboard' environment.

  Import module `cl.verimatrix` in order to enable the 'VerimatrixVCAS' environment.
- `customData` (`Record<string, any>`, optional): Values passed to the selected DRM environment when it builds the per-key-system configuration. Which keys are meaningful is up to the environment; please refer to the manual.
- `preferredDrmSystem` (`clpp.drm.KeySystem`, optional): Some platforms support multiple key systems, e.g. Widevine and Playready.

  By default the player automatically selects the suitable key system for the platform.

  Use this option to specify the preferred key system. If it does not work the player will fall back to other key systems supported by the platform.
- `emeApi` (`clpp.drm.eme.EmeFactory.Apis`, optional): Some platforms support multiple versions of the EME API. Even though there is only one standard, for historical reasons multiple versions of the EME API exist.

  Specifically Safari and Tizen come with custom versions of EME API.

  By default the player automatically selects the suitable version of EME API for the platform.

  Use this option to override which EME API version should be used on platforms where multiple versions are available. If it is not possible to honor the configuration, the player will fall back to any other suitable version of the EME API on the platform.

  To play protected content on Safari use MSE-based playback configure `STANDARD` (`clpp.drm.eme.EmeFactory.Apis`).
- `attemptParameters` (`clpp.net.AttemptParameters`, optional): Retry behavior for DRM license and server certificate requests. By default requests are attempted just once and with no timeout.
- `enforceSingleSession` (`boolean`, optional), default `false`: Enable to reuse one media key session instead of opening a separate one per init data, merging the init data of a period into the existing session. This avoids redundant license requests for multi-key content.

  Has no effect on FairPlay.

  In case of 'DRMtoday' and 'DRMtoday_STAGING' environment this is always enabled and changing this option has no effect.
- `delayLicenseRequestUntilPlayed` (`boolean`, optional), default `false`: Enable to hold the initial license request back until playback actually starts, instead of issuing it while the player is still paused.

  In a live scenario this spreads the load, rather than having every client ask for a license the moment the stream is opened. Only the first request is delayed.
- `offlineId` (`string`, optional): Identifier used to persist the DRM session.

  It is the key the session is stored under in the persistent session storage (see `clpp.persistent`), and setting it makes the player ask the DRM license server for a persistent license.

  Set this only if the DRM license server supports persistent licenses.
- `enableSessionCacheForSkd` (`boolean`, optional), default `false`: **Applies to:** safari Serve FairPlay SKD init data from the DRM session cache instead of handling every `encrypted` event.

  Native Safari sometimes emits duplicate `encrypted` events for a key that was already fetched. By default the player handles each one, which can mean redundant license requests but avoids the decryption errors that dropping them may cause. Enabling the cache removes those redundant requests, at the cost of possibly more 3016 decode errors on Safari with native playback and SKD initialization.
- `ignoreUnrecognizedInitData` (`boolean`, optional), default `true`: Enable to skip init data whose key ID cannot be parsed, instead of passing it to the CDM. Malformed init data would otherwise lead to a failed license request.

  Disable this in case the init data is in fact valid but the player's parsers cannot read it for any reason.
- `widevineVersion` (`string`, optional), default `"com.widevine.alpha"`: The version of the Widevine key system. This option may be used in order to enable experimental versions of the Widevine key system such as "com.widevine.alpha.experiment" or "com.widevine.alpha.experiment2".

  The value has to start with `com.widevine.alpha`. If the experimental key system turns out to be unavailable, the player falls back to standard Widevine.

## clpp.DrmConfigurationResolver (callback)

```ts
function(args: clpp.DrmResolverArgs): clpp.DrmConfiguration | null
```

DRM configuration resolver callback.

The resolver may be used to decide on DRM configuration based on the content of the manifest. The return value replaces the `drm` (`clpp.BasePlayerConfiguration#drm`) player configuration.

Parameters:

- `args` (`clpp.DrmResolverArgs`): Information about the loaded content.

Returns: `clpp.DrmConfiguration | null` - The DRM configuration to use, or null to use no DRM configuration, e.g. to rely on the license URLs from the manifest.

Example: Select DRM environment based on Laurl in the DASH manifest

```js
player.open({
  source: '...',
  drmResolver: (info) => {
    if (info.hasLaurl) {
      // Use DASH manifest-based DRM environment
      return null;
    } else {
      // Use DRMtoday staging environment
      return {
        env: 'DRMtoday_STAGING',
        // ...
      };
    }
  },
});
```

## clpp.DrmInfo (typedef)

DRM configuration for a single key system.

Properties:

- `keySystem` (`clpp.drm.KeySystem`): The key system, e.g., "com.widevine.alpha".
- `licenseServerUri` (`string`): *Filled in by DRM config if missing.*

  The license server URI.
- `distinctiveIdentifierRequired` (`boolean`, optional), default `false`: *Can be filled in by advanced DRM config.*

  True if the application requires the key system to support distinctive identifiers.
- `persistentStateRequired` (`boolean`, optional), default `false`: *Can be filled in by advanced DRM config.*

  True if the application requires the key system to support persistent state, e.g., for persistent license storage.
- `audioRobustness` (`string | Array<string>`): *Defaults to '', i.e., no specific robustness required.  Can be filled in by advanced DRM config.*

  A key-system-specific string that specifies a required security level.
- `videoRobustness` (`string | Array<string>`): *Defaults to '', i.e., no specific robustness required.  Can be filled in by advanced DRM config.*

  A key-system-specific string that specifies a required security level.
- `serverCertificate` (`Uint8Array`, optional): *Defaults to null, i.e., certificate will be requested from the license server if required.  Can be filled in by advanced DRM config.*

  A key-system-specific server certificate used to encrypt license requests. Its use is optional and is meant as an optimization to avoid a round-trip to request a certificate.
- `initData` (`Array<clpp.InitDataOverride>`, optional): A list of initialization data which override any initialization data found in the content.  See also `clpp.InitDataOverride`.
- `keyIds` (`Array<string>`): If not empty, it contains the default key IDs for this key system, as lowercase hex strings.
- `periodId` (`string`, optional): The ID of the period that these DRM infos belong to.

## clpp.DrmResolverArgs (typedef)

Arguments passed to the DRM configuration resolver callback.

Properties:

- `hasLaurl` (`boolean`, optional): Indicates whether the manifest contains at least one License Acquisition URL (dashif:Laurl).

## clpp.Error.Category (enum)

Enum for error categories.

Values:

- `NETWORK` = `1`: Errors from the network stack.
- `TEXT` = `2`: Errors parsing text streams.
- `MEDIA` = `3`: Errors parsing or processing audio or video streams.
- `MANIFEST` = `4`: Errors parsing the Manifest.
- `STREAMING` = `5`: Errors related to streaming.
- `DRM` = `6`: Errors related to DRM.
- `PLAYER` = `7`: Miscellaneous errors from the player.
- `CAST` = `8`: Errors related to cast.
- `PLUGIN` = `9`: Errors related to plugins.
- `ADS` = `10`: Errors related to ads.

## clpp.Error.Severity (enum)

Enum for error severity.

Values:

- `RECOVERABLE` = `1`: An error occurred that the player will try to recover from. If retrying continues to fail, the player might still issue a FATAL error. A good example for this is a failing download. The first failure might be reported as a recoverable error, but if the download continues to fail, the error will turn into a fatal error.
- `FATAL` = `2`: A fatal error that the player can not recover from. Usually this stops playback and loading and you want to release the player before you try again.

## clpp.EventCallback (typedef)

Type: `EventListener | function`

The type for event listener callback functions.

## clpp.FairplayDrmSystem (typedef)

The main property is the `licenseUrl` to the DRM backend, but you would usually also implement at least some of the network modifier. This can be used for example to add some headers to the license request, or to access and even modify the responses.

Properties:

- `licenseUrl` (`string`, optional): The URL to the license server.
- `certificateUrl` (`string`, optional): The URL to the certificate.
- `individualizationServer` (`string`, optional): The server that handles an 'individualization-request'. If the server isn't given, it will default to the license server.
- `modifiers` (`clpp.drm.LicenseModifiers`, optional): A set of callbacks to perform modifications on license/certificate requests and/or responses.

## clpp.FreeWheelConfiguration (typedef)

The `freewheel` (`clpp.BasePlayerConfiguration#freewheel`) subsection of player configuration.

Configuration of FreeWheel ads (CSAI).

Properties:

- `networkId` (`number`, optional): The network ID of the distributor.
- `serverUrl` (`string`, optional): Ad server URL.
- `profileId` (`string`, optional): Name of global profile.
- `videoAssetId` (`string | number`, optional): The ID of the video asset which correspond to the ad request.
- `siteSectionId` (`string | number`, optional): The ID of the site section which correspond to the ad request.
- `pods` (`Array<clpp.FreeWheelPod>`, optional): List of temporal slots which should be added to the context.
- `keyValues` (`Record<string, string>`, optional): Key value pairs that will be passed to the context.
- `parameters` (`Array<clpp.FreeWheelParameter>`, optional): Additional parameters that will be passed to the context.

## clpp.FreeWheelParameter (typedef)

FreeWheel parameter.

Properties:

- `name` (`string`, optional): Name of the parameter to be set.
- `value` (`any`, optional): Value for the parameter
- `level` (`number`, optional): Level of the parameters, must be one of values provided by FreeWheel SDK ( `PARAMETER_LEVEL_GLOBAL` or `PARAMETER_LEVEL_OVERRIDE`).

## clpp.FreeWheelPod (typedef)

FreeWheel pod definition.

Properties:

- `id` (`string`, optional): Custom ID of the slot.
- `position` (`number`, optional): Time position of the slot in seconds.
- `type` (`clpp.ads.PodType`, optional): Type of slot.
- `slotProfile` (`string`, optional): Profile name of the slot.
- `cuepointSequence` (`number`, optional): Cuepoint sequence override.
- `maxDuration` (`number`, optional): Maximum duration of the slot allowed in seconds.
- `minDuration` (`number`, optional): Minimum duration of the slot allowed in seconds.
- `acceptContentType` (`string`, optional): Accepted content types, use "," as delimiter.

## clpp.HlsAdsConfiguration (typedef)

Configuration of HLS interstitial ads.

Properties:

- `enable` (`boolean`, optional), default `true`: Enable support for HLS interstitials.
- `resolutionOffsetSec` (`number`, optional), default `35`: **Deprecated.** How many seconds ahead of an interstitial date range should its interstitial assets or asset lists be requested and preloaded.

## clpp.HlsSmpteConfiguration (typedef)

The `hlssmpte` (`clpp.BasePlayerConfiguration#hlssmpte`) subsection of player configuration.

Configuration or SMPTE-TT subtitles in HLS.

Properties:

- `patchMetadataTrack` (`boolean`, optional), default `false`: On Safari sometimes SMPTE-TT subtitles do not get displayed due to an issue in Safari. In that case enable this option to work around the issue.
- `timestampOffset` (`number`, optional), default `0`: Offset which is applied to cue timestamps.

## clpp.HtmlCueConfiguration (typedef)

The `htmlcue` (`clpp.BasePlayerConfiguration#htmlcue`) subsection of player configuration.

Configuration of HTML-based rendering of subtitles.

Properties:

- `stretchSmpteImage` (`boolean`, optional), default `false`: This configuration applies to image-based subtitles.

  Enable to stretch subtitle images (like SMPTE-TT or IMSC1) to fit the surrounding container.
- `enableResizeObserver` (`boolean`, optional), default `true`: By default `ResizeObserver` API is used to detect resize of viewport and stretch or shrink subtitle display area accordingly.

  On smart TVs the viewport size is fixed making this feature unnecessary and in order to optimize performance it is recommended to disable this.

## clpp.IPlayerSurface (interface)

Player Surface is the area of UI/DOM where the video will be displayed. It also includes a container area used for rendering subtitles and displaying ads and ad overlays.

### Methods

#### clpp.IPlayerSurface#getContainer

```ts
getContainer(): Element | null
```

Returns the container element. Returns null if container is disabled.

Returns: `Element | null` - The container element, or `null` if the container is disabled.

#### clpp.IPlayerSurface#getMedia

```ts
getMedia(): HTMLMediaElement | null
```

Returns the primary media element or null.

Returns: `HTMLMediaElement | null` - The `<video>` or `<audio>` element, or `null` if none exists.

#### clpp.IPlayerSurface#getCastElement

```ts
getCastElement(): Element | null
```

Returns the cast media player element on Chromecast Web Receiver. Note that this will return an element only when using `<cast-media-player>` instead of `<video>` or `<audio>` tag.

Returns: `Element | null` - The `<cast-media-player>` element, or `null` if not used.

#### clpp.IPlayerSurface#release

```ts
release()
```

Request that this object release all internal references.

#### clpp.IPlayerSurface#addElementToContainer

```ts
addElementToContainer(element: Element, opt_fill?: boolean, opt_prepend?: boolean)
```

Adds the given element to the container. Throws an error if no container is available.

Parameters:

- `element` (`Element`): The element to add
- `opt_fill` (`boolean`, optional): If true, the css fill class will be applied
- `opt_prepend` (`boolean`, optional): If true, appends the element at the beginning

Throws:

- An error if no container element is available

#### clpp.IPlayerSurface#removeElementFromContainer

```ts
removeElementFromContainer(element: Element)
```

Removes an element from the container.

Parameters:

- `element` (`Element`): The element to remove

Throws:

- An error if no container element is available

## clpp.ITextDisplayer (interface)

An interface for modules which display subtitle text os overlay over the video element.

Subtitles can be styled either via player configuration or directly by calling methods of `clpp.ITextDisplayer`.

### Methods

#### clpp.ITextDisplayer#getBackgroundColor

```ts
getBackgroundColor(): string | null
```

Returns the background color.

Returns: `string | null` - The background color as CSS expression.

#### clpp.ITextDisplayer#setBackgroundColor

```ts
setBackgroundColor(color: string)
```

Sets the background color.

Parameters:

- `color` (`string`): The background color as CSS expression.

#### clpp.ITextDisplayer#getWindowColor

```ts
getWindowColor(): string | null
```

Returns the window color, i.e. a box around a cue.

Returns: `string | null` - The window color as CSS expression.

#### clpp.ITextDisplayer#setWindowColor

```ts
setWindowColor(color: string)
```

Sets the window color, i.e. a box around a cue.

Please note that the HTML text displayer doesn't support this option at the moment.

Parameters:

- `color` (`string`): The window color as CSS expression.

#### clpp.ITextDisplayer#getFontFamily

```ts
getFontFamily(): string | null
```

Returns the font family.

Returns: `string | null` - The font family as CSS expression.

#### clpp.ITextDisplayer#setFontFamily

```ts
setFontFamily(family: string)
```

Sets the font family.

Parameters:

- `family` (`string`): The font family as CSS expression.

#### clpp.ITextDisplayer#getFontColor

```ts
getFontColor(): string | null
```

Returns the font color.

Returns: `string | null` - The font color as CSS expression.

#### clpp.ITextDisplayer#setFontColor

```ts
setFontColor(color: string)
```

Sets the font color.

Parameters:

- `color` (`string`): The font color as CSS expression.

#### clpp.ITextDisplayer#getFontSize

```ts
getFontSize(): string | null
```

Returns the font size.

Returns: `string | null` - The font size as CSS expression.

#### clpp.ITextDisplayer#setFontSize

```ts
setFontSize(fontSize: string)
```

Sets the font size.

If defined, it takes precedence over the `fontSizePercent`.

Parameters:

- `fontSize` (`string`): The font size as CSS expression.

#### clpp.ITextDisplayer#getFontSizePercent

```ts
getFontSizePercent(): number | null
```

Returns the font size percent.

Returns: `number | null` - The font size percent.

#### clpp.ITextDisplayer#setFontSizePercent

```ts
setFontSizePercent(fontSize: number)
```

Sets the font size percent.

The font size percent is relative to the video height. The actual font size will be adjusted automatically on video size change, for example when entering fullscreen mode. Please note that the native text displayer doesn't support this option at the moment.

Parameters:

- `fontSize` (`number`): The font size percent. Default value is `1/15`.

#### clpp.ITextDisplayer#getEdgeColor

```ts
getEdgeColor(): string | null
```

Returns the edge color.

Returns: `string | null` - The edge color as CSS expression.

#### clpp.ITextDisplayer#setEdgeColor

```ts
setEdgeColor(val: string)
```

Sets the edge color.

Parameters:

- `val` (`string`): The edge color as CSS expression.

#### clpp.ITextDisplayer#getEdgeType

```ts
getEdgeType(): clpp.text.EdgeType | null
```

Returns the edge type.

Returns: `clpp.text.EdgeType | null` - The edge type.

#### clpp.ITextDisplayer#setEdgeType

```ts
setEdgeType(type: clpp.text.EdgeType | null)
```

Sets the edge type.

Parameters:

- `type` (`clpp.text.EdgeType | null`): The edge type.

## clpp.ImaConfiguration (typedef)

The `ima` (`clpp.BasePlayerConfiguration#ima`) subsection of player configuration.

Configuration of Google IMA ads plugin (CSAI).

On devices such as smart TVs (LG, Samsung) and iOS IMA SDK switches to so called "custom playback mode" due to the lack of support for multiple video decoders. Custom playback mode is experimental in the IMA SDK, it may exhibit slightly different behavior and have some limitations.

Properties:

- `adTagUrl` (`string`): VAST or VMAP URL.
- `isVast` (`boolean`, optional), default `false`: Set to true when `adTagUrl` (`clpp.ImaConfiguration#adTagUrl`) is a VAST file.
- `bitrate` (`number`, optional): Maximum recommended bitrate. The value is in kbit/s. See original [IMA docs](https://developers.google.com/interactive-media-ads/docs/sdks/html5/client-side/reference/class/google.ima.AdsRenderingSettings#google.ima.AdsRenderingSettings.bitrate).
- `disableCustomPlayback` (`boolean`, optional), default `false`: Disable IMA SDK on devices in custom playback mode. These are Samsung TV, LG TV and iPhone.

  This may be useful in case of any issues with ad playback on those platforms.
- `enablePreloading` (`boolean`, optional), default `true`: Enable preloading of video assets. See original [IMA docs](https://developers.google.com/interactive-media-ads/docs/sdks/html5/client-side/reference/class/google.ima.AdsRenderingSettings#google.ima.AdsRenderingSettings.enablePreloading).
- `loadVideoTimeout` (`number`, optional), default `8000`: Timeout (in milliseconds) to be applied when loading the ad media file. See original [IMA docs](https://developers.google.com/interactive-media-ads/docs/sdks/html5/client-side/reference/class/google.ima.AdsRenderingSettings#google.ima.AdsRenderingSettings.loadVideoTimeout).
- `mimeTypes` (`Array<string>`, optional): MIME types of the ad media files, only ads with one of the listed MIME types will be played.

  By default the SDK selects MIME types based on player capabilities. See original [IMA docs](https://developers.google.com/interactive-media-ads/docs/sdks/html5/client-side/reference/class/google.ima.AdsRenderingSettings#google.ima.AdsRenderingSettings.mimeTypes).
- `playAdsAfterTime` (`number`, optional): For VMAP and ad rules playlists, ignore all ads scheduled before this content time. See original [IMA docs](https://developers.google.com/interactive-media-ads/docs/sdks/html5/client-side/reference/class/google.ima.AdsRenderingSettings#google.ima.AdsRenderingSettings.playAdsAfterTime).
- `useStyledLinearAds` (`boolean`, optional): Render linear ads with full UI styling. See original [IMA docs](https://developers.google.com/interactive-media-ads/docs/sdks/html5/client-side/reference/class/google.ima.AdsRenderingSettings#google.ima.AdsRenderingSettings.useStyledLinearAds).
- `uiElements` (`Array<string>`, optional): Specifies the UI elements that should be displayed. See original [IMA docs](https://developers.google.com/interactive-media-ads/docs/sdks/html5/client-side/reference/class/google.ima.AdsRenderingSettings#google.ima.AdsRenderingSettings.uiElements).

## clpp.InitDataOverride (typedef)

Explicit initialization data, which override any initialization data in the content. The initDataType values and the formats that they correspond to are specified [here](https://w3c.github.io/encrypted-media/format-registry/initdata/).

Properties:

- `initData` (`Uint8Array`): Initialization data in the format indicated by initDataType.
- `initDataType` (`string`): A string to indicate what format initData is in.
- `keyId` (`string`, optional): The key ID that corresponds to this initData.
- `periodId` (`string`, optional): The period ID.

## clpp.InitDataTransformerParams (typedef)

Parameters passed to `clpp.drm.InitDataTransformer`. They could be used to customize the behavior of provided initDataTransformer modifier.

Properties:

- `playerConfig` (`clpp.PlayerConfiguration`, optional): The current player configuration.
- `initData` (`Uint8Array`, optional): The initData from `encrypted` event.
- `initDataType` (`string`, optional): The initData type from `encrypted` event.
- `drmInfo` (`clpp.DrmInfo | null`, optional): The current DRM info.
- `drmSystemConfig` (`clpp.FairplayDrmSystem | clpp.PlayreadyDrmSystem | clpp.WidevineDrmSystem`, optional): The current DRM system configuration.
- `sessionContext` (`clpp.SessionContext`, optional): The current session context.
- `emeApi` (`clpp.drm.eme.EmeFactory.Apis`, optional): EME API currently in use.

## clpp.ManifestConfiguration (typedef)

The `manifest` (`clpp.BasePlayerConfiguration#manifest`) subsection of player configuration.

Configuration of DASH manifests, HLS playlists and MSS manifests.

Properties:

- `attemptParameters` (`clpp.net.AttemptParameters`, optional): Configure recovery behavior for when the player fails to fetch the manifest. Configure how many times, how often to retry the request etc.

  This applies only to the manifest, not to media segments or other data.
- `availabilityWindowOverride` (`number`, optional): The duration of live stream DVR window in seconds, analogous to `MPD@timeShiftBufferDepth` in DASH.

  By default DVR window is established based on the DASH manifest, HLS playlist or MSS manifests.

  This option allows a client-side override of the DVR window duration.
- `clockSyncUri` (`string`, optional): **Applies to:** dash By default clock sync in live DASH streams is done based on the `UTCTiming` element.

  This option allows a client-side override of the `UTCTiming` element or it can be used for DASH manifests where the `UTCTiming` element is missing.

  Pass in the URL to a clock sync server.

  The "Date" header from the HTTP response from this URL will be used to determine the current time. (According to the urn:mpeg:dash:utc:http-head:2014 scheme.)
- `ignoreDrmInfo` (`boolean`, optional), default `false`: **Applies to:** dash By default in DASH DRM information can be signalled both in the manifest and inside media segments.

  Use this override to ignore DRM information in the manifest and rely only on DRM information in media segments instead.

  This can be used to work around issues with `ContentProtection` signalling in the manifest.
- `xlinkFailGracefully` (`boolean`, optional), default `false`: **Applies to:** dash In DASH use this to keep parsing when an `xlink:href` cannot be resolved, instead of failing playback.

  If true, when `xlink:href` resolution fails the element falls back to the inline contents it already carries and parsing continues. If false, the error is propagated to the application and playback fails.
- `autoCorrectDrift` (`boolean`, optional), default `true`: **Deprecated.** If true, ignore the availabilityStartTime in the DASH manifest and instead use the segments to determine the live edge. This allows us to play streams that have a lot of drift. If false, we can't play content where the manifest specifies segments in the future.
- `liveRefreshPeriod` (`number`, optional): **Applies to:** hls, mss How often a live manifest gets reloaded by the player in seconds.

  By default the period is based on the DASH manifest, HLS playlist or MSS manifests.

  This option allows a client-side override for HLS and MSS.
- `playreadyVersion` (`'4.0.0.0' | '4.1.0.0' | '4.2.0.0' | '4.3.0.0'`, optional): **Applies to:** dash, mss Some CDMs may accept only certain values of PlayReady WRMHEADER header.

  This option allows a client-side override of the WRMHEADER header for cases where it is not possible to change the manifest and the platform accepts a different version from the one declared in the manifest.
- `hlsDefaultCodecs` (`string`, optional), default `'avc1.42E01E,mp4a.40.2'`: **Applies to:** hls Codecs of HLS variant.

  By default the HLS playlist carries codec information and the player takes it from there. However declaring codec information is not strictly required by the HLS spec so there might be playlists without it.

  Use this option to define codecs client-side. The value is a list of codecs separated by comma (video,audio).  If a stream is video-only or audio-only a single codec should be passed in.
- `timeline` (`clpp.TimelineConfiguration`, optional): Configuration of the timeline.

## clpp.MediaSourceConfiguration (typedef)

The `mediaSource` (`clpp.BasePlayerConfiguration#mediaSource`) subsection of player configuration.

Media source configuration.

Properties:

- `codecSwitchingStrategy` (`clpp.CodecSwitchingStrategy`, optional), default `PREVENT`: By default the player only plays tracks with the same codec, if the stream contains tracks encoded with multiple codecs one codec is selected and the others are ignored.

  To enable full support for streams with multiple codecs configure `SMOOTH` (`clpp.CodecSwitchingStrategy#SMOOTH`).

## clpp.MseConfiguration (typedef)

The `mse` (`clpp.BasePlayerConfiguration#mse`) subsection of player configuration.

Configuration of MSE-based playback. This is the default on most browsers and smart TVs.

Properties:

- `sendPlaybackSessionIdHeader` (`boolean`, optional), default `false`: Enable to send playback session ID along with each request. This allows for easy mapping between HTTP requests and a specific playback session.

  The session ID is sent in HTTP header `X-Playback-Session-Id`.

  It is disabled by default to avoid adding header to HTTP requests, because that might cause some servers to reject the request.

## clpp.MuxDataConfiguration (typedef)

The `muxdata` (`clpp.BasePlayerConfiguration#muxdata`) subsection of player configuration.

Configuration of Mux Data analytics.

Properties:

- `envKey` (`string`): Your MUX Data environment key.
- `muxLib` (`Object`, optional): Reference to MUX Data SDK.

  By default the player looks for the MUX Data SDK in the global namespace variable `window.mux`.

  Alternatively you can pass it in directly here.
- `muxOptionsOverride` (`clpp.MuxOverride`, optional): Pass additional or overriding MUX SDK options, which will be passed to the call of `mux.init()`.

## clpp.MuxOptionsData (typedef)

The `data` (`clpp.MuxOverride#data`) subsection of MUX Data configuration.

MUX Data options metadata.

Properties:

- `env_key` (`string`): A key identifying a MUX Data environment/bucket/project.
- `video_id` (`string`, optional): Your internal ID for the video.
- `video_title` (`string`, optional): Title of the video player (e.g.: 'Awesome Show: Pilot')
- `viewer_user_id` (`string`, optional): An ID representing the viewer who is watching the stream. Use this to look up video views for an individual viewer. If no value is specified, a unique ID will be generated by the SDK. Note: You should not use any value that is personally identifiable on its own (such as email address, username, etc). Instead, you should supply an anonymized viewer ID which you have stored within your own system.
- `player_version` (`string`, optional): As you make changes to your player you can compare how new versions of your player perform. This is not the player software version (e.g. Video.js 5.0.0), which is tracked automatically by the SDK.
- `player_software_name` (`string`, optional): Player Software being used to play the Video (e.g. Video.js, JW Player, etc.). Note this was previously named player_software
- `player_software_version` (`string`, optional): Player Software Version (e.g. 2.45.5).
- `player_mux_plugin_name` (`string`, optional): The name of the plugin being built (some descriptive string).
- `player_mux_plugin_version` (`string`, optional): The version of the plugin being built (a version string).

## clpp.MuxOverride (typedef)

The `muxOptionsOverride` (`clpp.MuxDataConfiguration#muxOptionsOverride`) subsection of MUX Data configuration.

Overriding options to pass to the MUX Data SDK.

Properties:

- `data` (`clpp.MuxOptionsData`, optional): Data about the viewer, video and the integration.
- `debug` (`boolean`, optional): Controls whether debug log statements are logged to the console.

## clpp.NpawConfiguration (typedef)

The `npaw` (`clpp.BasePlayerConfiguration#npaw`) subsection of player configuration.

Configuration of NPAW analytics plugin.

In addition to the options listed here, you can also pass in any NPAW `AnalyticsOptions` which will be passed the the NPAW SDK NpawPlugin. (Options that get passed into `npawPlugin.setAnalyticsOptions()` such as 'content.isLive', 'content.title', etc.).

For more information please visit the [NPAW Developer Site](https://documentation.npaw.com/integration-docs/docs/setting-options-and-metadata) (behind login).

Properties:

- `accountCode` (`string`): Account code for NPAW analytics.
- `errorFilter` (`clpp.NpawErrorFilter`, optional): A custom function to convert `clpp.Error` to a payload for NPAW before sending it to NPAW analytics. Return `null` to prevent a specific error from being sent.
- `disabledSubtitlesLabel` (`string`, optional), default `"off"`: A label used to identify disabled subtitles.

Example: Pass NpawPlugin options along with the account code.

```js
import '@castlabs/prestoplay/cl.youbora';

const player = new clpp.Player('video', {
  npaw: {
    accountCode: 'account_code',
    'content.title': 'My Movie',
    'content.customDimension.1': 'premium',
    'user.name': 'user_123',
  },
});

player.open('https://example.com/manifest.mpd');
```

## clpp.NpawErrorFilter (callback)

```ts
function(error: clpp.Error): clpp.NpawErrorPayload | null
```

A function that converts a `clpp.Error` to a `clpp.NpawErrorPayload` for NPAW analytics. If it returns `null`, the error will not be sent.

Parameters:

- `error` (`clpp.Error`): The error that occurred during playback.

Returns: `clpp.NpawErrorPayload | null` - The payload to send to NPAW, or `null` to not report the error.

Example: Custom NPAW error filter

```js
function (error) {
   if (error.code === 1) return null;

   return {
     code: `${error.code}`,
     message: error.message,
     severity: error.severity,
     metadata: { ... },
   };
 };
```

## clpp.NpawErrorPayload (typedef)

A payload sent to NPAW analytics to report an error that occurred during playback.

Properties:

- `code` (`string`, optional): The error code as string.
- `message` (`string`, optional): The error message.
- `severity` (`clpp.Error.Severity`, optional): The error severity.
- `metadata` (`Record<string, any>`, optional): Additional metadata further describing the error.

## clpp.OnboardConfiguration (typedef)

The DRMtoday Onboard configuration.

Properties:

- `baseUrl` (`string`): The base URL of the DRMtoday Onboard host.
- `widevineUrl` (`string`): The Widevine path. Default is 'widevine'.
- `serverCertificate` (`string | Uint8Array | null`, optional): Widevine server certificate.
- `playreadyUrl` (`string`): The Playready path. Default is 'playready'.
- `fairplayUrl` (`string`): The Fairplay path. Default is 'fairplay'.

## clpp.ParsedMp4Box (typedef)

Parsed MP4 box.

Properties:

- `parser` (`clpp.utils.Mp4Parser`): The parser that parsed this box. The parser can be used to parse child boxes where the configuration of the current parser is needed to parsed other boxes.
- `partialOkay` (`boolean`): If true, allows reading partial payloads from some boxes. If the goal is a child box, we can sometimes find it without enough data to find all child boxes. This property allows the partialOkay flag from parse() to be propagated through methods like children().
- `start` (`number`): The start of this box (before the header) in the original buffer. This start position is the absolute position.
- `size` (`number`): The size of this box (including the header).
- `headerSize` (`number`): The size of this box header.
- `version` (`number`, optional): The version for a full box, null for basic boxes.
- `flags` (`number`, optional): The flags for a full box, null for basic boxes.
- `reader` (`clpp.utils.dataview.DataViewReader`): The reader for this box is only for this box. Reading or not reading to the end will have no affect on the parser reading other sibling boxes.
- `has64BitSize` (`boolean`): If true, the box header had a 64-bit size field.  This affects the offsets of other fields.

## clpp.PlatformInfo (typedef)

Platform information.

Properties:

- `os` (`string`): The operating system name.
- `osVersion` (`clpp.PlatformVersion`): The operating system version.
- `browser` (`string`): The current browser.
- `browserVersion` (`clpp.PlatformVersion`): The browser version.

## clpp.PlatformVersion (typedef)

A version with a human readable name and major, minor, patch, and build properties.

Properties:

- `major` (`number`): The major version number.
- `name` (`string`): The human readable name.
- `minor` (`number`, optional): The minor version number.
- `patch` (`number`, optional): The patch version number.
- `build` (`number`, optional): The build version number.

## clpp.Player.State (enum)

Enum for player states.

Values:

- `IDLE` = `0`: When player has been created or released.
- `PREPARING` = `1`: When player receives the api command to load the movie until it starts requesting the first fragment.
- `BUFFERING` = `2`: When player doesn't have enough data to play the content for any reasons.
- `PLAYING` = `3`: When player starts playing content.
- `PAUSED` = `4`: When player is stopped.
- `ENDED` = `5`: When video is ended.
- `ERROR` = `6`: When player encounters an error.
- `UNSET` = `7`: This state is deprecated, the player will never get to this state.

## clpp.PlayerFleet (class)

Constructor:

```ts
new clpp.PlayerFleet()
```

**Experimental:** may change without a major release.

Player Fleet manages multiple player instances playing in parallel and keeps them in sync.

We sync playhead, pause and unpause.

There is one main player and all the other (secondary) players mirror it.

### Methods

#### clpp.PlayerFleet#load

```ts
load(config: clpp.PlayerConfiguration): Promise<void>
```

Load a config by all players in the fleet.

Parameters:

- `config` (`clpp.PlayerConfiguration`): The player configuration opened by every player.

Returns: `Promise<void>` - A promise that resolves when all players have opened the content.

#### clpp.PlayerFleet#setLoop

```ts
setLoop(loop: boolean)
```

Set looping behavior.

Parameters:

- `loop` (`boolean`): if true the video will play in a loop

#### clpp.PlayerFleet#addSecondaryPlayer

```ts
addSecondaryPlayer(player: clpp.Player)
```

Add a secondary player to the fleet.

Parameters:

- `player` (`clpp.Player`): The player that mirrors the main player.

#### clpp.PlayerFleet#addMainPlayer

```ts
addMainPlayer(player: clpp.Player)
```

Add a main player to the fleet.

Parameters:

- `player` (`clpp.Player`): The player that the secondary players follow. Ignored if a main player is already set.

#### clpp.PlayerFleet#clear

```ts
clear()
```

Release all players and remove all listeners.

## clpp.PlayerPlugin (interface)

An interface for player plugins which can hook into player lifecycle. Each player instance has its own instances of plugins.

### Methods

#### clpp.PlayerPlugin#onPlayerCreated

```ts
onPlayerCreated(player: clpp.Player)
```

Callback that is triggered when the player is created, i.e. when an instance of `clpp.Player` is created.

Parameters:

- `player` (`clpp.Player`): The player

#### clpp.PlayerPlugin#onPlayerWillDestroy

```ts
onPlayerWillDestroy(player: clpp.Player)
```

Callback that is triggered when the player is destroyed.

Parameters:

- `player` (`clpp.Player`): The player

#### clpp.PlayerPlugin#onPlayerWillRelease

```ts
onPlayerWillRelease(player: clpp.Player)
```

Callback that is triggered when the player is released.

Parameters:

- `player` (`clpp.Player`): The player

#### clpp.PlayerPlugin#onContentWillLoad

```ts
onContentWillLoad(player: clpp.Player, source: clpp.Source): void | string | Promise<void> | Promise<string>
```

Callback that is triggered before content is loaded.

A plugin may replace the stream URL by returning a new URL, or a promise which resolves with it.

Parameters:

- `player` (`clpp.Player`): The player
- `source` (`clpp.Source`): The chosen source

Returns: `void | string | Promise<void> | Promise<string>` - If a promise is returned content will start loading after it is resolved. Avoid returning a promise if possible in order to keep load times short. Return a string, or resolve with one, to replace the URL the stream is loaded from.

#### clpp.PlayerPlugin#onContentLoaded

```ts
onContentLoaded(player: clpp.Player): void | Promise<unknown>
```

Callback that is triggered after content is loaded.

Parameters:

- `player` (`clpp.Player`): The player

Returns: `void | Promise<unknown>` - If a promise is returned, the player's `open()` call resolves only after it is resolved.

#### clpp.PlayerPlugin#id

```ts
id(): string
```

Returns a plugin ID. If a plugin ID is exposed, the plugin instance will be registered as a player component.

Returns: `string` - The plugin ID.

## clpp.PlayerPluginFactory (interface)

An interface for a factory which creates a player plugin based on player configuration.

### Methods

#### clpp.PlayerPluginFactory#create

```ts
create(config: clpp.PlayerConfiguration): clpp.PlayerPlugin | null
```

Create a new player plugin or return null.

Parameters:

- `config` (`clpp.PlayerConfiguration`): The player configuration

Returns: `clpp.PlayerPlugin | null` - The new player plugin instance or null

## clpp.PlayerState (enum)

Enum with all possible player states. This enum conforms to Castlabs common spec.

Warning: This enum corresponds to the common API player state model, but it is not yet fully functional across all PRESTOplay SDK components. Use `clpp.Player.State` instead.

Values:

- `IDLE` = `0`: The player is in Idle state when no content is loaded or being loaded and no additional resources are open. No data is loaded in buffers and no decoder instances are open.

  This is the initial state of the Player.
- `STOPPING` = `1`: The player is in the process of unloading content and releasing resources. as requested by stop() or release().
- `OPENING` = `2`: The player is in Opening state when it started to open content. It will stay in this state until it has enough meta-data loaded to build up a track model and transition to Ready.
- `ERROR` = `3`: The player ends up in the Error state after a fatal error occurred.
- `READY` = `4`: The player reached the Ready state when enough data was loaded to build a track model. At this point how the player proceeds depends on the configuration. The player will in the Ready state until it is transitioned out of the state and loading of data is triggered. This transition can happen automatically or manually depending on the configuration.
- `SEEKING` = `5`: A position change was requested. The player can either reach the new position in its buffer and will transition back to PLAY or PAUSING depending on where it came from or it will first transition into BUFFERING if the requested position is not found in the current buffer.
- `BUFFERING` = `6`: The player does not have enough data to keep in playing and need to fill its buffers further before playback can continue.
- `PLAY` = `7`: The player tries to start playback. This operation might fail, for instance because if auto-play not being permitted, in which case the player transitions to PAUSING. Usually the player transitions out to PLAYING and playback starts.
- `PLAYING` = `8`: The playhead is moving forward and the content is playing.
- `PAUSING` = `9`: The player is trying to stop playback.
- `PAUSED` = `10`: Playback is possible but paused.
- `ENDED` = `11`: The final state of the player is reached when the playhead moves to the end of the available content either by normal playback or via a seek operation that seeks at or beyond the end of the content.

## clpp.PlayerSurfaceConfiguration (typedef)

The player surface configuration.

Properties:

- `disableContainer` (`boolean`, optional), default `false`: If true, no container will be generated.
- `webOSStartupPatch` (`boolean`, optional), default `false`: If true, a performance patch will be applied on webOS 4,5,6 devices in order to reduce startup time by setting the 'controls' attribute on the video element.
- `crossorigin` (`string`, optional), default `'anonymous'`: The default crossorigin configuration that will be applied to any media tag if its not specified in the tag.
- `containerEl` (`Element | null`, optional), default `null`: The container element.

## clpp.Playlist (class)

Extends: `clpp.EventTarget`. Inherited members are documented there.

Constructor:

```ts
new clpp.Playlist(player: clpp.Player, onItemWillChange?: function)
```

Playlist enables sequential playback of multiple media items.

Transition between items in a playlist is automatic. There’s no requirement that they’re of the same format (e.g., it’s fine for a playlist to contain both HLS and DASH videos).

Parameters:

- `player` (`clpp.Player`): The player instance.
- `onItemWillChange` (`function`, optional): The callback triggered right before changing a playlist item. Adjust the playlist item if needed. For example update the auth token.

### Methods

#### clpp.Playlist#addEventListener

```ts
addEventListener(type: string, listener: clpp.EventCallback)
```

Adds an event listener for the given event.

Parameters:

- `type` (`string`): The event name
- `listener` (`clpp.EventCallback`): The callback function

Example: Add an event listener.

```js
const callback = () => {};
  playlist.addEventListener('event', callback);
```

#### clpp.Playlist#on

```ts
on(name: string, callback: clpp.EventCallback, opt_callbackScope?: object): clpp.EventCallback
```

Adds an event listener for the given event. Optionally, scope can be passed in, in which case the callback function will be bound/executed in the given scope.

This method returns a reference to the callback for convenient removal of the listener via `playlist.off()` (`clpp.Playlist#off`).

Parameters:

- `name` (`string`): The event name
- `callback` (`clpp.EventCallback`): The callback function
- `opt_callbackScope` (`object`, optional): The callback scope

Returns: `clpp.EventCallback` - The callback function

Example: Listen to modification of playlist.

```js
const listener = playlist.on(clpp.events.PLAYLIST_MODIFIED, () => {
    // ...
  });
  playlist.off(clpp.events.PLAYLIST_MODIFIED, listener);
```

Example: Listen to playlist item change.

```js
const listener = playlist.on(clpp.events.PLAYLIST_ITEM_CHANGED,
    event => {
    // ...
  });
  playlist.off(clpp.events.PLAYLIST_ITEM_CHANGED, listener);
```

#### clpp.Playlist#one

```ts
one(name: string, callback: clpp.EventCallback, opt_callbackScope?: object): clpp.EventCallback
```

Adds a one time event listener for the given event. The listener will be removed once the event was triggered. Otherwise it works the same as `playlist.on()` (`clpp.Playlist#on`).

Parameters:

- `name` (`string`): The event name
- `callback` (`clpp.EventCallback`): The callback function
- `opt_callbackScope` (`object`, optional): The callback scope

Returns: `clpp.EventCallback` - The callback function

Example: Listen to fist modification of playlist.

```js
const listener = player.one(clpp.events.PLAYLIST_MODIFIED, () => {
     // first playlist modification
  });
```

#### clpp.Playlist#off

```ts
off(name: string, callback: clpp.EventCallback): boolean
```

Remove an event listener.

Parameters:

- `name` (`string`): The event name
- `callback` (`clpp.EventCallback`): The callback function

Returns: `boolean` - True if the listener was removed

Example: Remove a listener.

```js
const listener = playlist.on(clpp.events.PLAYLIST_MODIFIED, () => {});
  ...
  playlist.off(clpp.events.PLAYLIST_MODIFIED, listener);
```

#### clpp.Playlist#removeEventListener

```ts
removeEventListener(type: string, listener: clpp.EventCallback)
```

Remove an event listener.

Parameters:

- `type` (`string`): The event name
- `listener` (`clpp.EventCallback`): The callback function

Example: Remove a listener.

```js
const callback = () => {};
  playlist.removeEventListener('event', callback);
```

#### clpp.Playlist#getPosition

```ts
getPosition(): number
```

Return the position of the current playlist item.

Returns: `number` - The position of the current playlist item.

#### clpp.Playlist#getQueue

```ts
getQueue(): Array<clpp.PlaylistItem>
```

Return the internal list of playlist items.

Returns: `Array<clpp.PlaylistItem>` - The list of playlist items.

#### clpp.Playlist#getCurrent

```ts
getCurrent(): clpp.PlaylistItem | null
```

Get the current item, advancing if it's time to.

Returns: `clpp.PlaylistItem | null` - The current playlist item. Null if the playlist is empty.

#### clpp.Playlist#getUpcoming

```ts
getUpcoming(): clpp.PlaylistItem | null
```

Get the upcoming item.

Returns: `clpp.PlaylistItem | null` - The upcoming playlist item. Null if the end of the playlist.

#### clpp.Playlist#isStarted

```ts
isStarted(): boolean
```

Checks if playing through the playlist.

Returns: `boolean` - True if running. False otherwise.

#### clpp.Playlist#start

```ts
start()
```

Play through the playlist.

#### clpp.Playlist#stop

```ts
stop()
```

Stop iterating the playlist. Does not stop the playback.

#### clpp.Playlist#onEnded

```ts
onEnded()
```

Override if different behavior needed.

Default behavior is go to immediately the next playlist item on playback end.

#### clpp.Playlist#next

```ts
next(): Promise<void>
```

Go to the next playlist item.

Returns: `Promise<void>`

#### clpp.Playlist#previous

```ts
previous(): Promise<void>
```

Go to the previous playlist item.

Returns: `Promise<void>`

#### clpp.Playlist#goTo

```ts
goTo(position: number, reload?: boolean): Promise<void>
```

Go to a specific playlist item.

Parameters:

- `position` (`number`): The index of the playlist item
- `reload` (`boolean`, optional), default `false`: True if force reload. False otherwise. Default is false.

Returns: `Promise<void>`

#### clpp.Playlist#append

```ts
append(item: clpp.PlaylistItem)
```

Add an item at the end of the playlist.

Parameters:

- `item` (`clpp.PlaylistItem`): The new playlist item

#### clpp.Playlist#insert

```ts
insert(item: clpp.PlaylistItem, index: number)
```

Add an item at the current position in the playlist.

Parameters:

- `item` (`clpp.PlaylistItem`): The new playlist item
- `index` (`number`): The index where the playlist item needs to be inserted

#### clpp.Playlist#remove

```ts
remove(index: number)
```

Remove an item from the playlist. An error is thrown when removing the current item.

Parameters:

- `index` (`number`): The index of the playlist item

Throws:

- `clpp.Error` when removing the current item

#### clpp.Playlist#clear

```ts
clear()
```

Remove all playlist items.

## clpp.PlaylistConfiguration (typedef)

The `playlist` (`clpp.BasePlayerConfiguration#playlist`) subsection of player configuration.

Options of a `clpp.playlist.ScPlaylist`. Pass this configuration to the first item of `clpp.playlist.ScPlaylist`.

Properties:

- `startTime` (`number`, optional): Where playback starts, in seconds from the start of the first item.
- `endTime` (`number`, optional): Where playback stops, in seconds from the start of the first item. It may lie in a later item.

  Required if `content` (`clpp.PlaylistConfiguration#content`) is `"DVR"`.
- `timeline` (`'basic' | 'flat'`, optional), default `"basic"`: How the items are shown on the timeline:

  - `"basic"`: each item has its own timeline.
  - `"flat"`: all items are joined into one timeline.
- `content` (`'VOD' | 'DVR'`, optional), default `"VOD"`: What kind of items the playlist may contain:

  - `"VOD"`: VOD items only.
  - `"DVR"`: VOD items followed by one DVR item at the end.
- `cropTimeline` (`boolean`, optional), default `false`: Enable to cut the timeline down to the range from `startTime` (`clpp.PlaylistConfiguration#startTime`) to `endTime` (`clpp.PlaylistConfiguration#endTime`) .

## clpp.PlaylistItem (typedef)

Playlist item.

Properties:

- `title` (`string`, optional): The title.
- `description` (`string`, optional): The description.
- `image` (`string`, optional): The URL of the poster.
- `skippable` (`boolean`, optional): If false, the item cannot be skipped via playlist controls. This property is respected only in `clpp.cast.playlist.CastPlaylist`.
- `configuration` (`clpp.PlayerConfiguration`): The player configuration.

## clpp.PlayreadyDrmSystem (typedef)

The main property is the `licenseUrl` to the DRM backend, but you would usually also implement at least some of the network modifier. This can be used for example to add some headers to the license request, or to access and even modify the responses.

Properties:

- `licenseUrl` (`string`, optional): The URL to the license server.
- `videoRobustness` (`undefined | clpp.drm.PlayreadyRobustnessLevel | Array<(undefined|clpp.drm.PlayreadyRobustnessLevel)>`, optional): The EME video robustness level.
- `audioRobustness` (`undefined | clpp.drm.PlayreadyRobustnessLevel | Array<(undefined|clpp.drm.PlayreadyRobustnessLevel)>`, optional): The EME audio robustness level.
- `individualizationServer` (`string`, optional): The server that handles an 'individualization-request'. If the server isn't given, it will default to the license server.
- `useLegacySystem` (`boolean`, optional): Use only the legacy `com.microsoft.playready` key system, also on platforms that support the `.recommendation` key systems. Set it to `true` if your DRM provider supports only the legacy key system.
- `modifiers` (`clpp.drm.LicenseModifiers`, optional): A set of callbacks to perform modifications on license requests and/or responses.

## clpp.PreloadConfiguration (typedef)

Configuration for preloading thumbnails.

Properties:

- `preloadWhileBuffering` (`boolean`, optional), default `false`: By default loading of thumbnails is put on hold when video is buffering to free up more bandwidth in order to load the video faster.

  Enable this to allow thumbnails to be downloaded even during video buffering which makes thumbnails display faster at the price of potentially longer buffering of video.
- `step` (`number`, optional): Value indicating index of images downloaded in current wave (i.e. 5 means in current wave we will preload images for indices 5, 10, 15 and so on).

## clpp.ReceiverConfiguration (typedef)

Cast receiver configuration.

Properties:

- `useShakaForHls` (`boolean`, optional): If true, Shaka player is used for HLS. If false, MPL player is used for HLS. If undefined the default is selected by Chromecast Receiver SDK, for more information see [cast.framework.CastReceiverOptions#useShakaForHls](https://developers.google.com/cast/docs/reference/web_receiver/cast.framework.CastReceiverOptions#useShakaForHls).

## clpp.RemoteTextTrack (typedef)

Text track that can be side-loaded.

Properties:

- `url` (`string`): URL of the subtitle track.
- `language` (`string`): Subtitle language code.
- `mimeType` (`string`): Subtitle MIME type.
- `kind` (`string`): Kind of subtitles.
- `codec` (`string`, optional): Subtitle codec.
- `label` (`string`, optional): Optional track label.

## clpp.Rendition (class)

Constructor:

```ts
new clpp.Rendition(id: string, track: clpp.Track)
```

A single quality level (encoding) of a `clpp.Track`, e.g. one resolution and bitrate of a video track.

Parameters:

- `id` (`string`): id
- `track` (`clpp.Track`): track

### Properties

#### clpp.Rendition#track

Type: `clpp.Track`

Back reference to a track.

#### clpp.Rendition#id

Type: `string`

Identifier of this rendition assigned by the player. See `originalId` for the id used in the manifest.

#### clpp.Rendition#width

Type: `number | null`

The width in pixel of this track if this is a video track and information about the size is available

#### clpp.Rendition#height

Type: `number | null`

The height in pixel of this track if this is a video track and information about the size is available

#### clpp.Rendition#bandwidth

Type: `number | null`

The bitrate of this track in bits per second (bps).

#### clpp.Rendition#codec

Type: `string | null`

The codec string of this rendition (e.g. `avc1.4d401f`), or `null` if not known.

#### clpp.Rendition#originalId

Type: `string | null`

Rendition id that appeared in original manifest.

## clpp.RenditionChoice (typedef)

A record of track rendition choice.

Properties:

- `timestamp` (`number`): The timestamp the choice was made, in seconds since 1970 (i.e. Date.now() / 1000).
- `id` (`string`): The id of the rendition that was chosen.
- `trackId` (`string`): The associated track id.
- `type` (`string`): The type of rendition chosen ('video', 'audio, or 'text').
- `fromAdaptation` (`boolean`): True if the choice was made by AbrManager for adaptation; false if it was made by the application through selectTrack.
- `width` (`number`, optional): The width of the chosen rendition (null for audio and text).
- `height` (`number`, optional): The bandwidth of the chosen rendition (null for audio and text).
- `bandwidth` (`number`, optional): The bandwidth of the chosen rendition (null for text).

## clpp.RestrictionInfo (typedef)

Information about why a stream could not be played.

Properties:

- `hasAppRestrictions` (`boolean`): Whether there are streams that are restricted due to app-provided restrictions.
- `missingKeys` (`Array<string>`): The key IDs that were missing.
- `restrictedKeyStatuses` (`Array<string>`): The restricted EME key statuses that the streams had. For example, 'output-restricted' would mean streams couldn't play due to restrictions on the output device (e.g. HDCP).

## clpp.Restrictions (typedef)

Track restrictions. This is mostly geared towards video tracks but bandwidth restrictions apply also to audio.

Properties:

- `minWidth` (`number`, optional): The minimum width of a video track, in pixels.
- `maxWidth` (`number`, optional): The maximum width of a video track, in pixels.
- `minHeight` (`number`, optional): The minimum height of a video track, in pixels.
- `maxHeight` (`number`, optional): The maximum height of a video track, in pixels.
- `minPixels` (`number`, optional): The minimum number of total pixels in a video track (i.e. width * height).
- `maxPixels` (`number`, optional): The maximum number of total pixels in a video track (i.e. width * height).
- `minBandwidth` (`number`, optional): The minimum bandwidth of a track in bit/sec.
- `maxBandwidth` (`number`, optional): The maximum bandwidth of a track in bit/sec.

Example: Restrict video width for one source

```js
const player = new clpp.Player(...);

player.open({
  source: '...',
  ...
  restrictions: {
    maxWidth: 1080
  },
  ...
});
```

Example: Restrict video width

```js
const player = new clpp.Player('video', {
  ...
  restrictions: {
    maxWidth: 1080
  },
  ...
});

// The restrictions apply to all subsequent calls to open().

player.open('...');
```

## clpp.SafariConfiguration (typedef)

Configuration of Safari-based playback for HLS.

By default the player uses Safari-based playback for HLS on Safari. This can be changed to MSE-based playback `preferNativeHlsOnSafari` (`clpp.StreamingConfiguration#preferNativeHlsOnSafari`).

Properties:

- `enableHlsVideoTrackInfo` (`boolean`, optional), default `false`: By default Safari-based playback does not provide metadata about video tracks.

  Enable this to side-load the manifest and parse out metadata about video tracks with a performance tradeoff of potentially making additional network requests if client-side caching is disabled.

  This flag is experimental and may not work for some special cases, such as playlists containing multiple video renditions for one resolution.
- `enableMetadata` (`boolean`, optional), default `false`: By default Safari-based playback does not provide track metadata attributes such as accessibility labels.

  Enable this to side-load the manifest and parse out track metadata with a performance tradeoff of potentially making additional network requests if client-side caching is disabled.

  Note that in order for this feature to work, `NAME` attributes of `#EXT-X-MEDIA` tags must be unique per type (i.e. no two audio tracks share the same name, no two text tracks share the same name).

## clpp.SdkConfiguration (typedef)

Contains global SDK configuration.

Properties:

- `companionSdk` (`clpp.CompanionSdk`, optional): Companion SDK information.

## clpp.SeekRange (typedef)

The seek range.

Properties:

- `start` (`number`): Start of seek range in seconds.
- `end` (`number`): End of seek range in seconds.

## clpp.SessionContext (typedef)

Session context is used for passing additional data between license requests and responses in scope of media session. User can store tokens or other necessary data in `customData` field or setup delay in `ldlDelay` field.

Properties:

- `ldlDelay` (`number`, optional): Delay for manual Limited Duration Licenses (in seconds). Setting this to >0 value will schedule internal LDL timer. This should be used primarily when PlayReady is in use, as associated CDM does not trigger `license-renewal` event automatically.
- `customData` (`Record<string, any>`, optional): Custom data. It is permitted to pass some DRM related data by users there.

## clpp.SimidConfiguration (typedef)

The `simid` (`clpp.BasePlayerConfiguration#simid`) subsection of player configuration.

Configuration of SIMID ads.

Properties:

- `creatives` (`Array<clpp.SimidCreative>`): List of pre-configured SIMID creatives. Note that this is exposing a low level configuration and it is an experimental feature.
- `style` (`clpp.SimidStyle`, optional): Style configuration for SIMID frame.

## clpp.SimidCreative (typedef)

Describes a basic SIMID creative without additional meta-data other than the creative, the start time in seconds relative to the main contents timeline, and the duration.

Properties:

- `url` (`string`): The URL to the SIMID creative.
- `preload` (`number`, optional), default `5`: The offset in seconds before the startTime at which to preload the creative.
- `startTime` (`number`): The start time in seconds relative to the main content timeline.
- `duration` (`number`): The duration of the SIMID creative in seconds.
- `adParameters` (`string`, optional): Ad parameters passed to the creative when it is initialized.

## clpp.SimidStyle (typedef)

Style configuration for SIMID frame.

Properties:

- `className` (`string`, optional): Custom CSS class name that overwrites the default style for the SIMID frame.

## clpp.SpeedUpMode (enum)

Speed-up mode to use during trick play.

Values:

- `DECODER` = `decoder`: Decoder mode play the content at the indicated speed, using native play rate.
- `SEEK` = `seek`: Seek mode will internally pause the playback and continuously perform seek operations.

## clpp.StateChange (typedef)

A record representing a state change.

Properties:

- `timestamp` (`number`): The timestamp the state was entered, in seconds since 1970 (i.e. Date.now() / 1000).
- `state` (`clpp.Player.State`): The state the player entered. This could be 'buffering', 'playing', 'paused', or 'ended'.
- `duration` (`number`): The number of seconds the player was in this state. If this is the last entry in the list, the player is still in this state, so the duration will continue to increase.

## clpp.Stats (typedef)

Contains statistics and information about the current state of the player. This is meant for applications that want to log quality-of-experience (QoE) or other stats. These values will reset when open() is called again.

Properties:

- `width` (`number`): The width of the current video track.
- `height` (`number`): The height of the current video track.
- `streamBandwidth` (`number`): The bandwidth required for the current streams (total, in bit/sec).
- `decodedFrames` (`number`): The total number of frames decoded by the Player. This may be NaN if this is not supported by the browser.
- `droppedFrames` (`number`): The total number of frames dropped by the Player. This may be NaN if this is not supported by the browser.
- `corruptedFrames` (`number`): The total number of corrupted frames dropped by the browser. This may be NaN if this is not supported by the browser.
- `estimatedBandwidth` (`number`): The current estimated network bandwidth (in bit/sec).
- `loadLatency` (`number`): This is the number of seconds it took for the video element to have enough data to begin playback. This is measured from the time open() is called to the time the 'loadeddata' event is fired by the media element.
- `playTime` (`number`): The total time spent in a playing state in seconds.
- `pauseTime` (`number`): The total time spent in a paused state in seconds.
- `bufferingTime` (`number`): The total time spent in a buffering state in seconds.
- `switchHistory` (`Array<clpp.RenditionChoice>`): A history of the rendition changes.
- `stateHistory` (`Array<clpp.StateChange>`): A history of the state changes.

## clpp.StreamingConfiguration (typedef)

The `streaming` (`clpp.BasePlayerConfiguration#streaming`) subsection of player configuration.

Configuration of streaming.

Properties:

- `attemptParameters` (`clpp.net.AttemptParameters`, optional): Recovery behavior in case when media requests fail and need to be retried.

  By default 3 attempts are made to load each request with delay of 1s and `backoffFactor` of 2.
- `bufferingGoal` (`number`, optional), default `10`: The number of seconds of content that the player will attempt to buffer ahead of the playhead.

  This value must be greater than or equal to `rebufferingGoal` (`clpp.StreamingConfiguration#rebufferingGoal`).
- `rebufferingGoal` (`number`, optional), default `2`: The minimum number of seconds of content that the player must buffer ahead of the playhead before it can begin playback or before it can continue playback after it has entered a buffering state (i.e. after it has depleted the buffered data).

  This value must be less than or equal to `bufferingGoal` (`clpp.StreamingConfiguration#bufferingGoal`).
- `bufferBehind` (`number`, optional), default `30`: The maximum number of seconds of content that the player will keep in buffer behind the playhead during playback.

  Some amount of back buffer is useful for quick seek backward.
- `loopBackBufferFlush` (`boolean`, optional), default `true`: Applies only with `loop` (`clpp.BasePlayerConfiguration#loop`) enabled. Once a higher quality starts playing, the player flushes the lower quality video buffered behind it, so the next loop downloads the start of the video again at the current quality.
- `ignoreTextStreamFailures` (`boolean`, optional), default `false`: Enable to ignore failures of text streams. By default a text stream failure will result in an error.

  If subtitles are not a vital part of the application and may fail it may make sense to ignore text failures.
- `alwaysStreamText` (`boolean`, optional), default `false`: Enable to download the selected text track even while subtitles are hidden.

  By default, during MSE playback text segments are only loaded while subtitles are shown via the player API. If subtitles are rendered natively (on iOS, or when `enableHtmlCue` (`clpp.BasePlayerConfiguration#enableHtmlCue`) is `false` or `cl.htmlcue.js` is not loaded), viewers can also turn them on with the browser's own controls, e.g. in the iOS fullscreen player, which the player is not notified about. Enable this so that subtitles appear in that case.

  This is not needed on Safari (iOS) with default settings, it is only needed when `preferNativeHlsOnSafari` (`clpp.StreamingConfiguration#preferNativeHlsOnSafari`) is false.

  Costs additional bandwidth for the text segments.
- `relativeTextTimestamp` (`boolean`, optional), default `false`: Workaround for non-standard segmented WebVTT subtitles whose cue use relative timestamps so their times restart at zero in every segment.

  Enable this to turn these timestamps to absolute by offsetting them by segment start time.

  Standard-compliant content uses presentation timeline timestamps and does not need this. Ignored for segments with an HLS `X-TIMESTAMP-MAP` header.
- `disableAudioTracks` (`boolean`, optional), default `false`: **Applies to:** mse If true, audio tracks will be disabled.

  Disabling audio tracks means they are discarded as if the source had no audio. The audio tracks are not loaded and won't show up in `clpp.TrackManager`.
- `disableVideoTracks` (`boolean`, optional), default `false`: **Applies to:** mse If true, video tracks will be disabled, only audio will remain.

  Disabling video tracks means they are discarded as if the source had no video. The video tracks are not loaded and won't show up in `clpp.TrackManager`.
- `startAtSegmentBoundary` (`boolean`, optional), default `false`: Enable this to optimize load time of live streams by adjusting the start time backwards so it lands at a segment boundary thus decreasing the amount of segments needed to fetch to fill the buffer and start playback.

  This comes at the cost of slight change in playhead position which may land further from the live edge. The effect depends on segment size.

  You may use `enableLiveEdgeChasing` (`clpp.StreamingConfiguration#enableLiveEdgeChasing`) to make up for the shift in playhead position and progressively bring the playhead back up to the live edge.
- `gapDetectionThreshold` (`number`, optional), default `0.1`: **Applies to:** #gap Content is sometimes not fully valid and has gaps, i.e. time ranges without media, e.g. when segments do not line up exactly, at period boundaries in multi-period (SSAI) streams, or when a segment is missing. The browser stops playback at such a gap, so the player automatically recovers by jumping over it.

  This value is how close, in seconds, the playhead must get to a gap before the player jumps.

  Some platforms stop playback a little before the gap is reached, and the jump then never happens if this value is too small. The default is therefore 0.5 on Edge and Tizen, and 0.8 on webOS.
- `smallGapLimit` (`number`, optional), default `0.5`: **Applies to:** #gap Gaps of size up to this many seconds are considered small, larger gaps are considered large. See `gapDetectionThreshold` (`clpp.StreamingConfiguration#gapDetectionThreshold`) for what gaps are and how the player jumps over them.

  Small gaps are always jumped over silently. Before jumping over a large gap, the player fires a `largegap` event with the current time and the gap size. The app can call `preventDefault()` on the event to stop the jump, see `jumpLargeGaps` (`clpp.StreamingConfiguration#jumpLargeGaps`).
- `jumpLargeGaps` (`boolean`, optional), default `true`: **Deprecated.** **Applies to:** #gap Whether the player jumps over large gaps, see `smallGapLimit` (`clpp.StreamingConfiguration#smallGapLimit`). Small gaps are always jumped over.

  The `largegap` event is fired either way. If true, the player jumps over the gap unless the app calls `preventDefault()` on the event. If false, the player does not jump and playback may get stuck at the gap.

  It is recommended on to disable this feature.
- `gapTolerance` (`number`, optional), default `0.001`: **Applies to:** #gap Tiny gaps in media, e.g. between two segments because of rounding of media timestamps, are normal and browsers handle them gracefully. However it is not clear where the limit is.

  This option defines the limit of what is considered a tiny gap which is expected to be handled gracefully by browsers.

  It is recommended to keep the default value unless tests on device show that it can be safely increased.
- `durationBackoff` (`number`, optional), default `1`: By default the player never seeks exactly to the end of seek range, this is because some platforms do not support this. Therefore a safety margin of 1 second is used.

  It is recommended to keep this at default.
- `maxSegmentToMediaOffset` (`number`, optional), default `1`: Workaround for content whose media timestamps do not match the times in the manifest, e.g. a DASH manifest missing a `presentationTimeOffset`. Such segments are buffered at the wrong position and playback stalls.

  After the first segment is appended, the player compares its start time from the manifest with its actual media start time. If they differ by more than this many seconds, the player auto-corrects the shift.

  Set `Infinity` to disable it.
- `forceNativeTS` (`boolean`, optional), default `false`: By default, MPEG-TS (TS) segments are always converted (transmuxed) to fMP4 before being pushed to buffer, even on platforms that support TS natively. This is a robust approach.

  Enable this to skip the transmuxing step on platforms that support MPEG-TS natively, which may improve performance and reduce memory consumption.

  This flag has no effect on AES-encrypted streams.

  By enabling this you disable support for CEA-708 closed captions.
- `preferNativeHlsOnSafari` (`boolean`, optional), default `true`: For playback of HLS on Safari `clpp.Player` uses native Safari player under the hood by default.

  Configure false in order to switch to MSE-based playback instead, which is the same mode that is used for DASH. One limitation of MSE-based playback is that it does not support encrypted MPEG-TS due to browser limitations.

  Read more in the manual about pros and cons of each playback mode.
- `safeSeekOffset` (`number`, optional), default `5`: Only affects live streams with a DVR window. The start of the window moves forward in real time, so the playhead can fall behind it, e.g. after a long pause. The player then corrects by moving the playhead forward into the playable window.

  This value is the number of seconds the player adds as a safety margin instead of repositioning to the exact start of seek range.

  It is recommended to keep this at default value.
- `stallThreshold` (`number`, optional), default `1`: The player detects unexpected stall situations and attempts to automatically recover and continue playback.

  This value is the number of seconds the playhead must stay frozen before the situation is treated as a stall. Too low a value can mistake slow platform reactions for stalls; too high a value leaves a frozen picture longer before recovery.

  The default is 3 on webOS, where the hardware pipeline is slow to react.
- `bufferLimitUpdateInterval` (`number`, optional), default `0.5`: How often, in seconds, the player checks again whether it can download the next segment while it is waiting, e.g. because the buffering goal is reached or because the next live segment is not available yet.

  Lower values let the player react faster, which matters for low latency live streams, at the cost of more CPU work. Must be greater than 0.
- `overridePasp` (`boolean`, optional), default `false`: **Deprecated.** Video can use non-square pixels, signaled by the pixel aspect ratio (`pasp` box) in the init segment. For example, 1440x1080 video with a pixel aspect ratio of 4:3 should be displayed at 16:9. Not all browsers apply the pixel aspect ratio, so the same video can be displayed with different aspect ratios in different browsers.

  If true, the player rewrites the pixel aspect ratio to 1:1 (square pixels), so all browsers display the video at its stored resolution. This gives consistent behavior, but non-square pixel content is then displayed distorted in every browser.

  Only applies to encrypted video.
- `enableLiveEdgeChasing` (`boolean`, optional), default `false`: **Applies to:** #catchup Keeps live playback close to the live edge to show the latest live content. When playback falls behind, e.g. after rebuffering, the player catches up by playing slightly faster, or by seeking to the live edge.

  Enable this to automatically optimize glass-to-glass for the whole duration of playback.

  Seeking backward in the DVR window is not allowed with this option enabled, it goes against the auto-correction mechanism.
- `chasingRate` (`number`, optional), default `1.15`: **Applies to:** #catchup The playback rate used to catch up with the live edge, see `enableLiveEdgeChasing` (`clpp.StreamingConfiguration#enableLiveEdgeChasing`). Higher values catch up faster but the speed-up becomes noticeable, lower values take longer.

  For example, at 1.15 the player catches up 3 seconds in 20 seconds.

  Must be greater than 1.
- `startChasingAt` (`number`, optional), default `5`: **Applies to:** #catchup How many seconds playback may fall behind the live edge before the player starts catching up, see `enableLiveEdgeChasing` (`clpp.StreamingConfiguration#enableLiveEdgeChasing`).

  Must be greater than `stopChasingAt` (`clpp.StreamingConfiguration#stopChasingAt`).
- `stopChasingAt` (`number`, optional), default `2`: **Applies to:** #catchup Once playback is back within this many seconds of the live edge, the player stops catching up and returns to normal speed, see `enableLiveEdgeChasing` (`clpp.StreamingConfiguration#enableLiveEdgeChasing`).

  Must be 0 or greater.
- `chaseJumpDistance` (`number`, optional), default `10`: **Applies to:** #catchup If playback falls this many seconds or more behind the live edge, the player seeks to the live edge instead of just speeding up, see `enableLiveEdgeChasing` (`clpp.StreamingConfiguration#enableLiveEdgeChasing`).

  Must be greater than `startChasingAt` (`clpp.StreamingConfiguration#startChasingAt`).
- `addMissingTimelineCues` (`boolean`, optional), default `false`: **Applies to:** hls, safari Workaround for SCTE-35 ad markers in live HLS played natively on Safari. When playback starts in the middle of an ad break, the playlist may contain only the `SCTE35-IN` tag marking the end of the break, because the `SCTE35-OUT` tag that marked its start has scrolled out of the live window. Safari then reports a cue with wrong times (from the end of the ad break to the end of the playlist).

  Enable this to auto-correct these wrong cues so they span from the start of the stream to the end of the ad break.
- `patchEdgeWhenMixedContent` (`boolean`, optional), default `false`: **Applies to:** edge Workaround for Microsoft Edge, which fails to decrypt encrypted content that follows clear content in the same stream, e.g. DRM-protected content after a clear pre-roll ad. Edge sets up its DRM playback pipeline only if the first content it plays is encrypted.

  If true, the player makes every init segment look encrypted to Edge before appending it, so the DRM pipeline is set up from the start.

  Enable this only for streams that switch from clear to encrypted content. It applies to all streams on Edge and adds an extra append for every init segment. It has no effect on other browsers.
- `ignoreDrift` (`boolean`, optional), default `false`: By default the streaming engine tries to account for drift between media times exposed by the manifest and the actual segment media times.

  This automatic recovery mechanism comes at the cost of possible making more segment requests.

  Enable this in order to decrease buffering time but do so only when you are sure about the validity of timestamps in the manifest.
- `disableFragmentSupport` (`boolean`, optional), default `false`: By default, fMP4 segments are appended to the buffer while they are still downloading: fMP4 fragments are parsed out on the fly and appended to the buffer. This is what makes low latency streaming with chunked transfer possible, and it can also reduce startup time.

  This feature works on platforms which support Fetch API.

  Set `true` to ignore fragments and make segments always download completely before being pushed to the buffer. It is recommended to keep this `false.
- `disableMergedFragments` (`boolean`, optional), default `false`: Controls how fMP4 segments are appended to the buffer while they are still downloading. A segment can consist of several fMP4 fragments (`moof` + `mdat` pairs), and a single piece of data received from the network may contain more than one of them.

  By default, all complete fragments received together are merged and appended to the buffer at once.

  Set `true` to append each fragment to the buffer separately which might reduce time to first frame.
- `ignoreManagedMediaSourceStreamingHints` (`boolean`, optional), default `false`: **Applies to:** ios, mse Only affects browsers using ManagedMediaSource (MMS) API (e.g. Safari on iOS 17.1+).

  There the browser fires `startstreaming` and `endstreaming` events to tell the player when to download media, e.g. to save battery or mobile data. By default the player pauses audio and video downloads between `endstreaming` and `startstreaming`.

  Enable this in order to reduce buffering and improve playback quality by ignoring the MMS events, but at the cost of possible lower battery life and or higher data usage.
- `enableStalledSegmentAbort` (`boolean`, optional), default `true`: By default the player watches the progress of media segment downloads and when it detects a drop in throughput it switches to a lower quality in order to avoid buffering.

  It is possible to disable this feature, but it is recommended to keep it enabled.

## clpp.TextStyleConfiguration (typedef)

The `textStyle` (`clpp.BasePlayerConfiguration#textStyle`) subsection of player configuration.

Configuration for CSS styling of subtitle text.

Properties:

- `backgroundColor` (`string`, optional): The background color as CSS expression.

  Example: `green` or `rgba(0,0,0,.25)`.
- `windowColor` (`string`, optional): **Deprecated.** The window color as CSS expression. For example `green` or `rgba(0,0,0,.25)`.
- `fontFamily` (`string`, optional): The font family as CSS expression.

  Example: `sans` or `Arial, Helvetica, sans-serif`.
- `fontColor` (`string`, optional): The font color as CSS expression.

  Example: `green` or `rgba(0,0,0,.25)`.
- `fontSize` (`string`, optional): The font size as CSS expression.

  Example: `1em`, `100%` or `24px`.

  It takes precedence over `fontSizePercent` (`clpp.TextStyleConfiguration#fontSizePercent`).
- `fontSizePercent` (`number`, optional), default `0.0667`: The font size as percentage of video height. The font size will be adjusted automatically on video size change, for example when entering fullscreen mode.

  Supported in `cl.htmlcue` module.
- `edgeColor` (`string`, optional): The color of the outline or shadow around subtitle text.

  Example: `green` or `rgba(0,0,0,.25)`.
- `edgeType` (`clpp.text.EdgeType`, optional): The type of edge (outline, shadow, etc.) around subtitle text.

## clpp.ThumbnailsConfiguration (typedef)

The `thumbnails` (`clpp.BasePlayerConfiguration#thumbnails`) subsection of player configuration.

Configuration of thumbnails.

Properties:

- `enabled` (`boolean`, optional), default `true`: Enable the thumbnail plugins.
- `mode` (`'SINGLE' | 'GRID' | 'WEBVTT' | 'BIF'`, optional): The type of thumbnails to configure. The options are:

  - 'SINGLE' - single images
  - 'GRID' - grid images
  - 'WEBVTT' - WebVTT file carrying thumbnails
  - 'BIF' - binary BIF file

  If omitted, the player will try to guess the correct mode based on the URL.
- `duration` (`number`, optional): Duration of each thumbnail image in seconds in case of 'SINGLE' and 'GRID' thumbnails.
- `url` (`string`, optional): URL to the thumbnail file. In case of 'SINGLE' and 'GRID' thumbnails the URL is a template. See `templateKey` (`clpp.ThumbnailsConfiguration#templateKey`) about the format of the template variable.

  Example: URL template for 'SINGLE' thumbnails:

  `https://thumb.castlabs.com/.../thumb_$index$.jpg`
- `templateKey` (`string`, optional), default `'$index$'`: The key to be replaced in the URL for each image used for 'SINGLE' and 'GRID' modes.

  Example: templateKey: `'[key]'` and URL `https://thumb.castlabs.com/.../[key].jpg`

  The template key `[key]` gets replaced by a numeric index calculated based on the timeline position of the requested thumbnail, duration and in case of 'GRID' thumbnails the size of the grid in order to load the right images for the timeline position.
- `gridSize` (`string`, optional): In 'GRID' mode specify the grid dimensions as a string 'ROWSxCOLUMNS'.

  Example: '10x10' when every grid image contains 10 rows x 10 columns.
- `preload` (`Array<number> | Array<(clpp.PreloadConfiguration|number)>`, optional): Array of steps. For each step, an independent downloader is triggered. The downloader preloads every n-th thumbnail (i.e. step). The thumbnail set is limited to preloaded entries.

Example: Single thumbnails, each located at a different URL. URLs are generated by replacing numeric index.

```js
import '@castlabs/prestoplay/cl.thumbnails';

player.open({
  source: 'https://example.com/manifest.mpd',
  thumbnails: {
    mode: 'SINGLE',
    // $index$ is replaced by the number of the image: 1, 2, 3, ...
    url: 'https://example.com/thumbs/thumb_$index$.jpg',
    // Each image covers 10 seconds of the video.
    duration: 10,
  },
});
```

Example: Grids of 100 thumbnails in one gird image. URLs to load more grids are generated by replacing numeric index.

```js
import '@castlabs/prestoplay/cl.thumbnails';

player.open({
  source: 'https://example.com/manifest.mpd',
  thumbnails: {
    mode: 'GRID',
    url: 'https://example.com/thumbs/grid_$index$.jpg',
    // Each thumbnail covers 10 seconds of the video.
    duration: 10,
    // Each image holds 10 rows x 10 columns of thumbnails.
    gridSize: '10x10',
  },
});
```

Example: WebVTT thumbnails with preloading.

```js
import '@castlabs/prestoplay/cl.thumbnails';

player.open({
  source: 'https://example.com/manifest.mpd',
  thumbnails: {
    mode: 'WEBVTT',
    url: 'https://example.com/thumbs/thumbnails.vtt',
    // Load every 30th thumbnail first, then every 10th, then all the
    // rest, so a rough set of thumbnails is ready early.
    preload: [30, 10, 1],
  },
});
```

Example: Show the thumbnail at 12 seconds, 180 pixels wide.

```js
player.getPlugin(clpp.thumbnails.ThumbnailsPlugin.Id).get(12)
  .then(thumb => thumb.element(180))
  .then(el => container.appendChild(el));
```

## clpp.TimelineConfiguration (typedef)

The `timeline` (`clpp.ManifestConfiguration#timeline`) subsection of manifest configuration.

Configuration of the timeline.

Properties:

- `type` (`'startover'`, optional): **Applies to:** dash Set this option to 'startover' to enable seeking to the very beginning of seek range in case of live DVR DASH streams (growing window live).

  DASH manifests with SegmentTimeline or SegmentList are supported.

  This option has no effect in HLS, where seeking to the start of a DVR window works by default.

  This is intended to be used in combination with version: 1.
- `version` (`1 | 2`, optional), default `1`: Set timeline version to change the timeline model.

  V1 and v2 have different time models, seek range is computed differently and this is especially significant in case of live and DVR streams.

  Timeline v2 may show better behavior in cases of seeking or setting position to the edges of the seek range and transition from dynamic stream to static (end of live/DVR).

  Timeline v2 is fully supported in HLS. In DASH it is experimental.

## clpp.TimelineCue (typedef)

Contains information about a cue in the timeline that will cause an event to be raised when the playhead enters or exits it. In DASH this is the EventStream element. In HLS this is the EXT-X-DATERANGE tag.

Properties:

- `id` (`string`): Specifies an identifier for this instance of the cue.
- `configurationId` (`string`, optional): ID of the configuration object of the asset to which this cue belongs if it is defined in `clpp.PlayerConfiguration`.
- `customAttributes` (`Record<string, any>`, optional): A map containing custom attributes of the EXT-X-DATERANGE HLS tag (aka client-defined attributes) in case this cue comes from HLS.
- `alternativeMpdEvent` (`Record<string, any>`, optional): The parsed MPEG-DASH Alternative MPD event. Only defined for cues of type `DASH_ALTERNATIVE_MPD`.
- `startTime` (`number`): The presentation time (in seconds) that the cue should start. Specifically for VOD streams the startTime is relative to the start of the stream, so the value is something between 0 and duration. For live streams the startTime is absolute, so the value is something between the start of the first period and the end of the last period of the stream.
- `endTime` (`number`): The presentation time (in seconds) that the cue should end. Allowed values follow the same rules as startTime. It is possible for endTime and startTime to be equal, in which case the cue is considered to be a discrete point on the timeline.
- `value` (`string`): Specifies the value for the cue.
- `schemeIdUri` (`string`): Identifies the message scheme.
- `eventElement` (`Element | null`): The XML element that defines the Event. Defined only for DASH.
- `type` (`clpp.TimelineCueType`): The type of this timeline cue e.g. SCTE35.

## clpp.TimelineCueType (enum)

Enum for types of timeline cues.

Values:

- `SCTE35` = `scte35`: Identifies SCTE35 markers
- `DASH_CALLBACK` = `mpeg-dash-callback-event`: Identifies an MPEG-DASH callback event
- `DASH_ALTERNATIVE_MPD` = `mpeg-dash-alternative-mpd-event`: Identifies an MPEG-DASH Alternative MPD event.
- `HLS_DATERANGE` = `hls-daterange`: Identifies an HLS EXT-X-DATERANGE cue type.
- `DASH_SVTA_AD_SIGNALING` = `mpeg-dash-svta-ad-signaling`: Identifies an MPEG-DASH event carrying SVTA signaling. HLS date ranges with SVTA signaling use the `HLS_DATERANGE` type.
- `UNKNOWN` = `unknown`: Unknown or unsupported timeline cue type.

## clpp.TimelineOffset (typedef)

Information about the wall-clock time of the player's timeline. It can be used to display the wall-clock time of the playback of a live stream in the UI. This is only available for HLS playback via the MSE player.

Properties:

- `offsetDateTime` (`number`): The offset in seconds that can be added to timeline position and seek range in order to get the wall-clock time for these values.
- `seekRangeStartDateTime` (`number`): The wall-clock time in seconds of the initial start of the seek range. (Seek range changes during live playback as new segments become available and old ones stop being available. This value refers to the seek range at the very beginning of playback of the stream.) This value is taken directly from the EXT-X-PROGRAM-DATE-TIME HLS tag.

Example: Get the wall-clock time of the player timeline

```js
const offset = player.getTimelineOffset();
if (offset) {
  // Get the wall-clock values for UI
  const position = player.getPosition() + offset.offsetDateTime;
  const start = player.getSeekRange().start + offset.offsetDateTime;
  const end = player.getSeekRange().end + offset.offsetDateTime;
}
```

## clpp.TizenConfiguration (typedef)

The `tizen` (`clpp.BasePlayerConfiguration#tizen`) subsection of player configuration.

Configuration for Tizen version 2.

Properties:

- `sideStreamText` (`boolean`, optional), default `false`: Enable this to stream text alongside the native player.

  This can enable subtitles for use cases that are not supported by the native player e.g. subtitles embedded inside a DASH stream.

## clpp.Track (class)

Constructor:

```ts
new clpp.Track(id: string, type: clpp.Track.Type)
```

This is the unified track model exposed by the player. The class wraps around properties exposed by media tracks currently available in the player.

A lot of the properties exposed by the track are optional and might not be available. You should always check for null on the optional properties.

Parameters:

- `id` (`string`): The unique track ID.
- `type` (`clpp.Track.Type`): The track type

### Properties

#### clpp.Track#id

Type: `string`

The unique track ID. Please note that the uniqueness is relevant for all tracks of the same type, i.e. all video tracks should have distinguishable IDs, but might share IDs with audio tracks.

#### clpp.Track#type

Type: `clpp.Track.Type`

The track type.

#### clpp.Track#roles

Type: `Array<string>`

The roles of the track, e.g. 'main', 'caption', or 'commentary'.

#### clpp.Track#kind

Type: `string | null`

The track kind. This can be for instance be 'captions', 'subtitles' or 'forced`.

#### clpp.Track#language

Type: `string | null`

The language associated with this track. This value is normalized - language part is always lowercase and translated to ISO-639-1 if possible.

#### clpp.Track#originalLanguage

Type: `string | null`

The original language manifest value associated with this track. Language value of the track, as it is present in the manifest. This is the exact value provided in the manifest; for normalized value use `language` property.

#### clpp.Track#label

Type: `string | null`

An optional label associated with this track.

#### clpp.Track#frameRate

Type: `number | null`

The frame rate of this track. Only defined if this is a video track and frame rate information is available.

#### clpp.Track#trickPlay

Type: `boolean`

True indicates that this track is intended for trick mode playback.

*Note* that tracks marked as trick play are completely ignored by ABR, meaning their renditions are not considered for automatic selection when the normal track associated with this trick play track is active. It is also not possible to enable ABR when the currently active track is a trick play track. You can only manually select a desired trick play tracks and its renditions using methods from `clpp.TrackManager`.

Example: List and select trick play track

```js
const player = new clpp.Player(...);
  const trackManager = player.getTrackManager();
  const videoTracks = trackManager.getVideoTracks();
  console.log(videoTracks);
  // Output:
  // [
  //   0 : clpp.Track {…, trickPlay: false, …}, // normal video track
  //   1 : clpp.Track {…, trickPlay: true, …} // trick play track
  // ]
  // Now select the trick play track. This will select first rendition
  // of the trick play track.
  trackManager.selectVideoTrack(videoTracks[1]);
  // Output:
  // [clpp.mse.Player] Disable ABR and enable manual track selection to
  // select 1280x720@4112000
  // Select different rendition of the trick play track if needed.
  trackManager.setVideoRendition(videoTracks[1].renditions[1]);
  // It's impossible to enable ABR when trick play track is selected.
  trackManager.setVideoRendition();
  // Output:
  // [clpp.mse.TrackManager] Enabling ABR for trick play tracks is not
  // supported
  // To enable ABR, select normal video track first
  trackManager.selectVideoTrack(videoTracks[0]);
  // And then enable ABR with
  trackManager.setVideoRendition();
  // Output:
  // [clpp.mse.Player] Enable ABR Selection
```

#### clpp.Track#mimeType

Type: `string | null`

The MIME type of this track.

#### clpp.Track#src

Type: `string | null`

The URL to the source of this track. This is usually set for side-loaded remote text tracks.

#### clpp.Track#channelsCount

Type: `number | null`

The count of the audio track channels.

#### clpp.Track#spatialAudio

Type: `boolean`

True indicates that the content has spatial audio.

#### clpp.Track#renditions

Type: `Array<clpp.Rendition>`

Renditions of this track.

#### clpp.Track#accessibility

Type: `Array<clpp.TrackAccessibility>`

Accessibility features of this track.

### Methods

#### clpp.Track#toString

```ts
toString(): string
```

Returns a short string representation of this track for debugging.

Returns: `string` - Simple string representation for this track

## clpp.Track.Type (enum)

Enum for types of media tracks.

Values:

- `VIDEO` = `video`: Video tracks
- `AUDIO` = `audio`: Audio tracks
- `TEXT` = `text`: Text tracks
- `METADATA` = `metadata`: Metadata tracks

## clpp.TrackAccessibility (typedef)

Track Accessibility describes the accessibility features provided by a track.

In general accessibility features are features designed to help bring the media to a larger audience, such as the vision-impaired or hearing-impaired.

Properties:

- `value` (`string`, optional), default `""`: For HLS this corresponds to MCT Media Characteristic Tags (e.g. "public.easy-to-read"). For DASH this corresponds to `Accessibility@value` (e.g. "caption").
- `protocol` (`'DASH' | 'HLS'`): The streaming protocol.
- `type` (`clpp.Track.Type`, optional): The type of the stream.
- `id` (`string`, optional): ID of the accessibility feature, this may be defined only in DASH.
- `scheme` (`string`, optional): Scheme of the accessibility feature, this may be defined only in DASH and it corresponds to the `Accessibility@schemeIdUri` attribute.

## clpp.TrackManager (class)

Constructor:

```ts
new clpp.TrackManager()
```

Track manager provides information about available tracks and methods to manage them. Call `getTrackManager()` (`clpp.Player#getTrackManager`) to obtain an instance.

Use this module to query available video, audio, and text tracks in the currently playing stream. There are two data structures: tracks and renditions. Typically video renditions represent different levels of video quality. Audio and text tracks then typically represent different audio languages or languages of subtitles.

By default ABR algorithm is used to automatically select the best level of video quality suitable for the current network bandwidth.

You can also side-load external subtitle or caption files at runtime via `addTextTrack()` (`clpp.TrackManager#addTextTrack`).

Example: Obtain an instance of track manager from the player.

```js
const trackManager = player.getTrackManager();
```

Example: Listen to track change events on the player.

```js
player.on(clpp.events.TEXT_TRACK_CHANGED, () => {
  // Text track changed
});

player.on(clpp.events.AUDIO_TRACK_CHANGED, () => {
  // Audio track changed
});
```

Example: Listen to video rendition change on the player.

```js
player.on(clpp.events.BITRATE_CHANGED, () => {
  // Video bitrate changed (rendition changed)
});
```

Example: Side-load subtitles for a VOD stream.

```js
const trackManager = player.getTrackManager();
trackManager.addTextTrack({
  url: 'https://...subs-en.vtt',
  language: 'en',
  label: 'English',
  kind: 'subtitles',
  mimeType: 'text/vtt'
});
```

### Methods

#### clpp.TrackManager#canSelectVideoTracks

```ts
canSelectVideoTracks(): boolean
```

Returns whether this platform supports manual video track selection. When false, any calls to `setVideoTrack()` (`clpp.TrackManager#setVideoTrack`) or `setVideoRendition()` (`clpp.TrackManager#setVideoRendition`) will have no effect.

Returns: `boolean` - `true` if video track selection is supported.

#### clpp.TrackManager#getVideoTracks

```ts
getVideoTracks(): Array<clpp.Track>
```

Returns all video tracks available for the currently loaded content. Each track may contain multiple `clpp.Rendition` objects representing different quality levels.

Returns: `Array<clpp.Track>` - The list of video tracks.

#### clpp.TrackManager#getAudioTracks

```ts
getAudioTracks(): Array<clpp.Track>
```

Returns all audio tracks available for the currently loaded content. Tracks typically represent different languages or audio descriptions.

Returns: `Array<clpp.Track>` - The list of audio tracks.

#### clpp.TrackManager#getTextTracks

```ts
getTextTracks(): Array<clpp.Track>
```

Returns all text tracks available for the currently loaded content. Text tracks can be subtitles or closed captions, typically they represent different languages.

Returns: `Array<clpp.Track>` - The list of text tracks.

#### clpp.TrackManager#getVideoRendition

```ts
getVideoRendition(): clpp.Rendition | null
```

Returns the video rendition that is currently being played.

Returns: `clpp.Rendition | null` - The active video rendition, or null.

#### clpp.TrackManager#getAudioRendition

```ts
getAudioRendition(): clpp.Rendition | null
```

Returns the audio rendition that is currently being played. Each audio track typically contains exactly one audio rendition.

Returns: `clpp.Rendition | null` - The active audio rendition, or null.

#### clpp.TrackManager#getTextRendition

```ts
getTextRendition(): clpp.Rendition | null
```

Returns the text rendition that is currently being displayed. When no text rendition is selected it returns `null`.

Returns: `clpp.Rendition | null` - The active text rendition, or null.

#### clpp.TrackManager#getLoadingVideoRendition

```ts
getLoadingVideoRendition(): clpp.Rendition | null
```

Returns the video rendition that has been selected but not yet fully switched to. When player switches to the selected rendition this returns `null`.

Returns: `clpp.Rendition | null` - The loading video rendition, or null.

#### clpp.TrackManager#getLoadingAudioRendition

```ts
getLoadingAudioRendition(): clpp.Rendition | null
```

Returns the audio rendition that has been selected but not yet fully switched to. When player switches to the selected rendition this returns `null`.

Returns: `clpp.Rendition | null` - The loading audio rendition, or null.

#### clpp.TrackManager#getLoadingTextRendition

```ts
getLoadingTextRendition(): clpp.Rendition | null
```

Returns the text rendition that has been selected but not yet fully switched to. When player switches to the selected rendition this returns `null`.

Returns: `clpp.Rendition | null` - The loading text rendition, or null.

#### clpp.TrackManager#getVideoTrack

```ts
getVideoTrack(): clpp.Track | null
```

Returns the currently selected video track.

Returns: `clpp.Track | null` - The active video track, or null.

#### clpp.TrackManager#getAudioTrack

```ts
getAudioTrack(): clpp.Track | null
```

Returns the currently selected audio track.

Returns: `clpp.Track | null` - The active audio track, or null.

#### clpp.TrackManager#getTextTrack

```ts
getTextTrack(): clpp.Track | null
```

Returns the currently selected text track. If no text track is selected this returns `null`.

Returns: `clpp.Track | null` - The active text track, or null.

#### clpp.TrackManager#setVideoTrack

```ts
setVideoTrack(track: clpp.Track | null)
```

Selects the given video track as the active track. Pass `null` to let the player choose automatically. Has no effect if `canSelectVideoTracks()` (`clpp.TrackManager#canSelectVideoTracks`) returns false.

Parameters:

- `track` (`clpp.Track | null`): The video track to activate, or null.

#### clpp.TrackManager#setAudioTrack

```ts
setAudioTrack(track: clpp.Track | null)
```

Selects the given audio track as the active track. Call this for example to switch to a different audio language. Pass `null` to let the player choose automatically.

Parameters:

- `track` (`clpp.Track | null`): The audio track to activate, or null.

#### clpp.TrackManager#setTextTrack

```ts
setTextTrack(track: clpp.Track | null)
```

Selects the given text track as the active track, enabling subtitles or captions. Pass `null` to disable text track rendering.

Parameters:

- `track` (`clpp.Track | null`): The text track to activate, or null to disable.

#### clpp.TrackManager#setVideoRendition

```ts
setVideoRendition(rendition: clpp.Rendition | null, clearBuffer?: boolean)
```

Locks playback to a specific video rendition (quality level), bypassing ABR. Pass `null` to re-enable automatic ABR selection.

When clearBuffer is true, the current buffer is flushed to apply the switch immediately. Otherwise, already buffered video stays at the quality it was buffered at and only newly buffered media has the newly selected quality level.

Parameters:

- `rendition` (`clpp.Rendition | null`): The video rendition to lock to, or null to re-enable ABR.
- `clearBuffer` (`boolean`, optional): Whether to flush the buffer on switch.

#### clpp.TrackManager#setAudioRendition

```ts
setAudioRendition(rendition: clpp.Rendition | null, clearBuffer?: boolean)
```

Selects the given audio rendition as the active one.

Parameters:

- `rendition` (`clpp.Rendition | null`): The rendition
- `clearBuffer` (`boolean`, optional): clear buffer

#### clpp.TrackManager#setTextRendition

```ts
setTextRendition(rendition: clpp.Rendition | null, clearBuffer?: boolean)
```

Selects the given text rendition as the active one. Pass `null` to disable subtitles.

Parameters:

- `rendition` (`clpp.Rendition | null`): The rendition
- `clearBuffer` (`boolean`, optional): clear buffer

#### clpp.TrackManager#findVideoTrack

```ts
findVideoTrack(filter: Record<string, unknown>): clpp.Track | null
```

Searches video tracks for the first one matching the filter.

Returns the video track whose properties match all key-value pairs in the filter object. Useful for selecting a track by codec, or any other `clpp.Track` property.

Parameters:

- `filter` (`Record<string, unknown>`): An object whose keys and values must all match the corresponding properties of the returned track.

Returns: `clpp.Track | null` - The first matching video track, or `undefined` if no track matches.

#### clpp.TrackManager#findAudioTrack

```ts
findAudioTrack(filter: Record<string, unknown>): clpp.Track | null
```

Searches the audio tracks for the first one matching the filter.

Returns the audio track whose properties match all key-value pairs in the filter object. Useful for selecting a track by language, codec, or any other `clpp.Track` property.

Parameters:

- `filter` (`Record<string, unknown>`): An object whose keys and values must all match the corresponding properties of the returned track.

Returns: `clpp.Track | null` - The first matching audio track, or `undefined` if no track matches.

#### clpp.TrackManager#findTextTrack

```ts
findTextTrack(filter: Record<string, unknown>): clpp.Track | null
```

Searches the text tracks for the first one matching the filter.

Returns a text track whose properties match all key-value pairs in the filter object. Useful for selecting a track by language, kind, or any other `clpp.Track` property.

Parameters:

- `filter` (`Record<string, unknown>`): An object whose keys and values must all match the corresponding properties of the returned track.

Returns: `clpp.Track | null` - The first matching text track, or `undefined` if no track matches.

#### clpp.TrackManager#findVideoRendition

```ts
findVideoRendition(filter: Record<string, unknown>): clpp.Rendition | null
```

Searches across all video renditions for the first one matching the filter.

Returns the video rendition whose properties match all key-value pairs in the filter object. Useful for finding a rendition by bitrate, resolution, or codec.

Parameters:

- `filter` (`Record<string, unknown>`): An object whose keys and values must all match the corresponding properties of the returned rendition.

Returns: `clpp.Rendition | null` - The first matching video rendition, or `undefined` if no rendition matches.

#### clpp.TrackManager#findAudioRendition

```ts
findAudioRendition(filter: Record<string, unknown>): clpp.Rendition | null
```

Searches across all audio renditions for the first one matching the filter.

Parameters:

- `filter` (`Record<string, unknown>`): filter object containing desired rendition properties.

Returns: `clpp.Rendition | null` - desired rendition or `undefined` if not found.

#### clpp.TrackManager#findTextRendition

```ts
findTextRendition(filter: Record<string, unknown>): clpp.Rendition | null
```

Searches across all text renditions for the first one matching the filter.

Parameters:

- `filter` (`Record<string, unknown>`): filter object containing desired rendition properties.

Returns: `clpp.Rendition | null` - desired rendition or `undefined` if not found.

#### clpp.TrackManager#addTextTrack

```ts
addTextTrack(track: clpp.RemoteTextTrack): Promise<void>
```

Side-loads an external text track from a remote URL.

Loads a text track from a URL and makes it available for selection alongside any tracks embedded in the manifest. The returned promise resolves once the track has been successfully added.

Parameters:

- `track` (`clpp.RemoteTextTrack`): The remote text track descriptor to load.

Returns: `Promise<void>` - Resolves when the track has been added.

#### clpp.TrackManager#isAbrEnabled

```ts
isAbrEnabled(): boolean
```

Returns whether Adaptive Bitrate (ABR) selection is currently active. When enabled, the player automatically picks the optimal rendition based on available bandwidth and buffer health. When disabled, the rendition locked via `setVideoRendition()` (`clpp.TrackManager#setVideoRendition`) or `setAudioRendition()` (`clpp.TrackManager#setAudioRendition`) is used. By default ABR is enabled.

Returns: `boolean` - `true` if ABR is enabled, `false` otherwise.

## clpp.TrickPlayConfiguration (typedef)

The `trickPlay` (`clpp.BasePlayerConfiguration#trickPlay`) subsection of player configuration.

Configuration of trick play (fast-forwarding, rewinding, scrubbing, etc).

Properties:

- `speedUpMode` (`clpp.SpeedUpMode`, optional), default `DECODER`: How playback rates other than 1 are achieved.

  - **Decoder:** the video plays at the requested rate. Smooth, but supported rates vary per platform and rewinding is not possible. Negative or unsupported rates fall back to Seek mode.
  - **Seek:** playback is paused and the player seeks repeatedly. Works for any rate, including negative rates for rewinding, and downloads fewer segments at high rates, but playback stutters. Consider hiding the buffering indicator in this mode. Recommended for platforms with limited Decoder mode support.
- `preferTrickPlayTracks` (`boolean`, optional), default `true`: Enable to use content's dedicated trick play track (I-frame only) for trick play if available. This saves bandwidth and decoding power when scrubbing at high rates.

  Disable it to keep smooth full-quality video at moderate rates (e.g. 1.5x) where switching to trick play tracks is not necessary. Also disable if you want to control trick play tracks manually via `clpp.TrackManager`, or if the content's trick play track is broken.

## clpp.TtmlConfiguration (typedef)

The `ttml` (`clpp.BasePlayerConfiguration#ttml`) subsection of player configuration.

Configuration of TTML subtitles (including SMPTE-TT and IMSC1).

TTML may position and size subtitles in pixels of the canvas they were authored for. The player converts these to relative values (% and `em`) so subtitles scale with the video. The canvas size and base font size are taken from the document's `tts:extent` and `ttp:cellResolution`. Use these options when a document uses pixels without declaring them, i.e. when subtitles are misplaced or wrongly sized. Values set here override the TTML document.

Properties:

- `containerHeight` (`number`, optional), default `480`: Height in pixels of the authoring canvas. Used to convert vertical pixel positions and sizes. Falls back to `tts:extent`, then 480.
- `containerWidth` (`number`, optional), default `720`: Width in pixels of the authoring canvas. Used to convert horizontal pixel positions and sizes. Falls back to `tts:extent`, then 720.
- `fontSizeRadix` (`number`, optional), default `16`: Base font size in pixels (`1em`). Pixel font sizes are divided by it, e.g. with 16, `24px` becomes `1.5em`. Falls back to canvas height divided by `ttp:cellResolution` rows, then 16.

## clpp.Type (enum)

Stream types that can be used to specify content mime types explicitly.

Values:

- `DASH` = `application/dash+xml`: This type identifies DASH content.
- `HLS` = `application/x-mpegurl`: Identifies HLS content and m3u8 playlists
- `SMOOTH_STREAMING` = `application/vnd.ms-sstr+xml`: Identifies SmoothStreaming content
- `MP4` = `video/mp4`: Identifies mp4 files
- `MP3` = `audio/mp3`: Identifies mp3 files

## clpp.VerimatrixVcasConfiguration (typedef)

The Verimatrix VCAS Ultra configuration.

Properties:

- `deviceId` (`string`): The device's Verimatrix unique identifier (VUID)
- `authenticator` (`string`, optional): Optional third-party authentication to the Subscriber Management System (SMS).
- `licenseRequestVuidLocation` (`clpp.verimatrix.Vcas.LicenseRequestVuidLocation`, optional): Method for passing `deviceId` and `authenticator` (if defined) to the license server. They could be inserted into one of two potential locations in the license acquisition request:
  - `QUERY_STRING` - Base64 encoded query string parameters.
  - `HTTP_HEADER` - custom HTTP request headers. If you use this method, please configure header names accepted by your license server in `httpHeaderNames` Default: `QUERY_STRING`
- `httpHeaderNames` (`Record<clpp.verimatrix.Vcas.LicenseRequestHttpHeader, string>`, optional): Defines custom HTTP header names for passing `deviceId` and `authenticator` to the license server. It's used when `licenseRequestVuidLocation` is set to `HTTP_HEADER` otherwise ignored. Default: `     {        LicenseRequestHttpHeader.DEVICE_ID: 'DeviceId',        LicenseRequestHttpHeader.AUTHENTICATOR_HEADER: 'Authenticator'      }     `
- `widevineLicenseUrl` (`string`): The Widevine license server URL.
- `playReadyLicenseUrl` (`string`): The Playready license server URL.
- `fairPlayLicenseUrl` (`string`): The Fairplay license server URL.
- `fairPlayCertificateUrl` (`string`): The Fairplay certificate URL.
- `fairPlaySiteId` (`string`, optional): The unique identifier of the site to which the subscriber is associated. Used only in conjunction with fairPlayAssetIdStrategy set to `CONTENTID_SITEID`.
- `fairPlayAssetIdStrategy` (`clpp.verimatrix.Vcas.FairPlayAssetIdStrategy`, optional): FairPlay assetId acquisition strategy. Default: `clpp.verimatrix.Vcas.FairPlayAssetIdStrategy.KEYID`

## clpp.VimondPlayerEventBody (typedef)

Event template.

Properties:

- `originator` (`string`, optional): Originator. Filled by the integrator.
- `timestamp` (`string`, optional): Date when the play event is sent following the ISO 8601 Extended Format. Filled by the plugin.
- `client` (`clpp.VimondPlayerEventClient`, optional): Client info.
- `progress` (`clpp.VimondPlayerEventProgress`, optional): Stream info.

## clpp.VimondPlayerEventClient (typedef)

Client information of a Vimond player event, describing the player, the device, the stream and the current playback state.

Properties:

- `buildName` (`string`, optional): Player's name. Filled by the plugin.
- `buildVersion` (`string`, optional): Player's version. Filled by the plugin.
- `deviceId` (`string`, optional): End-user's device id. Filled by the integrator.
- `drm` (`string`, optional): Data right management type. Empty if unprotected content. Filled by the plugin.
- `envPlatform` (`string`, optional): Underling technology. For example 'silverlight'. Filled by the integrator.
- `envVersion` (`string`, optional): Version of the underling technology Filled by the integrator.
- `pageUrl` (`string`, optional): Page url on which the client played this asset. Filled by the plugin.
- `playerEvent` (`string`, optional): Event which occurred during a playback session. Filled by the plugin.
- `playerState` (`string | null`, optional): Values for this field are "playing", "pause" and null. Filled by the plugin. Null if ended.
- `streamUrl` (`string`, optional): Stream url played by the client. Filled by the plugin.
- `userAgent` (`string`, optional): User agent of the browser. Filled by the plugin.
- `videoFormat` (`string`, optional): Mime type of the stream played by the client. Filled by the plugin.
- `videoProtocol` (`string`, optional): Network protocol of the stream. Filled by the plugin.
- `viewingSession` (`string`, optional): End-user's viewing session. Filled by the integrator.

## clpp.VimondPlayerEventLive (typedef)

Live progress information of a Vimond player event, sent when playing live content.

Properties:

- `onLiveEdge` (`boolean`, optional): True if close to the live edge. False otherwise. Filled by the plugin.
- `liveResumePossible` (`boolean`, optional): True if live resume possible. False otherwise. Filled by the plugin if not defined. Default is True.
- `position` (`string`, optional): Current position of the stream following the ISO 8601 Extended Format. Filled by the plugin.

## clpp.VimondPlayerEventProgress (typedef)

Playback progress information of a Vimond player event, i.e. the event number and the VOD or live position.

Properties:

- `eventNumber` (`number`, optional): Event number used for synchronization purposes. Filled by the plugin.
- `vod` (`clpp.VimondPlayerEventVod`, optional): Vod info.
- `live` (`clpp.VimondPlayerEventLive`, optional): Live info.

## clpp.VimondPlayerEventRequest (typedef)

The request sent to the Vimond Player Session endpoint, i.e. the endpoint URL, the event template and how often events are sent.

Properties:

- `body` (`clpp.VimondPlayerEventBody`, optional): Event template.
- `eventInterval` (`number`, optional): The first event is triggered on play. The second event is triggered after 10 seconds. Next, an event is triggered after X seconds from the last one. Where X is the value of the `eventInterval`.
- `uri` (`string`, optional): URL of the Vimond Player Session endpoint.

## clpp.VimondPlayerEventVod (typedef)

VOD progress information of a Vimond player event, sent when playing on-demand content.

Properties:

- `position` (`number`, optional): Current position of the stream. Filled by the plugin.

## clpp.VrConfiguration (typedef)

The `vr` (`clpp.BasePlayerConfiguration#vr`) subsection of player configuration.

Configuration of virtual reality (VR) plugin which enables 360 video.

Properties:

- `enable` (`boolean`, optional), default `false`: Enable the VR plugin.
- `attachMouseListener` (`boolean`, optional), default `true`: Attach mouse listeners to the VR canvas to change the camera position.
- `fieldOfView` (`number`, optional), default `70`: The default field of view of the camera.
- `sensitivity` (`number`, optional), default `1`: The mouse/touch controls sensitivity multiplier. Must be a positive number.

  Example: 2 means that the mouse is 2x as sensitive.
- `invertHorizontalControl` (`boolean`, optional), default `false`: Invert the mouse/touch movement for horizontal axis.
- `invertVerticalControl` (`boolean`, optional), default `false`: Invert the mouse/touch movement for vertical axis.

## clpp.WidevineDrmSystem (typedef)

The main property is the `licenseUrl` to the DRM backend, but you would usually also implement at least some of the network modifier. This can be used for example to add some headers to the license request, or to access and even modify the responses.

Properties:

- `licenseUrl` (`string`, optional): The URL to the license server. If a DASH manifest contains License Acquisition URL(s) then this can be set to an empty string and the license server URL will be taken from the manifest.
- `videoRobustness` (`undefined | clpp.drm.WidevineRobustnessLevel | Array<(undefined|clpp.drm.WidevineRobustnessLevel)>`, optional): The EME video robustness level. Please note that you usually do not need to specify this, the player will find an appropriate value based on the current platform and browser. You can also configure an array ordered by priority in descending order.
- `audioRobustness` (`undefined | clpp.drm.WidevineRobustnessLevel | Array<(undefined|clpp.drm.WidevineRobustnessLevel)>`, optional): The EME audio robustness level. Please note that you usually do not need to specify this, the player will find an appropriate value based on the current platform and browser. You can also configure an array ordered by priority in descending order.
- `distinctiveIdentifierRequired` (`boolean`, optional), default `false`: Set this to `true` if the application requires the key system to support distinctive identifiers.
- `persistentStateRequired` (`boolean`, optional), default `false`: Set this to `true` if the application requires the key system to support persistent state, e.g., for persistent license storage.
- `serverCertificate` (`Uint8Array`, optional), default `null`: The certificate will be requested from the license server if required. A key-system-specific server certificate used to encrypt license requests. Its use is optional and is meant as an optimization to avoid a round-trip to request a certificate. Please note that the player already caches the certificate to avoid the round-trip on the second request and there is usually no need to explicitly specify the certificate here.
- `individualizationServer` (`string`, optional): The server that handles an 'individualization-request'. If the server isn't given, it will default to the license server.
- `modifiers` (`clpp.drm.LicenseModifiers`, optional): A set of callbacks to perform modifications on license/certificate requests and/or responses.

## clpp.YospaceConfiguration (typedef)

The `yospace` (`clpp.BasePlayerConfiguration#yospace`) subsection of player configuration.

Configuration of Yospace ad management plugin.

Properties:

- `enabled` (`boolean`, optional), default `false`: Enable Yospace ad management plugin.
- `streamType` (`clpp.yospace.StreamType`, optional), default `clpp.yospace.StreamType.VOD`: The type of the stream.

## clpp.YouboraErrorFilter (callback)

```ts
function(error: clpp.Error): clpp.YouboraErrorPayload | null
```

A function that converts a `clpp.Error` to a payload for Youbora analytics service `clpp.YouboraErrorPayload`. If it returns `null`, the error will not be sent.

Parameters:

- `error` (`clpp.Error`): The error that occurred during playback.

Returns: `clpp.YouboraErrorPayload | null` - The payload to send to Youbora, or `null` to not report the error.

Example: Custom Youbora Error Filter

```js
function (error) {
   if (error.code === 1) return null;

   return {
     code: `${error.code}`,
     message: error.message,
     severity: error.severity,
     metadata: { ... },
   };
 };
```

## clpp.YouboraErrorPayload (typedef)

A payload to be sent to Youbora Analytics service in order to report an error that occurred during playback.

Properties:

- `code` (`string`, optional): The error code as string
- `message` (`string`, optional): The error message
- `severity` (`clpp.Error.Severity`, optional): The error severity
- `metadata` (`Object`, optional): Additional metadata further describing the error

## clpp.ads.ErrorType (enum)

Enum with all possible ad error types.

Values:

- `LOAD` = `0`: 0 - An error occurred when loading cue points or ad metadata.
- `PLAY` = `1`: 1 - An error occurred when playing ad.
- `OTHER` = `2`: 2 - Other error

## clpp.ads.IAd (interface)

Interface for advertisements. The same interface is used for various delivery methods including CSAI, SSAI and SGAI.

### Methods

#### clpp.ads.IAd#getAdManagerName

```ts
getAdManagerName(): string
```

The ad manager name.

Returns: `string` - The ad manager name.

#### clpp.ads.IAd#getAdManagerVersion

```ts
getAdManagerVersion(): string
```

The ad manager version.

Returns: `string` - The ad manager version.

#### clpp.ads.IAd#getTechnology

```ts
getTechnology(): clpp.ads.Technology
```

The technology of the ad, for example client side or server side.

Returns: `clpp.ads.Technology` - The technology of the ad.

#### clpp.ads.IAd#getId

```ts
getId(): string
```

The ID of the ad, or empty string if this information is unavailable.

Returns: `string` - The ID of the ad.

#### clpp.ads.IAd#getCreativeId

```ts
getCreativeId(): string
```

Retrieves the ID of the selected creative for the ad.

Returns: `string` - The ID of the selected creative for the ad, or the empty string if this information is unavailable.

#### clpp.ads.IAd#getSourceId

```ts
getSourceId(): string | null
```

The ID of the ad source.

In case of HLS interstitials this is the EXT-X-DATERANGE:ID.

Returns: `string | null` - The ID of the ad source.

#### clpp.ads.IAd#getApiFramework

```ts
getApiFramework(): string | null
```

Identifies the API needed to execute the ad. This corresponds with the apiFramework specified in vast.

Returns: `string | null` - The API framework need to execute the ad, or null if this information is unavailable.

#### clpp.ads.IAd#getAdSystem

```ts
getAdSystem(): string
```

The source ad server of the ad, or the empty string if this information is unavailable.

Returns: `string` - The source ad server of the ad.

#### clpp.ads.IAd#getAdvertiserName

```ts
getAdvertiserName(): string
```

The advertiser name, or the empty string if this information is unavailable.

Returns: `string` - The advertiser name of the ad.

#### clpp.ads.IAd#getTitle

```ts
getTitle(): string
```

The title, empty if not specified.

Returns: `string` - The title of the ad.

#### clpp.ads.IAd#getDuration

```ts
getDuration(): number
```

The duration of the ad.

Returns: `number` - The duration of the ad in seconds. Returns -1 if duration is unknown.

#### clpp.ads.IAd#getPosition

```ts
getPosition(): number
```

The playback position of the ad.

Returns: `number` - The playback position of the ad in seconds.

#### clpp.ads.IAd#getSkipTimeOffset

```ts
getSkipTimeOffset(): number
```

The number of seconds of playback before the ad becomes skippable. -1 is returned for non skippable ads or if this is unavailable.

Returns: `number` - The offset in seconds.

#### clpp.ads.IAd#isBumper

```ts
isBumper(): boolean
```

Whether the ad is a bumper ad.

Returns: `boolean` - True if the ad is a bumper ad.

#### clpp.ads.IAd#getClickThroughUrl

```ts
getClickThroughUrl(): string | null
```

Returns the click through url.

Returns: `string | null` - The url of the ad or null if this information is unavailable.

#### clpp.ads.IAd#getMediaUrl

```ts
getMediaUrl(): string | null
```

Returns the url of the media file.

Returns: `string | null` - The url of the media file. or null if this information is unavailable.

#### clpp.ads.IAd#getMediaWidth

```ts
getMediaWidth(): number
```

The media width of the ad.

Returns: `number` - The media width of the ad or 0 if this information is unavailable.

#### clpp.ads.IAd#getMediaHeight

```ts
getMediaHeight(): number
```

The media height of the ad.

Returns: `number` - The media height of the ad or 0 if this information is unavailable.

#### clpp.ads.IAd#getMediaBitrate

```ts
getMediaBitrate(): number
```

Returns the media bitrate of the ad.

Returns: `number` - The media bitrate of the ad or 0 if this information is unavailable.

#### clpp.ads.IAd#getPodType

```ts
getPodType(): clpp.ads.PodType
```

The type of the ad pod.

Returns: `clpp.ads.PodType` - The type of the ad pod.

#### clpp.ads.IAd#getPodIndex

```ts
getPodIndex(): number
```

The index of the ad pod in the ad playlist.

For a preroll pod, returns 0. For midrolls, returns 1, 2,..., N. For a postroll pod, returns -1. Defaults to 0 if this ad is not part of a pod, or this pod is not part of a playlist.

Returns: `number` - The index of the ad pod.

#### clpp.ads.IAd#getPodTimeOffset

```ts
getPodTimeOffset(): number
```

The content time offset at which the current ad pod was scheduled.

For preroll pod, 0 is returned. For midrolls, the scheduled time is returned in seconds. For postroll, -1 is returned. Defaults to 0 if this ad is not part of a pod, or the pod is not part of an ad playlist.

Returns: `number` - The time offset for the ad pod.

#### clpp.ads.IAd#getPositionInSequence

```ts
getPositionInSequence(): number
```

The position of the ad within the ad pod. Starts at 1.

Returns: `number` - The position of the ad.

#### clpp.ads.IAd#getSequenceLength

```ts
getSequenceLength(): number
```

The total number of ads contained within this pod, including bumpers. Defaults to 1 if this ad is not part of a pod.

Returns: `number` - Total number of ads in the pod. Returns -1 if the length of the ad pod is unknown

#### clpp.ads.IAd#getWrapperAdIds

```ts
getWrapperAdIds(): Array<string>
```

Ad IDs used for wrapper ads. The IDs returned starts at the inline ad (innermost) and traverses to the outermost wrapper ad. An empty array is returned if there are no wrapper ads.

Returns: `Array<string>` - The IDs of the ads, starting at the inline ad, or an empty array if there are no wrapper ads.

#### clpp.ads.IAd#getWrapperAdSystems

```ts
getWrapperAdSystems(): Array<string>
```

Ad systems used for wrapper ads. The ad systems returned starts at the inline ad and traverses to the outermost wrapper ad. An empty array is returned if there are no wrapper ads.

Returns: `Array<string>` - The ad systems of the ads, starting at the inline ad, or an empty array if there are no wrapper ads.

#### clpp.ads.IAd#getWrapperCreativeIds

```ts
getWrapperCreativeIds(): Array<string>
```

Selected creative IDs used for wrapper ads. The creative IDs returned starts at the inline ad and traverses to the outermost wrapper ad. An empty array is returned if there are no wrapper ads.

Returns: `Array<string>` - The IDs of the ads' creatives, starting at the inline ad, or an empty array if there are no wrapper ads.

#### clpp.ads.IAd#getVideoElement

```ts
getVideoElement(): HTMLVideoElement | null
```

Get the underlying video element used for playback of the ad.

This is works only for HLS interstitials, in other cases it returns null.

Returns: `HTMLVideoElement | null` - The video element use for playback of this ad.

#### clpp.ads.IAd#canSeek

```ts
canSeek(): boolean
```

Whether the user can seek during the ad or change playback rate.

Returns: `boolean` - True if the user can seek during the ad or change playback rate, otherwise false.

## clpp.ads.IAdsManager (interface)

Interface for advertisement managers. It controls the skipping of advertisements and tracks playback position. Call `getAdsManager()` (`clpp.Player#getAdsManager`) to obtain an instance.

Volume and play / pause is controlled seamlessly by `clpp.Player` making the same APIs here deprecated.

### Methods

#### clpp.ads.IAdsManager#skip

```ts
skip()
```

Skips the current ad if allowed by `clpp.ads.IAd.getSkipTimeOffset()` (`clpp.ads.IAd#getSkipTimeOffset`).

#### clpp.ads.IAdsManager#getPosition

```ts
getPosition(): number
```

Gets the current time of the currently playing ad.

Returns: `number` - The current time of the current ad in seconds or -1 if no ad is playing.

#### clpp.ads.IAdsManager#resume

```ts
resume()
```

**Deprecated.** Use `clpp.Player#play` instead.

Resumes playback of the ad if it is paused.

#### clpp.ads.IAdsManager#pause

```ts
pause()
```

**Deprecated.** Use `clpp.Player#pause` instead.

Pauses the currently playing ad.

#### clpp.ads.IAdsManager#getVolume

```ts
getVolume(): number
```

**Deprecated.** Use `clpp.Player#getVolume` instead.

Gets the audio volume of the current ad.

Returns: `number` - The volume of the current ad, from 0 to 1.

#### clpp.ads.IAdsManager#setVolume

```ts
setVolume(volume: number)
```

**Deprecated.** Use `clpp.Player#setVolume` instead.

Sets the audio volume for the current ad.

Parameters:

- `volume` (`number`): The volume to set, from 0 to 1.

## clpp.ads.IAdsTimeline (interface)

Interface for the ads timeline which is a read-only view of an ad schedule, i.e. when the ad breaks of the current content will play.

It doesn't describe the ads themselves, for that see `clpp.ads.IAd`. Access specific ad metadata on `clpp.events.AD_STARTED`.

### Methods

#### clpp.ads.IAdsTimeline#getCuePoints

```ts
getCuePoints(): Array<number>
```

An array of offsets in seconds indicating when a scheduled ad break will play.

A preroll is represented by 0, and a postroll is represented by -1. An empty array indicates the ad or ad pod has no schedule and can be played at any time.

Access specific ad metadata on `clpp.events.AD_STARTED`.

Returns: `Array<number>` - The list of cue points.

#### clpp.ads.IAdsTimeline#hasPreroll

```ts
hasPreroll(): boolean
```

Returns true if a preroll is scheduled; false otherwise.

Returns: `boolean` - True if a preroll is scheduled.

#### clpp.ads.IAdsTimeline#hasPostroll

```ts
hasPostroll(): boolean
```

Returns true if a postroll is scheduled; false otherwise.

Returns: `boolean` - True if a postroll is scheduled.

## clpp.ads.PodType (enum)

Enum with all possible ad pod types.

Values:

- `PREROLL` = `0`: 0 - Pre roll
- `MIDROLL` = `1`: 1 - Mid roll
- `POSTROLL` = `2`: 2 - Post roll

## clpp.ads.Technology (enum)

Enum with all possible ad technologies.

Values:

- `CLIENT_SIDE` = `0`: 0 - Client side
- `SERVER_SIDE` = `1`: 1 - Server side
- `SERVER_GUIDED` = `2`: 2 - Server guided

## clpp.airplay.AirPlayPlugin (class)

Constructor:

```ts
new clpp.airplay.AirPlayPlugin()
```

AirPlay lets you share videos and music from Apple devices to your Apple TV.

The plugin fires `AIRPLAY_STATUS_CHANGED` (`clpp.events.AIRPLAY_STATUS_CHANGED`), `AIRPLAY_CASTING_STARTED` (`clpp.events.AIRPLAY_CASTING_STARTED`) and `AIRPLAY_CASTING_ENDED` (`clpp.events.AIRPLAY_CASTING_ENDED`) events.

### Static properties

#### clpp.airplay.AirPlayPlugin.Id

Type: `string`

The ID of the AirPlay plugin, e.g. to get the plugin instance with `clpp.Player#getPlugin`.

### Methods

#### clpp.airplay.AirPlayPlugin#isCasting

```ts
isCasting(): boolean
```

Check if casting active.

Returns: `boolean` - True if casting active; False otherwise.

#### clpp.airplay.AirPlayPlugin#canCast

```ts
canCast(): boolean
```

Check if AirPlay available.

Returns: `boolean` - True if AirPlay available; False otherwise.

#### clpp.airplay.AirPlayPlugin#showCastMenu

```ts
showCastMenu()
```

Show the airplay target selection menu.

## clpp.broadpeak.BroadpeakPlugin (class)

Constructor:

```ts
new clpp.broadpeak.BroadpeakPlugin()
```

Broadpeak plugin.

### Static properties

#### clpp.broadpeak.BroadpeakPlugin.Id

The ID of the Broadpeak plugin, e.g. to get the plugin instance with `clpp.Player#getPlugin`.

### Static methods

#### clpp.broadpeak.BroadpeakPlugin.isSdkMissing

```ts
isSdkMissing(): boolean
```

Check if Broadpeak SDK is available.

Returns: `boolean` - True if Broadpeak SDK is missing.

## clpp.cast (namespace)

### Static methods

#### clpp.cast.createCastQueue

```ts
createCastQueue(): clpp.cast.Queue
```

**Experimental:** may change without a major release.

Returns instance of Cast queue.

Returns: `clpp.cast.Queue` - A new queue instance to pass to `setQueue()` (`clpp.cast.Receiver#setQueue`).

#### clpp.cast.onReady

```ts
onReady(callback: function)
```

Add a listener for when Chromecast Sender SDK is ready to be used.

Parameters:

- `callback` (`function`): a callback called when Chromecast Sender SDK is ready to be used.

## clpp.cast.CastProxy (class)

Constructor:

```ts
new clpp.cast.CastProxy(player: clpp.Player, receiverAppId: string, onResumeLocal?: function)
```

Cast Proxy enables Chromecast sender functionality.

It can start a casting session to a selected Receiver App, stop the session, checks whether casting is possible, notifies about status changes, and can set metadata for the casted content.

It attaches to a `clpp.Player` instance and switches its underlying player engine between local player (during normal playback) and cast player based on Chromecast Sender SDK (during casting). This way you control remote playback in the Receiver App with the same `clpp.Player` API as you do normal playback.

Designed to be used with `clpp.cast.Receiver` on the receiver side.

Parameters:

- `player` (`clpp.Player`): a player instance
- `receiverAppId` (`string`): ID of receiver application. If blank, casting will not be available, but the proxy will still function otherwise.
- `onResumeLocal` (`function`, optional): Callback function to add specific logic that should be executed after session ends. If not provided, default callback implementation is used.

### Methods

#### clpp.cast.CastProxy#destroy

```ts
destroy(): Promise<void>
```

Destroys the proxy.

Returns: `Promise<void>` - Resolves once the Cast sender has been disposed.

#### clpp.cast.CastProxy#canCast

```ts
canCast(): boolean
```

Checks if it is possible to cast to a Receiver App.

For this the `receiverAppId` supplied in the constructor must be correct, it must point to a published Receiver App and a Chromecast target device must be available for connection on your WiFi network.

Returns: `boolean` - true if it is possible to cast to one or more target devices

#### clpp.cast.CastProxy#isCasting

```ts
isCasting(): boolean
```

Checks if a casting session is in progress.

Returns: `boolean` - true if a casting session is in progress

#### clpp.cast.CastProxy#getReceiverName

```ts
getReceiverName(): string
```

Gets name of currently connected receiver.

Returns: `string` - name of receiver or an empty string if not connected

#### clpp.cast.CastProxy#setPlayerConfigInterceptor

```ts
setPlayerConfigInterceptor(interceptor: clpp.cast.utils.PlayerConfigInterceptor | null)
```

Set player configuration interceptor.

Gives a possibility to intercept player configuration during casting to modify it if necessary. The interceptor callback takes player config as an argument. The function should return a new configuration in synchronous or asynchronous way. If nothing is returned, the player will use the original config.

Parameters:

- `interceptor` (`clpp.cast.utils.PlayerConfigInterceptor | null`): a callback which modifies the configuration object

Example: Intercept player configuration to update auth token.

```js
castProxy.setPlayerConfigInterceptor(async (config) => {
  // use your business logic to obtain new authToken
  const authToken = await getAuthTokenForContent(config);
  config.drm.customData.authToken = authToken;
  return config;
});
```

#### clpp.cast.CastProxy#cast

```ts
cast(opt_playerConfig?: clpp.PlayerConfiguration, opt_queueOptions?: clpp.cast.QueueOptions): Promise<void>
```

Start casting.

If the player has some loaded content, it will be casted. Otherwise, the casting session will start empty and wait for a call to `player.open()` (`clpp.Player#open`).

Parameters:

- `opt_playerConfig` (`clpp.PlayerConfiguration`, optional): optional configuration to cast. If omitted, player will try to cast current content
- `opt_queueOptions` (`clpp.cast.QueueOptions`, optional): optional queue items and starting index to load

Returns: `Promise<void>` - Resolves once casting has started and the content has been loaded on the receiver. Errors are not rejected but dispatched as an `error` event.

#### clpp.cast.CastProxy#forceDisconnect

```ts
forceDisconnect()
```

Stop the receiver application.

#### clpp.cast.CastProxy#changeReceiverId

```ts
changeReceiverId(newAppId: string): Promise<void>
```

Change the receiver ID. If a casting session is in progress it will be closed first.

Parameters:

- `newAppId` (`string`): new receiver application ID

Returns: `Promise<void>` - Resolves once the previous sender has been disposed and a new one has been created for the given receiver ID.

#### clpp.cast.CastProxy#sendMessage

```ts
sendMessage(message: Record<string, unknown> | string): Promise<void>
```

Sends a custom message to the Receiver App.

Parameters:

- `message` (`Record<string, unknown> | string`): a message object

Returns: `Promise<void>` - Resolves once the message has been sent.

#### clpp.cast.CastProxy#queueNextItem

```ts
queueNextItem(): Promise<void>
```

Requests the receiver to advance to the next queue item.

Returns: `Promise<void>` - Resolves once the request has been sent.

#### clpp.cast.CastProxy#queuePreviousItem

```ts
queuePreviousItem(): Promise<void>
```

Requests the receiver to move to the previous queue item.

Returns: `Promise<void>` - Resolves once the request has been sent.

#### clpp.cast.CastProxy#queueAddItems

```ts
queueAddItems(items: Array<cast.framework.messages.QueueItem>): Promise<void>
```

Add items to the receiver queue.

Parameters:

- `items` (`Array<cast.framework.messages.QueueItem>`): queue items

Returns: `Promise<void>` - Resolves once the request has been sent.

#### clpp.cast.CastProxy#addMessageListener

```ts
addMessageListener(listener: function)
```

Add a listener for messages from Receiver App.

The message listener is registered under the 'urn:x-cast:castlabs' namespace.

Parameters:

- `listener` (`function`): Callback invoked with each message received from the Receiver App, parsed from JSON if possible.

#### clpp.cast.CastProxy#removeMessageListener

```ts
removeMessageListener(listener: function)
```

Remove a listener for messages from Receiver App.

The message listener is unregistered from the 'urn:x-cast:castlabs' namespace.

Parameters:

- `listener` (`function`): The callback previously passed to `clpp.cast.CastProxy#addMessageListener`.

#### clpp.cast.CastProxy#getContentMetadata

```ts
getContentMetadata(): clpp.cast.utils.SenderMetadataObject | null
```

Gets current Cast content metadata.

Returns: `clpp.cast.utils.SenderMetadataObject | null` - - A Cast metadata object, one of the `chrome.cast.media.*Metadata` objects (See [https://developers.google.com/cast/docs/reference/web_sender/chrome.cast.media#.MetadataType](https://developers.google.com/cast/docs/reference/web_sender/chrome.cast.media#.MetadataType)) or `null` if none is set.

#### clpp.cast.CastProxy#setContentMetadata

```ts
setContentMetadata(metadata: clpp.cast.utils.SenderMetadataObject | null)
```

Sets Cast content metadata.

Set Cast content metadata to one of the `chrome.cast.media.*Metadata` objects (See [https://developers.google.com/cast/docs/reference/web_sender/chrome.cast.media#.MetadataType](https://developers.google.com/cast/docs/reference/web_sender/chrome.cast.media#.MetadataType)), or clear it by passing `null`.

*Note:* You must set content metadata before calling cast/open, otherwise it will have no effect. Correctly setting metadata is crucial for some functionalities, especially for live streams, to work correctly.

Parameters:

- `metadata` (`clpp.cast.utils.SenderMetadataObject | null`): A Cast metadata object, one of the `chrome.cast.media.*Metadata` objects (See [https://developers.google.com/cast/docs/reference/web_sender/chrome.cast.media#.MetadataType](https://developers.google.com/cast/docs/reference/web_sender/chrome.cast.media#.MetadataType)) or `null` to clear the metadata.

#### clpp.cast.CastProxy#clearContentMetadata

```ts
clearContentMetadata()
```

**Deprecated.** Use `setContentMetadata()` (`clpp.cast.CastProxy#setContentMetadata`) instead.

Clear all Cast content metadata.

#### clpp.cast.CastProxy#setContentTitle

```ts
setContentTitle(title: string)
```

**Deprecated.** Use `clpp.cast.CastProxy#setContentMetadata` instead.

Set the Cast content title.

You should set metadata before calling cast/load.

Parameters:

- `title` (`string`): The content title.

#### clpp.cast.CastProxy#setContentImage

```ts
setContentImage(imageUrl: string)
```

**Deprecated.** Use `clpp.cast.CastProxy#setContentMetadata` instead.

Set the Cast content's thumbnail image. You should set metadata before calling cast/load.

Parameters:

- `imageUrl` (`string`): URL of the content's thumbnail image.

#### clpp.cast.CastProxy#setContentArtist

```ts
setContentArtist(artist: string)
```

**Deprecated.** Use `clpp.cast.CastProxy#setContentMetadata` instead.

Set the Cast content's artist. Also sets the metadata type to music track. You should set metadata before calling cast/load.

Parameters:

- `artist` (`string`): The content's artist.

#### clpp.cast.CastProxy#setContentReleaseDate

```ts
setContentReleaseDate(date: string)
```

**Deprecated.** Use `clpp.cast.CastProxy#setContentMetadata` instead.

Set the Cast content's release date. Given string must be compliant with ISO 8601 (YYYY-MM-DD). You should set metadata before calling cast/load.

Parameters:

- `date` (`string`): Release date in ISO 8601 format (YYYY-MM-DD).

## clpp.cast.Queue (class)

Constructor:

```ts
new clpp.cast.Queue()
```

**Experimental:** may change without a major release.

Queue implementation that starts playback from the sender's current state when `queueData` is missing; otherwise playback begins with the first provided `queueData` entry.

## clpp.cast.QueueOptions (typedef)

Queue to load when casting starts, see `clpp.cast.CastProxy#cast`.

Properties:

- `items` (`Array<chrome.cast.media.QueueItem>`): The items of the queue, in playback order.
- `startIndex` (`number`): The index of the item in `items` to start playback with.

## clpp.cast.Receiver (class)

Constructor:

```ts
new clpp.cast.Receiver()
```

Cast Receiver.

It is the main component needed to implement a Chromecast Receiver App. It listens to incoming load requests from a Google Cast Sender over the Google Cast protocol and uses `clpp.Player` to play back the casted stream and execute other commands coming from the sender.

Designed to be used with `clpp.cast.CastProxy` on the sender side.

### Static methods

#### clpp.cast.Receiver.getInstance

```ts
getInstance(): clpp.cast.Receiver
```

Returns the singleton instance of the Cast Receiver.

Returns: `clpp.cast.Receiver` - A singleton instance of the Cast Receiver.

### Methods

#### clpp.cast.Receiver#init

```ts
init(player: clpp.Player)
```

Initializes the receiver. This must be called before calling `start()`.

Parameters:

- `player` (`clpp.Player`): a player instance

#### clpp.cast.Receiver#start

```ts
start(configuration?: clpp.ReceiverConfiguration)
```

Starts listening to commands coming in from the sender.

Parameters:

- `configuration` (`clpp.ReceiverConfiguration`, optional): configuration

#### clpp.cast.Receiver#stop

```ts
stop()
```

Shuts down the Cast Receiver. Stops listening to cast session requests and releases resources.

#### clpp.cast.Receiver#setPlayerConfigInterceptor

```ts
setPlayerConfigInterceptor(interceptor: clpp.cast.utils.PlayerConfigInterceptor | null)
```

Set an interceptor for player configuration.

Gives a possibility to intercept player configuration during casting to modify it if necessary. The interceptor callback takes player config as the argument. The callback should return new configuration in synchronous or asynchronous way. If nothing is returned, the player will use the original config.

Parameters:

- `interceptor` (`clpp.cast.utils.PlayerConfigInterceptor | null`): a callback which takes the player configuration as its argument, or `null` to remove a previously set interceptor.

Example: Generate a new DRM auth token before loading content

```js
receiver.setPlayerConfigInterceptor(async (config) => {
  // use your business logic to obtain new authToken
  const authToken = await getAuthTokenForContent(config);
  config.drm.customData.authToken = authToken;
  return config;
});
```

#### clpp.cast.Receiver#setLoadRequestDataInterceptor

```ts
setLoadRequestDataInterceptor(interceptor: clpp.cast.utils.LoadRequestDataInterceptor | null)
```

Set an interceptor for load request data.

Gives a possibility to intercept [LoadRequestData](https://developers.google.com/cast/docs/reference/web_receiver/cast.framework.messages.LoadRequestData) before passing it to the Chromecast Receiver SDK.

Parameters:

- `interceptor` (`clpp.cast.utils.LoadRequestDataInterceptor | null`): a callback which takes load request data as its argument. It may return modified load request data in synchronous or asynchronous way. If nothing is returned, the player will use the original data.

Example: Add embedded ads to media

```js
receiver.setLoadRequestDataInterceptor((loadRequestData) => {
  const mediaInfo = loadRequestData.media;
  mediaInfo.breakClips = [
    {
      id: 'bc1',
      title: third_party.getBreakClipTitle('bc1'),
      posterUrl: third_party.getBreakClipPosterUrl('bc1'),
      duration: third_party.getBreakClipDuration('bc1')
    },
    {
      id: 'bc2',
      ...
    },
    {
      id: 'bc3',
      ...
    },
    {
      id: 'bc4',
      ...
    }
  ];
  mediaInfo.breaks = [
    {
      id: 'b1',
      breakClipIds: ['bc1', 'bc2'],
      position: 0,
      isEmbedded: true
    },
    {
      id: 'b2',
      breakClipIds: ['bc3', 'bc4'],
      position: 10 * 60,
      isEmbedded: true
    }
  ];

  return loadRequestData;
});
```

#### clpp.cast.Receiver#on

```ts
on(type: cast.framework.system.EventType, handler: function)
```

Add listener to events coming from Chromecast Receiver SDK. Event type should be one of [cast.framework.system.EventType](https://developers.google.com/cast/docs/reference/web_receiver/cast.framework.system#.EventType).

Parameters:

- `type` (`cast.framework.system.EventType`): The event type to listen to.
- `handler` (`function`): Callback invoked with the event.

#### clpp.cast.Receiver#off

```ts
off(type: cast.framework.system.EventType, handler: function)
```

Remove listener to events coming from Chromecast Receiver SDK. Event type should be one of [cast.framework.system.EventType](https://developers.google.com/cast/docs/reference/web_receiver/cast.framework.system#.EventType).

Parameters:

- `type` (`cast.framework.system.EventType`): The event type the handler was registered for.
- `handler` (`function`): The callback previously passed to `clpp.cast.Receiver#on`.

#### clpp.cast.Receiver#addMessageListener

```ts
addMessageListener(listener: function)
```

Add a listener for messages from `clpp.cast.CastProxy`. Add a custom message listener to 'urn:x-cast:castlabs' namespace.

Parameters:

- `listener` (`function`): custom message listener.

#### clpp.cast.Receiver#removeMessageListener

```ts
removeMessageListener(listener: function)
```

Remove a listener for messages from `clpp.cast.CastProxy`.

Remove a custom message listener to 'urn:x-cast:castlabs' namespace.

Parameters:

- `listener` (`function`): custom message listener.

#### clpp.cast.Receiver#sendMessage

```ts
sendMessage(message: unknown, senderId?: string)
```

Send a message to `clpp.cast.CastProxy`.

Send a custom message through 'urn:x-cast:castlabs' namespace.

Parameters:

- `message` (`unknown`): a message object
- `senderId` (`string`, optional): sender ID. If not set, message will be broadcasted to all connected senders.

#### clpp.cast.Receiver#getContentMetadata

```ts
getContentMetadata(): clpp.cast.utils.ReceiverMetadataObject | null
```

Get content metadata.

Get content metadata object set by user, one of the `cast.framework.messages.*MediaMetadata` objects.

Returns: `clpp.cast.utils.ReceiverMetadataObject | null` - The current content metadata, or `null` if none is set.

#### clpp.cast.Receiver#setContentMetadata

```ts
setContentMetadata(metadata: clpp.cast.utils.ReceiverMetadataObject | null)
```

Set content metadata.

Set content metadata object to be displayed on the Cast receiver and broadcast it to all senders. This will overwrite any existing metadata or remove it if `null` is passed.

Parameters:

- `metadata` (`clpp.cast.utils.ReceiverMetadataObject | null`): The metadata to set, or `null` to remove it.

#### clpp.cast.Receiver#updateContentMetadata

```ts
updateContentMetadata(metadata: clpp.cast.utils.ReceiverMetadataObject | null)
```

Update content metadata.

Updates the Cast metadata object with new values. Any existing metadata properties will be updated or replaced with the values provided in the `metadata` object. If the `metadata` object is `null` or not provided, the current metadata will remain unchanged. If no metadata is currently set, and a valid `metadata` object is provided, it will initialize the metadata with the given values.

Parameters:

- `metadata` (`clpp.cast.utils.ReceiverMetadataObject | null`): The metadata properties to merge into the current metadata, or `null` to keep it unchanged.

#### clpp.cast.Receiver#setQueue

```ts
setQueue(queue: cast.framework.QueueBase)
```

Sets the queue instance.

Parameters:

- `queue` (`cast.framework.QueueBase`): queue instance

#### clpp.cast.Receiver#getQueueManager

```ts
getQueueManager(): cast.framework.QueueManager | undefined
```

Gets the queue manager. Returns the Cast queue manager which exposes queue manipulation APIs for the active receiver session.

Returns: `cast.framework.QueueManager | undefined` - The queue manager of the Cast player manager, or `undefined` if not available.

#### clpp.cast.Receiver#isApiReady

```ts
isApiReady(): boolean
```

**Deprecated.**

Checks whether the receiver is ready.

Returns: `boolean` - true after `start()` was called.

## clpp.cast.playlist.CastPlaylist (class)

Constructor:

```ts
new clpp.cast.playlist.CastPlaylist(player: clpp.Player, castAppId: string, playlistItems: Array<clpp.PlaylistItem>)
```

Sender-side playlist utility that keeps a local playlist and cast queue in sync.

Creates a playlist controller bound to the provided player.

Parameters:

- `player` (`clpp.Player`): sender player instance
- `castAppId` (`string`): Chromecast receiver application ID
- `playlistItems` (`Array<clpp.PlaylistItem>`): items to enqueue

Example: Setup Cast playlist.

```js
const player = new clpp.Player('video');
const castPlaylist = new clpp.cast.playlist.CastPlaylist(
  player,
  CHROMECAST_APP_ID,
  [
    {configuration: {source: '...'}, skippable: false },
    {configuration: {source: '...'}, skippable: true },
  ]);

// add listeners
castPlaylist.onPlaylistItemChange(updateUI);
castPlaylist.onPlaylistModified(updateUI);
castPlaylist.onCastStatusChanged(updateUI);

// prepare the playlist
castPlaylist.start();
// play the playback
castPlaylist.play();

// get the playlist information from castPlaylist instance
function updateUI() {
  const playlistItems = castPlaylist.getPlaylistItems();
  const currentIndex = castPlaylist.getCurrentIndex();
  playlistItems.forEach((item, index) => { ... });
}

// call destroy to cleanup to destroy the castPlaylist and
// release the underlying player
function destroyButtonClick() {
  if (castPlaylist.isCasting()) { castPlaylist.toggleCast(); }
  castPlaylist.destroy();
  ...
}
```

### Methods

#### clpp.cast.playlist.CastPlaylist#onPlaylistItemChange

```ts
onPlaylistItemChange(handler: clpp.EventCallback): clpp.EventCallback
```

Registers a handler invoked when the active playlist index changes.

Parameters:

- `handler` (`clpp.EventCallback`): callback invoked with event payload

Returns: `clpp.EventCallback` - The registered callback.

#### clpp.cast.playlist.CastPlaylist#onPlaylistModified

```ts
onPlaylistModified(handler: clpp.EventCallback): clpp.EventCallback
```

Registers a handler invoked when the playlist content is modified.

Parameters:

- `handler` (`clpp.EventCallback`): callback invoked with event payload

Returns: `clpp.EventCallback` - The registered callback.

#### clpp.cast.playlist.CastPlaylist#onCastStatusChanged

```ts
onCastStatusChanged(handler: clpp.EventCallback): clpp.EventCallback
```

Registers a handler for cast availability or connection status changes.

Parameters:

- `handler` (`clpp.EventCallback`): callback invoked with event payload

Returns: `clpp.EventCallback` - The registered callback.

#### clpp.cast.playlist.CastPlaylist#canCast

```ts
canCast(): boolean
```

Returns whether casting is currently active.

Returns: `boolean` - true if cast is available on the sender device.

#### clpp.cast.playlist.CastPlaylist#getPlaylistItems

```ts
getPlaylistItems(): Array<clpp.PlaylistItem>
```

Returns the current local playlist queue.

Returns: `Array<clpp.PlaylistItem>` - The playlist items in playback order.

#### clpp.cast.playlist.CastPlaylist#isCasting

```ts
isCasting(): boolean
```

Returns whether casting is currently active.

Returns: `boolean` - true if a cast session is currently active.

#### clpp.cast.playlist.CastPlaylist#append

```ts
append(item: clpp.PlaylistItem): Promise<void>
```

Appends a new item locally and mirrors it to the cast queue when casting.

Parameters:

- `item` (`clpp.PlaylistItem`): The playlist item to append.

Returns: `Promise<void>` - resolves once the remote queue is updated

#### clpp.cast.playlist.CastPlaylist#getCurrentIndex

```ts
getCurrentIndex(): number
```

Returns the index of the currently active playlist item.

Returns: `number` - Zero-based index of the active item.

#### clpp.cast.playlist.CastPlaylist#start

```ts
start()
```

Starts playlist playback from the current index.

#### clpp.cast.playlist.CastPlaylist#play

```ts
play()
```

Plays the underlying player.

#### clpp.cast.playlist.CastPlaylist#pause

```ts
pause()
```

Pauses playback on the underlying player.

#### clpp.cast.playlist.CastPlaylist#destroy

```ts
destroy()
```

Stops playlist, destroys the current underlying castProxy and releases player.

#### clpp.cast.playlist.CastPlaylist#toggleCast

```ts
toggleCast(): Promise<void>
```

Starts casting with the current queue or disconnects if already casting.

Returns: `Promise<void>` - Resolves once casting has started, or immediately after requesting a disconnect.

#### clpp.cast.playlist.CastPlaylist#next

```ts
next(): Promise<void>
```

Moves to the next playlist item using cast queue when casting.

Returns: `Promise<void>` - Resolves once the move has been requested.

#### clpp.cast.playlist.CastPlaylist#previous

```ts
previous(): Promise<void>
```

Moves to the previous playlist item using cast queue when casting.

Returns: `Promise<void>` - Resolves once the move has been requested.

## clpp.cast.utils.LoadRequestDataInterceptor (callback)

```ts
function(request: cast.framework.messages.LoadRequestData): cast.framework.messages.LoadRequestData | Promise<?cast.framework.messages.LoadRequestData> | null
```

Callback function used to modify load request data before play. Intercepting function shall take `cast.framework.messages.LoadRequestData` as an argument and return modified `cast.framework.messages.LoadRequestData` in synchronous or asynchronous way.

Parameters:

- `request` (`cast.framework.messages.LoadRequestData`)

Returns: `cast.framework.messages.LoadRequestData | Promise<?cast.framework.messages.LoadRequestData> | null`

## clpp.cast.utils.PlayerConfigInterceptor (callback)

```ts
function(config: clpp.PlayerConfiguration): clpp.PlayerConfiguration | Promise<?clpp.PlayerConfiguration> | null
```

Callback function used to modify player config before play. It can be used both on sender and receiver side. Intercepting function shall take `clpp.PlayerConfiguration` as an argument and return modified `clpp.PlayerConfiguration` in synchronous or asynchronous way.

Parameters:

- `config` (`clpp.PlayerConfiguration`)

Returns: `clpp.PlayerConfiguration | Promise<?clpp.PlayerConfiguration> | null`

## clpp.cast.utils.ReceiverMetadataObject (typedef)

Type: `cast.framework.messages.GenericMediaMetadata | cast.framework.messages.MovieMediaMetadata | cast.framework.messages.TvShowMediaMetadata | cast.framework.messages.MusicTrackMediaMetadata | cast.framework.messages.PhotoMediaMetadata | cast.framework.messages.AudiobookChapterMediaMetadata`

Union type helper for describing one of the metadata objects used by Google Cast SDKs. Describes the media content. When used on the Cast Web Receiver the value should be one of the `cast.framework.messages.*MediaMetadata` objects. See:

- [https://developers.google.com/cast/docs/reference/caf_receiver/cast.framework.messages#.MetadataType](https://developers.google.com/cast/docs/reference/caf_receiver/cast.framework.messages#.MetadataType)

Use `clpp.cast.utils.SenderMetadataObject` instead for the Cast Web Sender.

## clpp.cast.utils.SenderMetadataObject (typedef)

Type: `chrome.cast.media.GenericMediaMetadata | chrome.cast.media.MovieMediaMetadata | chrome.cast.media.TvShowMediaMetadata | chrome.cast.media.MusicTrackMediaMetadata | chrome.cast.media.PhotoMediaMetadata | chrome.cast.media.AudiobookChapterMediaMetadata`

Union type helper for describing one of the metadata objects used by Google Cast SDKs. Describes the media content. When used on the Cast Web Sender the value should be one of the `chrome.cast.media.*Metadata` objects. See:

- [https://developers.google.com/cast/docs/reference/web_sender/chrome.cast.media#.MetadataType](https://developers.google.com/cast/docs/reference/web_sender/chrome.cast.media#.MetadataType)

Use `clpp.cast.utils.ReceiverMetadataObject` instead for the Cast Web Receiver.

## clpp.conviva.ConvivaPlugin (class)

Constructor:

```ts
new clpp.conviva.ConvivaPlugin()
```

Conviva plugin.

### Static properties

#### clpp.conviva.ConvivaPlugin.Id

Type: `string`

The ID of the Conviva plugin, e.g. to get the plugin instance with `clpp.Player#getPlugin`.

### Methods

#### clpp.conviva.ConvivaPlugin#reportAppEvent

```ts
reportAppEvent(eventType: string, opt_eventDetail?: Record<string, string>): boolean
```

Report app event. Use this API to report any Global Events associated to application (not associated to playback).

Parameters:

- `eventType` (`string`): The name of the app event, e.g. 'share-click'.
- `opt_eventDetail` (`Record<string, string>`, optional): Optional key-value pairs with details about the event.

Returns: `boolean` - True if event was successfully reported. False otherwise.

Example: Report a custom app event.

```js
const conviva = player.getPlugin(clpp.conviva.ConvivaPlugin.Id);

if (conviva) {
  const eventType = 'share-click';
  const eventDetail = {
    location: 'Toolbar',
    shareService: 'Facebook'
  };

  conviva.reportAppEvent(eventType, eventDetail);
}
```

## clpp.crypto.CryptoComponent (class)

Constructor:

```ts
new clpp.crypto.CryptoComponent()
```

This component adds cryptographic capabilities to the player. It enables the player to support HLS + AES-128 content on other browsers than Safari.

Example:

```js
import "@castlabs/prestoplay/cl.hls";
import "@castlabs/prestoplay/cl.crypto";

// Load a HLS + AES-128 stream
player.open('https://example.com/master.m3u8');
```

## clpp.dash.DashComponent (class)

Constructor:

```ts
new clpp.dash.DashComponent()
```

This component adds the capability to play MPEG-DASH streams.

Example:

```js
import "@castlabs/prestoplay/cl.dash";

// Load a MPEG-DASH stream
player.open('https://example.com/manifest.mpd');
```

## clpp.drm (namespace)

Methods for working with DRM.

### Static methods

#### clpp.drm.registerDrmEnvironment

```ts
registerDrmEnvironment(env: clpp.drm.DrmEnvironment)
```

Register a custom DRM environment.

Parameters:

- `env` (`clpp.drm.DrmEnvironment`): DRM environment.

Example: Register a custom Widevine DRM license server and play content.

```js
const env = new clpp.drm.DrmEnvironment('MyDrm');
env.setDrmSystem(clpp.drm.KeySystem.WIDEVINE, {
  licenseUrl: 'https://example.com/widevine/license',
});
clpp.drm.registerDrmEnvironment(env);

player.open({
  source: 'https://example.com/manifest.mpd',
  drm: {
    env: 'MyDrm',
  },
});
```

## clpp.drm.ContentIdExtractor (callback)

```ts
function(config: clpp.PlayerConfiguration, initData: Uint8Array, context?: clpp.SessionContext): string
```

Callback function that can be used to extract the Fairplay Content ID.

It takes the current `clpp.PlayerConfiguration`, `initData` and a `clpp.SessionContext`. Returns an extracted Content ID string.

This callback needs to be created only if you are using custom DRM environment and your Fairplay server expects different Content ID than that defined in default Apple implementation. If not provided, the default method will be used to extract the Content ID (see `clpp.utils.FairplayUtils.extractContentId`).

For DRMtoday the |SDK| automatically provides an implementation for this callback.

If DRMtoday is a backend then the default implementation returns the content ID as:

```
?assetId=foo&variantId=bar
```

Asset ID and variant ID should be defined in the initData, however they can be also defined in the configuration and in this case have higher precedence than those extracted from initData.

If DRMtoday is not a backend then the default implementation returns the hostname part from HLS `#EXT-X-KEY:URI`.

E.g. if FPS encrypted playlist has the HLS #EXT-X-KEY tag:

```js
#EXT-X-KEY:METHOD=SAMPLE-AES,URI="skd://d192ebad-5097",
KEYFORMAT="com.apple.streamingkeydelivery",KEYFORMATVERSIONS="1"
```

then the Content ID will be:

```
d192ebad-5097
```

You can also use `customData` object in the `clpp.SessionContext` to pass some additional data to license request/response modifiers if needed.

Parameters:

- `config` (`clpp.PlayerConfiguration`): The current player configuration.
- `initData` (`Uint8Array`): The FairPlay init data from the `encrypted` event.
- `context` (`clpp.SessionContext`, optional): The session context shared between the requests and responses of a media session.

Returns: `string` - The extracted Content ID.

Example: Implement a custom FairPlay callback for extracting Content ID

```js
const extractContentId = function (config, initData) {
   const { extractContentId } = clpp.utils.FairplayUtils;
   const fullHostname = extractContentId(initData); // d192ebad-5097
   return fullHostname.split("-")[0]; // d192ebad
};
```

## clpp.drm.DrmEnvironment (class)

Constructor:

```ts
new clpp.drm.DrmEnvironment(name: string)
```

DRM environment is as a set of DRM system configurations (Widevine, Fairplay, PlayReady) for a specific DRM provider such as DRMtoday.

Built-in environments are: 'DRMtoday', 'DRMtoday_STAGING' and 'HeaderDrm'.

Import module `cl.onboard` in order to enable the 'DRMtodayOnboard' environment.

Import module `cl.verimatrix` in order to enable the 'VerimatrixVCAS' environment.

To register a custom DRM environment call `registerDrmEnvironment()` (`clpp.drm.registerDrmEnvironment`).

Pass the `drm.env` (`clpp.DrmConfiguration#env`) option to `open()` (`clpp.Player#open`) to select a DRM environment to use for decryption of content.

Parameters:

- `name` (`string`): DRM environment name.

### Methods

#### clpp.drm.DrmEnvironment#setDrmSystem

```ts
setDrmSystem(identifier: clpp.drm.KeySystem, config: clpp.PlayreadyDrmSystem | clpp.FairplayDrmSystem | clpp.WidevineDrmSystem)
```

Set the default configuration for a given DRM system.

Parameters:

- `identifier` (`clpp.drm.KeySystem`): DRM system identifier.
- `config` (`clpp.PlayreadyDrmSystem | clpp.FairplayDrmSystem | clpp.WidevineDrmSystem`): DRM system configuration.

## clpp.drm.DrmRequestModifier (callback)

```ts
function(config: clpp.PlayerConfiguration, request: clpp.net.Request, context?: clpp.SessionContext): Promise<clpp.net.Request> | void
```

A callback to modify DRM requests before they are sent to the DRM license server.

To modify responses instead use `DrmResponseModifier` (`clpp.drm.DrmResponseModifier`).

Use it to modify the properties of the request and use context to pass additional data to the corresponding `DrmResponseModifier` (`clpp.drm.DrmResponseModifier`).

If it returns a promise the promise will be awaited before executing continues.

Parameters:

- `config` (`clpp.PlayerConfiguration`): The current player configuration.
- `request` (`clpp.net.Request`): The license or certificate request that is about to be sent. It can be modified in place.
- `context` (`clpp.SessionContext`, optional): The session context shared between the requests and responses of a media session.

Returns: `Promise<clpp.net.Request> | void` - Nothing or a promise that resolves with the modified request.

## clpp.drm.DrmResponseModifier (callback)

```ts
function(config: clpp.PlayerConfiguration, response: clpp.net.Response, context?: clpp.SessionContext): Promise<any> | void
```

A callback to modify DRM responses after they are received to the DRM license server.

To modify requests instead use `DrmRequestModifier` (`clpp.drm.DrmRequestModifier`).

Use it to modify the properties of the responses and use context to receive additional data from the corresponding `DrmRequestModifier` (`clpp.drm.DrmRequestModifier`).

If it returns a promise the promise will be awaited before executing continues.

Parameters:

- `config` (`clpp.PlayerConfiguration`): The current player configuration.
- `response` (`clpp.net.Response`): The license or certificate response received from the server. It can be modified in place, e.g. to extract the license data.
- `context` (`clpp.SessionContext`, optional): The session context shared between the requests and responses of a media session.

Returns: `Promise<any> | void` - Nothing, or a promise that resolves once processing of the response is done.

## clpp.drm.DrmToday (namespace)

Enums for DRMtoday.

## clpp.drm.DrmToday.WidevineCertificates (enum)

DRMtoday Widevine Server Certificates.

Use these constants to specify a specific DRMtoday Widevine Server Certificate to be used.

Values:

- `V1_PROD` = `V1_PROD`: Certificate version 1 for the production environment.
- `V1_STAGING` = `V1_STAGING`: Certificate version 1 for the staging environment.
- `V2` = `V2`: Certificate version 2, the latest version for both production and staging environment.

## clpp.drm.HeaderDrm (class)

Constructor:

```ts
new clpp.drm.HeaderDrm(wvLicenseUrl: string, prLicenseUrl: string, fpLicenseUrl: string, fpCertificateUrl: string, fpContentIdStrategy: clpp.drm.HeaderDrm.FairPlayContentIdStrategy)
```

A DRM environment for license servers that authorize requests by HTTP headers, e.g. an auth token.

It sends the headers from `drm.customData.headers` with every license and certificate request, for Widevine, PlayReady and FairPlay.

In most cases `clpp.drm.HeaderDrmComponent` is all you need: it creates and registers the environment from the player configuration. Create one yourself only to change its behavior, e.g. by overriding one of its methods in a subclass.

To leave out a DRM system, pass an empty string as its license URL. The environment then supports only the other DRM systems.

Parameters:

- `wvLicenseUrl` (`string`): The Widevine license server URL.
- `prLicenseUrl` (`string`): The PlayReady license server URL.
- `fpLicenseUrl` (`string`): The FairPlay license server URL.
- `fpCertificateUrl` (`string`): The FairPlay certificate URL. FairPlay is left out without it.
- `fpContentIdStrategy` (`clpp.drm.HeaderDrm.FairPlayContentIdStrategy`): How to derive the FairPlay content ID from the SKD URL.

Example: Register the environment and pass an auth header.

```js
const drmEnv = new clpp.drm.HeaderDrm(
  'https://example.com/widevine/license',
  'https://example.com/playready/license',
  'https://example.com/fairplay/license',
  'https://example.com/fairplay/certificate',
  clpp.drm.HeaderDrm.FairPlayContentIdStrategy.HOSTNAME,
);
clpp.drm.registerDrmEnvironment(drmEnv);

player.open({
  source: 'https://example.com/manifest.mpd',
  drm: {
    env: clpp.drm.HeaderDrm.NAME,
    customData: {
      headers: {
        'my-auth-header': 'foobar',
      },
    },
  },
});
```

### Static properties

#### clpp.drm.HeaderDrm.NAME

Type: `string`

The name under which `clpp.drm.HeaderDrm` DRM environment is registered. Set it as `drm.env` (`clpp.DrmConfiguration#env`) to play content with it.

### Methods

#### clpp.drm.HeaderDrm#onLicenseRequest

```ts
onLicenseRequest(playerConfig: clpp.PlayerConfiguration, request: clpp.net.Request)
```

Adds the headers from `drm.customData.headers` to a license or certificate request.

Parameters:

- `playerConfig` (`clpp.PlayerConfiguration`): The player configuration.
- `request` (`clpp.net.Request`): The request, changed in place.

#### clpp.drm.HeaderDrm#extractFairPlayContentId

```ts
extractFairPlayContentId(playerConfig: clpp.PlayerConfiguration, initData: Uint8Array): string
```

Derives the FairPlay content ID from the SKD URL in the init data, as the `clpp.drm.HeaderDrm.FairPlayContentIdStrategy` given to the constructor says.

Override it if your content IDs are derived differently.

Parameters:

- `playerConfig` (`clpp.PlayerConfiguration`): The player configuration.
- `initData` (`Uint8Array`): The FairPlay init data, which holds the SKD URL.

Returns: `string` - The content ID.

Throws:

- `clpp.Error` if the content ID strategy is unknown

#### clpp.drm.HeaderDrm#onFairPlayLicenseRequest

```ts
onFairPlayLicenseRequest(playerConfig: clpp.PlayerConfiguration, request: clpp.net.Request)
```

Prepares a FairPlay license request: adds the headers from `drm.customData.headers` and sends the SPC (the license challenge) as the form field `spc`, Base64 encoded.

Parameters:

- `playerConfig` (`clpp.PlayerConfiguration`): The player configuration.
- `request` (`clpp.net.Request`): The request, changed in place.

#### clpp.drm.HeaderDrm#onFairPlayLicenseResponse

```ts
onFairPlayLicenseResponse(playerConfig: clpp.PlayerConfiguration, response: clpp.net.Response)
```

Turns a FairPlay license response into the CKC (the license) for the CDM: Base64 decodes it, after removing the `<ckc>` and `</ckc>` tags around it if there are any.

Parameters:

- `playerConfig` (`clpp.PlayerConfiguration`): The player configuration.
- `response` (`clpp.net.Response`): The response, changed in place.

## clpp.drm.HeaderDrm.FairPlayContentIdStrategy (enum)

How `clpp.drm.HeaderDrm` derives the FairPlay content ID from the SKD URL of the HLS `#EXT-X-KEY` tag, e.g. `skd://my-content-id`.

Values:

- `HOSTNAME` = `hostname`: Use the host part of the SKD URL, e.g. `my-content-id`.
- `FULL_SKD` = `full-skd`: Use the whole SKD URL, e.g. `skd://my-content-id`.

## clpp.drm.HeaderDrmComponent (class)

Constructor:

```ts
new clpp.drm.HeaderDrmComponent()
```

A convenient wrapper around `clpp.drm.HeaderDrm`.

The component initializes the header-based DRM based on the given player configuration.

Example:

```js
// Select the header based DRM and pass server URLs and custom headers.
player.open({
  ...
  drm: {
    env: clpp.drm.HeaderDrm.NAME,
    customData: {
      widevineLicenseUrl: '...',
      widevineVideoRobustness: [
        clpp.drm.WidevineRobustnessLevel.SW_SECURE_DECODE,
        undefined
      ],
      widevineAudioRobustness: [
        clpp.drm.WidevineRobustnessLevel.SW_SECURE_CRYPTO,
        undefined
      ],
      playReadyLicenseUrl: '...',
      playReadyVideoRobustness: [
        clpp.drm.PlayreadyRobustnessLevel.SL3000
      ],
      playReadyAudioRobustness: [
        clpp.drm.PlayreadyRobustnessLevel.SL2000
      ],
      serverCertificate: new Uint8Array([...]),
      fairPlayLicenseUrl: '...',
      fairPlayCertificateUrl: '...',
      fairPlayContentIdStrategy:
        clpp.drm.HeaderDrm.ContentIdStrategy.FULL_SKD,
      headers: {
        'my-auth-header': 'foobar'
        ...
      }
    }
  }
});
```

## clpp.drm.InitDataTransformer (callback)

```ts
function(params: clpp.InitDataTransformerParams): Uint8Array
```

A function that accepts one parameter of type `clpp.InitDataTransformerParams` which provides:

- initData and initDataType from `encrypted` event;
- the current player configuration (`clpp.PlayerConfiguration`);
- the current DRM system configuration (`clpp.FairplayDrmSystem`|`clpp.PlayreadyDrmSystem`| `clpp.WidevineDrmSystem`);
- the current DRM info (`clpp.DrmInfo`);
- the current session context (`clpp.SessionContext`) which could be used to get and store some customData for later use within licenseRequest and/or licenseResponse modifiers.

It should return valid initData of type `Uint8Array` to pass to the currently used CDM to generate a license request.

Parameters:

- `params` (`clpp.InitDataTransformerParams`): The init data and the context it was encountered in.

Returns: `Uint8Array` - The init data to pass to the CDM.

Example: Custom FairPlay InitDataTransformer

```js
transformInitData: function ({
 initData,
 initDataType,
 drmInfo: { serverCertificate },
 sessionContext: { customData },
}) {
  if (initDataType === 'skd') {
    const { extractContentId, createFairplayPayload } =
      clpp.utils.FairplayUtils;
    customData.keyId = extractContentId(initData);
    const contentId = videoConfig.pid; // e.g. ID fetched from a custom API
    initData = createFairplayPayload(initData, contentId, serverCertificate);
  }
  return initData;
}
```

## clpp.drm.KeySystem (enum)

Key system identifiers for various DRM systems.

Values:

- `NONE` = `none`: Placeholder for empty / unspecified key system
- `CLEAR_KEY` = `org.w3.clearkey`: DRM Key system identifier for Clear Key
- `WIDEVINE` = `com.widevine.alpha`: DRM Key system identifier for Widevine
- `PLAYREADY` = `com.microsoft.playready`: DRM Key system identifier for Playready
- `FAIRPLAY` = `com.apple.fps`: DRM Key system identifier for Fairplay
- `PRIMETIME` = `com.adobe.primetime`: DRM Key system identifier for Primetime

## clpp.drm.LicenseModifiers (typedef)

A set of modifier functions that can be added to the DRM system.

Properties:

- `extractContentId` (`clpp.drm.ContentIdExtractor`, optional): A callback function that will be triggered to extract the Content ID. *(only used with Fairplay DRM)*
- `licenseRequest` (`clpp.drm.DrmRequestModifier`, optional): A callback function that will be triggered before the request.
- `licenseResponse` (`clpp.drm.DrmResponseModifier`, optional): A callback function that will be triggered with the response.
- `certificateRequest` (`clpp.drm.DrmRequestModifier`, optional): A callback function that will be triggered to prepare the certificate request.
- `certificateResponse` (`clpp.drm.DrmResponseModifier`, optional): A callback function that will be triggered to interpret the certificate response.
- `transformInitData` (`clpp.drm.InitDataTransformer`, optional): A callback function that will be triggered to transform init data from the manifest/media before it is passed to the browser's CDM.

## clpp.drm.PlayreadyRobustnessLevel (enum)

Robustness levels used for Playready DRM.

Values:

- `SL150` = `150`: For clients under development or under test. Not suitable for commercial content in a commercial scenario.
- `SL2000` = `2000`: Software security level.
- `SL3000` = `3000`: Hardware security level.

## clpp.drm.WidevineRobustnessLevel (enum)

Robustness levels used for Widevine DRM.

Values:

- `SW_SECURE_CRYPTO` = `SW_SECURE_CRYPTO`: EME Level 1, Widevine Level 3
- `SW_SECURE_DECODE` = `SW_SECURE_DECODE`: EME Level 2, Widevine Level 3
- `HW_SECURE_CRYPTO` = `HW_SECURE_CRYPTO`: EME Level 3, Widevine Level 2
- `HW_SECURE_DECODE` = `HW_SECURE_DECODE`: EME Level 4, Widevine Level 1
- `HW_SECURE_ALL` = `HW_SECURE_ALL`: EME Level 5, Widevine Level 1

## clpp.drm.eme.EmeFactory (namespace)

Enums for Encrypted Media Extensions (EME).

## clpp.drm.eme.EmeFactory.Apis (enum)

Versions of Encrypted Media Extensions (EME) API.

Values:

- `STANDARD` = `STANDARD`: Standard EME. Used by default on all platforms where it is available.
- `APPLE` = `APPLE`: Apple-prefixed EME.
- `WEBKIT` = `WEBKIT`: EME manager built on version v0.1b of EME standard. Typically used on older smart TV devices where there is no alternative.
- `NOP` = `NOP`: Internal dummy implementation of the EME API. Please do not use this.

## clpp.events.BitrateChangeDetails (typedef)

A container that holds information about a bitrate change event. The object is send with `BITRATE_CHANGED` (`clpp.events#BITRATE_CHANGED`) events.

Properties:

- `width` (`number`): The width in pixel of the currently playing video rendition.
- `height` (`number`): The height in pixel of the currently playing video rendition.
- `bandwidth` (`number | null`): The bandwidth (in bps) of the currently playing rendition. Note that this information might not always be available.
- `rendition` (`clpp.Rendition | null`): The video rendition if one could be found.

## clpp.events.BufferingDetails (typedef)

Container object that contains meta-data for a buffering event. The object is send with `BUFFERING_STARTED` (`clpp.events.BUFFERING_STARTED`) and `BUFFERING_ENDED` (`clpp.events.BUFFERING_ENDED`) events.

Properties:

- `bufferedTimeMS` (`number`): The time in milliseconds the player spent in buffering state or -1 in case of BUFFERING_STARTED events
- `reason` (`number`): One of the `BufferingReasons` (`clpp.events.BufferingReasons`) constants that indicate the reason for the buffering event

## clpp.events.BufferingReasons (enum)

Constants that express the reason why the player transitioned in to the `BUFFERING` (`clpp.Player.State#BUFFERING`) state.

Values:

- `SEEKING` = `1`: The player is buffering because of a seek event
- `NO_DATA` = `2`: The player is buffering because not enough data is available

## clpp.events.CmsdDynamic (typedef)

CMSD Dynamic values. Keys whose values apply only to the next transmission hop. Typically a new CMSD-Dynamic header instance will be added by each intermediary participating in the delivery.

Properties:

- `duress` (`boolean`, optional): Key is included without a value if the server is under duress, due to cpu, memory, disk IO, network IO or other reasons. *Header-Key: du*
- `estimatedThroughputKbps` (`number`, optional): The throughput between the server and the client over the currently negotiated transport as estimated by the server  at the start of the response. The value is expressed in units of kilobits per second. *Header-Key: etp*
- `maxSuggestedBitrateKbps` (`number`, optional): The maximum bitrate value that the player SHOULD play in its Adaptive Bit Rate (ABR) ladder. *Header-Key: mb*
- `responseDelay` (`number`, optional): The time in milliseconds elapsed between the receipt of the request and when the first byte of the body becomes available to send to the client. *Header-Key: rd*
- `roundTripTime` (`number`, optional): Estimated round trip time in milliseconds between client and server. This estimate may be derived from the transport handshake. *Header-Key: rtt*

## clpp.events.CmsdStatic (typedef)

CMSD Static values. Keys whose values persist over multiple requests for the object.

Properties:

- `availabilityTime` (`number`, optional): The wallclock time at which the first byte of this object became available at the origin for successful request. The time is expressed as integer milliseconds since the Unix Epoch. *Header-Key: at*
- `encodedBitrateKbps` (`number`, optional): The encoded bitrate of the audio or video object being requested. *Header-Key: br*
- `heldTime` (`number`, optional): The number of milliseconds that this response was held back by an origin before returning. *Header-Key: ht*
- `intermediaryIdentifier` (`string`, optional): An identifier for the processing server. *Header-Key: n*
- `nextObjectResponse` (`string`, optional): The URL-encoded relative path to one or more objects which can reasonably be expected to be requested by a client. *Header-Key: nor*
- `nextRangeResponse` (`string`, optional): If the next response will be a partial object response, then this string denotes the byte range that will be returned. *Header-Key: nrr*
- `objectDuration` (`number`, optional): The playback duration in milliseconds of the object. *Header-Key: d*
- `objectType` (`string`, optional): The media role of the current object being returned: m = text file, such as a manifest or playlist a = audio only v = video only av = muxed audio and video i = init segment c = caption or subtitle tt = ISOBMFF timed text track k = cryptographic key, license or certificate. o = other *Header-Key: ot*
- `startup` (`boolean`, optional): It should approximate the starting buffer of the intended players. *Header-Key: su*
- `streamingFormat` (`string`, optional): The streaming format that defines the current response. d = MPEG DASH h = HTTP Live Streaming (HLS) s = Smooth Streaming o = other *Header-Key: sf*
- `streamType` (`string`, optional): v = all segments are available – e.g., VoD. l = segments become available over time – e.g., live. *Header-Key: st*
- `version` (`number`, optional): The version of this specification used for interpreting the defined key names and values. *Header-Key: v*

## clpp.events.PlayerStateChangeDetails (typedef)

Container object that is sent with `PLAYER_STATE_CHANGED` (`clpp.events#PLAYER_STATE_CHANGED`) events.

Properties:

- `currentState` (`clpp.PlayerState`): The current internal player state.
- `previousState` (`clpp.PlayerState`): The previous internal player state.
- `observableState` (`clpp.PlayerState`, optional): The observable player state for compatibility listeners.
- `previousObservableState` (`clpp.PlayerState`, optional): The previous observable player state.
- `timeSinceLastStateChangeMS` (`number`): The time since the last state change event.
- `timeSinceLastObservableStateChangeMS` (`number`, optional): The time since the last observable state change event.
- `reason` (`number`, optional): Optional reason for the state transition. This is set for transitions into the BUFFERING state, in which case the value is one of `BufferingReasons` (`clpp.events.BufferingReasons`).

## clpp.events.StateChangeDetails (typedef)

Container object that is send with state change events.

Properties:

- `currentState` (`clpp.Player.State`): The current player state.
- `previousState` (`clpp.Player.State`): The previous player state.
- `timeSinceLastStateChangeMS` (`number`): The time since the last state change event.
- `reason` (`number`, optional): Optional reason for the state transition. This is set for transitions into the BUFFERING state, in which case the value is one of `BufferingReasons` (`clpp.events.BufferingReasons`).

## clpp.events.VideoTrackChangeDetails (typedef)

Container object that covers video track changed and information about the currently selected.

The object is send with `VIDEO_TRACK_CHANGED` (`clpp.events#VIDEO_TRACK_CHANGED`) events.

Properties:

- `width` (`number`): The width in pixel of the currently playing video rendition.
- `height` (`number`): The height in pixel of the currently playing video rendition.
- `bandwidth` (`number | null`): The bandwidth (in bps) of the currently playing rendition. Note that this information might not always be available.
- `track` (`clpp.Track`): The vide track if one could be found for the currently playing rendition.
- `abrSelection` (`boolean`): True if the track change was triggered by the ABR algorithm, false for manual track selections.

## clpp.freewheel.FreeWheelPlugin (class)

Constructor:

```ts
new clpp.freewheel.FreeWheelPlugin()
```

FreeWheel plugin for CSAI.

### Static properties

#### clpp.freewheel.FreeWheelPlugin.Id

Type: `string`

FreeWheel plugin ID.

#### clpp.freewheel.FreeWheelPlugin.AD_CONTAINER_ID

Type: `string`

ID of the ad container.

### Methods

#### clpp.freewheel.FreeWheelPlugin#getAdContainer

```ts
getAdContainer(): Element | null
```

Gets the ad container.

Returns: `Element | null` - The element that holds the ad video, or null if the FreeWheel SDK is missing or the player was destroyed.

#### clpp.freewheel.FreeWheelPlugin#getAdVideo

```ts
getAdVideo(): HTMLVideoElement | null
```

Gets the video element from the ad container.

Returns: `HTMLVideoElement | null` - The video element that plays the ads, or null if the FreeWheel SDK is missing or the player was destroyed.

## clpp.hls.HlsComponent (class)

Constructor:

```ts
new clpp.hls.HlsComponent()
```

This component adds the capability to play HTTP Live Streaming (HLS) streams.

Example:

```js
import "@castlabs/prestoplay/cl.hls";

// Load a HLS playlist
player.open('https://example.com/master.m3u8');
```

## clpp.htmlcue.HtmlCueComponent (class)

Constructor:

```ts
new clpp.htmlcue.HtmlCueComponent()
```

This component adds the capability to display text tracks on the HTML overlay. Its most important features include very good WebVTT support and rich styling capabilities.

Example:

```js
import "@castlabs/prestoplay/cl.htmlcue";

// Load a stream with text tracks
player.open('https://example.com/Manifest.mpd');
```

## clpp.ima.ImaPlugin (class)

Constructor:

```ts
new clpp.ima.ImaPlugin()
```

IMA SDK Plugin for ad insertion.

### Static properties

#### clpp.ima.ImaPlugin.Id

Type: `string`

The ID of the IMA plugin, e.g. to get the plugin instance with `getPlugin()` (`clpp.Player#getPlugin`).

### Static methods

#### clpp.ima.ImaPlugin.isSdkMissing

```ts
isSdkMissing(): boolean
```

Check if Client Side IMA SDK is available.

Returns: `boolean` - True if IMA SDK is missing.

### Methods

#### clpp.ima.ImaPlugin#getAdsLoader

```ts
getAdsLoader(): google.ima.AdsLoader | null
```

Returns the instance of the ads loader. See [google.ima.AdsLoader](https://developers.google.com/interactive-media-ads/docs/sdks/html5/client-side/reference/js/google.ima.AdsLoader).

Returns: `google.ima.AdsLoader | null` - The ads loader.

#### clpp.ima.ImaPlugin#getAdDisplayContainer

```ts
getAdDisplayContainer(): google.ima.AdDisplayContainer | null
```

Returns the instance of the ad display container. See [google.ima.AdDisplayContainer](https://developers.google.com/interactive-media-ads/docs/sdks/html5/client-side/reference/js/google.ima.AdDisplayContainer).

Returns: `google.ima.AdDisplayContainer | null` - The ad display container.

#### clpp.ima.ImaPlugin#getAdContainer

```ts
getAdContainer(): Element | null
```

Returns the instance of the ad container.

Returns: `Element | null` - The ad display container.

## clpp.interstitial.Asset (typedef)

An interstitial asset.

Properties:

- `URI` (`string`): URI of the asset.
- `DURATION` (`number`): Duration of the asset.
- `X-AD-CREATIVE-SIGNALING` (`Object`, optional): SVTA signaling metadata for the ad.

## clpp.interstitial.AssetListResponse (typedef)

Response to the request for the asset list (X-ASSET-LIST) as defined in the HLS spec.

Properties:

- `ASSETS` (`Array<clpp.interstitial.Asset>`): A list of assets.
- `X-AD-CREATIVE-SIGNALING` (`Object`, optional): SVTA signaling metadata for the ad pod.

## clpp.log (namespace)

The logger class and log methods. Create tagged loggers or use the global logger, set log level or configure log message interceptors.

### Static methods

#### clpp.log.getLoggers

```ts
getLoggers(): Record<string, clpp.log.Level> | Record<string, clpp.log.Level>
```

Get a map of all log tags to their configured log level.

Returns: `Record<string, clpp.log.Level>` - A map from logger tag to its log level.

`Record<string, clpp.log.Level>` - a map of log tags to log levels

#### clpp.log.addInterceptor

```ts
addInterceptor(interceptor: clpp.log.LogInterceptor)
```

Add a log interceptor to intercept all log messages from all loggers.

Parameters:

- `interceptor` (`clpp.log.LogInterceptor`): A function called with the log level and the messages of every log call.

#### clpp.log.removeInterceptor

```ts
removeInterceptor(interceptor: clpp.log.LogInterceptor)
```

Remove a log interceptor.

Parameters:

- `interceptor` (`clpp.log.LogInterceptor`): The interceptor previously passed to `addInterceptor()` (`clpp.log.addInterceptor`).

#### clpp.log.getTagLevel

```ts
getTagLevel(tag?: string): clpp.log.Level
```

Takes a logger instance and will return its local log level according to the logger registry. If no local level is found, the global level will be returned.

Parameters:

- `tag` (`string`, optional): The tag

Returns: `clpp.log.Level` - - The log level that should be used by this logger

#### clpp.log.hasTagLevel

```ts
hasTagLevel(tag?: string): boolean
```

Checks whether a custom log level was set for the given tag.

Parameters:

- `tag` (`string`, optional): The tag

Returns: `boolean` - True if the given tag has a custom level

#### clpp.log.setTagLevel

```ts
setTagLevel(tag: string, level: clpp.log.Level | string)
```

Sets the log level for the given tag.

Tag levels support hierarchies using dot notation. For example, you can set a log level for 'my.tag', which will control levels for all tags that start with 'my.tag' unless they also have a custom level entry.

Parameters:

- `tag` (`string`): The tag
- `level` (`clpp.log.Level | string`): The log level or -1 to disable any custom tag level

Example: Set log level to DEBUG for a specific log tag.

```js
clpp.log.setTagLevel('clpp.player', clpp.log.Level.DEBUG);
```

Example: Unset log level to use default log level.

```js
clpp.log.setTagLevel('clpp.player', clpp.log.Level.DEFAULT);
```

#### clpp.log.setLogLevel

```ts
setLogLevel(level: clpp.log.Level | string)
```

Set the default log level. All loggers will use this log level unless overridden by `setTagLevel()` (`clpp.log#setTagLevel`).

Parameters:

- `level` (`clpp.log.Level | string`): The global log level

Example: Set the default log level to INFO.

```js
clpp.log.setLogLevel(clpp.log.Level.INFO);
```

Example: Disable logs by default by setting level NONE.

```js
clpp.log.setLogLevel(clpp.log.Level.NONE);
```

#### clpp.log.getLogLevel

```ts
getLogLevel(): clpp.log.Level
```

Get the global log level.

Returns: `clpp.log.Level` - The global log level.

#### clpp.log.info

```ts
info(...messages: Array<unknown>)
```

Log info messages using the global logger.

Parameters:

- `...messages` (`Array<unknown>`): The message(s) that will be logged to console.

#### clpp.log.debug

```ts
debug(...messages: Array<unknown>)
```

Log debug messages using the global logger.

Parameters:

- `...messages` (`Array<unknown>`): The message(s) that will be logged to console.

#### clpp.log.warn

```ts
warn(...messages: Array<unknown>)
```

Log warning messages using the global logger.

Parameters:

- `...messages` (`Array<unknown>`): The message(s) that will be logged to console.

Example: Log warning with the global logger.

```js
clpp.log.warn('This is a warning!');
```

#### clpp.log.error

```ts
error(...messages: Array<unknown>)
```

Log error messages using the global logger.

Parameters:

- `...messages` (`Array<unknown>`): The message(s) that will be logged to console.

Example: Log error with the global logger.

```js
clpp.log.error('Something went wrong!');
```

## clpp.log.Level (enum)

Log level.

Values:

- `DEFAULT` = `-1`: Used for tag loggers to make them use the global log level.
- `NONE` = `0`: All logging will be disabled.
- `ERROR` = `1`: Only errors will be logged.
- `WARNING` = `2`: Errors and Warnings will be logged.
- `INFO` = `3`: Errors, Warnings and Info messages will be logged.
- `DEBUG` = `4`: All logging messages will be permitted and logged.

## clpp.log.LogInterceptor (callback)

```ts
function(level: clpp.log.Level, messages: Array<unknown>)
```

Log interceptor callback.

Parameters:

- `level` (`clpp.log.Level`): log level
- `messages` (`Array<unknown>`): logged messages

## clpp.log.Logger (class)

Constructor:

```ts
new clpp.log.Logger(tag?: string)
```

A logger that can be used by modules to log messages. The logger can contain a tag which will be used to prefix all log message.

Besides the tag, the loggers log level can be configured independently of the global log level.

Parameters:

- `tag` (`string`, optional): The optional tag. Tags should follow package names and use '.' to separate components. This will allow you to control the log levels of modules and components globally

### Methods

#### clpp.log.Logger#log

```ts
log(level: clpp.log.Level, messages: Array<unknown>)
```

Log a message at a specific log level.

Parameters:

- `level` (`clpp.log.Level`): The log level of the message. If not specified, `clpp.log.Level.INFO` will be used
- `messages` (`Array<unknown>`): The message(s) that will be logged to console.

#### clpp.log.Logger#info

```ts
info(...messages: Array<unknown>)
```

Log info messages.

Parameters:

- `...messages` (`Array<unknown>`): The message(s) that will be logged to console.

#### clpp.log.Logger#debug

```ts
debug(...messages: Array<unknown>)
```

Log debug messages.

Parameters:

- `...messages` (`Array<unknown>`): The message(s) that will be logged to console.

#### clpp.log.Logger#warn

```ts
warn(...messages: Array<unknown>)
```

Log warning messages.

Parameters:

- `...messages` (`Array<unknown>`): The message(s) that will be logged to console.

#### clpp.log.Logger#error

```ts
error(...messages: Array<unknown>)
```

Log error messages.

Parameters:

- `...messages` (`Array<unknown>`): The message(s) that will be logged to console.

#### clpp.log.Logger#createChild

```ts
createChild(tag?: string): clpp.log.Logger
```

Returns a child logger the will extend this logger's tag.

Parameters:

- `tag` (`string`, optional): The logger tag extension

Returns: `clpp.log.Logger` - The new child logger

## clpp.media.Timeline (class)

A windowed timeline.

This is an abstraction, the timeline consists of one or multiple windows where each window can represent for instance one asset in a playlist.

### Methods

#### clpp.media.Timeline#getWindow

```ts
getWindow(index: number): clpp.media.TimelineWindow | null
```

Get a window of the timeline at the given index.

Parameters:

- `index` (`number`): The zero-based index of the window.

Returns: `clpp.media.TimelineWindow | null` - a window at the given index or null

Example: Get timeline window at index.

```js
const timelineWindow = timeline.getWindow(0);
```

#### clpp.media.Timeline#getWindowCount

```ts
getWindowCount(): number
```

Get the number of windows in the timeline.

Returns: `number` - the count of windows in the timeline

Example: Get the number of timeline windows.

```js
const count = timeline.getWindowCount(); // 4
```

#### clpp.media.Timeline#getWindows

```ts
getWindows(): Array<clpp.media.TimelineWindow>
```

Get all the windows of the timeline.

Returns: `Array<clpp.media.TimelineWindow>` - all windows of the timeline

Example: Get all timeline windows.

```js
const windows = timeline.getWindows(); // [...]
```

#### clpp.media.Timeline#getCurrentWindow

```ts
getCurrentWindow(): clpp.media.TimelineWindow | null
```

Get the currently active window of the timeline.

Returns: `clpp.media.TimelineWindow | null` - the active window or null

Example: Get the current timeline window.

```js
const timelineWindow = timeline.getCurrentWindow();
```

#### clpp.media.Timeline#getCurrentWindowIndex

```ts
getCurrentWindowIndex(): number
```

Get the index of the currently active window of the timeline.

Returns: `number` - the index of the active window

Example: Get the index of the current timeline window.

```js
const index = timeline.getCurrentWindowIndex(); // 0
```

## clpp.media.TimelineWindow (class)

A timeline window.

### Methods

#### clpp.media.TimelineWindow#getDuration

```ts
getDuration(): number
```

Get the duration of the timeline window.

Returns: `number` - the duration of the window in seconds

Example: Get the duration.

```js
const duration = timelineWindow.getDuration(); // 600
```

#### clpp.media.TimelineWindow#getId

```ts
getId(): string
```

Get the ID of the timeline window.

Returns: `string` - the ID of the window

Example: Get the ID.

```js
const id = timelineWindow.getId(); // "asset1"
```

#### clpp.media.TimelineWindow#getStart

```ts
getStart(): number
```

Get the start time of the timeline window.

Returns: `number` - the start of the window in seconds

Example: Get the start of the window.

```js
const startTime = timelineWindow.getStart(); // 400
```

#### clpp.media.TimelineWindow#isDynamic

```ts
isDynamic(): boolean
```

Check whether the timeline window is static or dynamic.

Returns: `boolean` - true if the duration of this windows is dynamic and can change

Example: Check if the window is dynamic.

```js
const dynamic = timelineWindow.isDynamic(); // false
```

## clpp.muxdata.MuxDataPlugin (class)

Constructor:

```ts
new clpp.muxdata.MuxDataPlugin()
```

Mux Data Analytics plugin.

### Static properties

#### clpp.muxdata.MuxDataPlugin.Id

Type: `string`

The ID of the Mux Data plugin, e.g. to get the plugin instance with `getPlugin()` (`clpp.Player#getPlugin`).

### Methods

#### clpp.muxdata.MuxDataPlugin#emit

```ts
emit(eventType: string, data: Object)
```

Emit a custom event. This method can be used to send supplementary events to Mux, in addition to the mandatory playback events.

Parameters:

- `eventType` (`string`): event name
- `data` (`Object`): data to send along with the event

## clpp.net (namespace)

Classes, utilities and types for making network requests.

### Static properties

#### clpp.net.DEFAULT_FATAL_STATUS_CODES

Type: `Array<number>`

Default fatal status codes are 403 and 401.

### Static methods

#### clpp.net.makeRequest

```ts
makeRequest(source: string | Array<string> | Record<string, any>, opt_attemptParameters?: clpp.net.AttemptParameters): clpp.net.Request
```

Create an object representing an HTTP request.

Parameters:

- `source` (`string | Array<string> | Record<string, any>`): A single URI, a list of URIs (tried in order on failure), or an object with `clpp.net.Request` properties to initialize the request with. Unset properties get default values.
- `opt_attemptParameters` (`clpp.net.AttemptParameters`, optional): Optional retry and timeout parameters that override the ones given in `source`.

Returns: `clpp.net.Request` - The new request object.

## clpp.net.AttemptParameters (typedef)

General configuration for the recovery mechanism of retrying network requests.

Properties:

- `maxAttempts` (`number`): The maximum number of times the request should be attempted.
- `baseDelay` (`number`): The delay before the first retry, in milliseconds.

  For successive retries this value gets repeatedly multiplied by `backoffFactor`.
- `backoffFactor` (`number`): Exponential backoff strategy is used by the player when retrying network requests.

  Configure the multiplier for successive retry delays.

  Example: If `baseDelay` is 1s and `backoffFactor` is 2 then 4 retries would be made with the following delays in between: of 1s, 2s, 4s, 8s.
- `fuzzFactor` (`number`): Fuzz factor to apply to each retry delay in order to randomize it.

  If a server is overloaded a large number of clients retrying to fetch data at the same time might worsen the situation. Fuzz factor aims to alleviate that by randomizing the delays between requests and spreading them in time from the point of view of the server.

  Example: a value of 0.5 means between 50% below and 50% above the retry delay.
- `timeout` (`number`): How many milliseconds the player should wait for a response to an HTTP request.

  If the time elapses without a response the request is considered failed and is either retried or throws an error.

  Zero means unlimited timeout. In that case it is up to the server or the browser to handle timeout of the request.
- `fatalStatusCodes` (`Array<number>`, optional), default `[403, 401]`: List of HTTP status codes that will not trigger a retry and will be considered fatal instead.

## clpp.net.FragmentCallback (callback)

```ts
function(fragment: clpp.net.Mp4Fragment): Promise<any> | null
```

This callback is called whenever a new MP4 fragment is parsed.

Parameters:

- `fragment` (`clpp.net.Mp4Fragment`): The parsed MP4 fragment.

Returns: `Promise<any> | null` - A promise that is awaited before reading of the response continues, or null if there is nothing to wait for.

## clpp.net.Mp4Fragment (typedef)

MP4 fragment.

Properties:

- `start` (`number`): The start of this fragment
- `end` (`number`): The end of this fragment
- `length` (`number`): The length of the fragment
- `data` (`DataView`): The data
- `count` (`number`): The number of mdat boxes in this fragment or -1 if the number is unknown

## clpp.net.NetworkEngine (class)

Constructor:

```ts
new clpp.net.NetworkEngine()
```

The network engine is responsible for making HTTP(S) requests.

Requests are made either via XHR or Fetch API, the better option will be automatically selected based on availability.

It also supports fetching data via the `data:` scheme.

### Methods

#### clpp.net.NetworkEngine#setRateLimit

```ts
setRateLimit(limitBps: number)
```

Set a rate limit in bits per second.

Note that this is intended for debug purposes only. The setting will only affect the next request.

Parameters:

- `limitBps` (`number`): rate limit in bits per second, pass a value <= 0 to disable the rate limit.

#### clpp.net.NetworkEngine#addRequestModifier

```ts
addRequestModifier(callback: clpp.net.RequestModifier)
```

Registers callbacks for to modify network requests.

You can use this to intercept and manipulate the network requests for manifest and segment downloads. For example, use this if you need to add additional headers or query parameters to the request.

These requests can be removed through the `clpp.net.NetworkEngine#removeRequestModifier` function.

Note that fetching HLS data on Safari is not handled by NetworkEngine and thus request modifiers will not be called.

Parameters:

- `callback` (`clpp.net.RequestModifier`): The function which is called when a network requests is fired. It allows the modification of the request before it's sent to the server

Example: Adding a network request modifier

```js
const player = new clpp.Player(...);
 ...
const networkEngine = player.getNetworkEngine();

networkEngine.addRequestModifier(function (request) {
  if (request.type === clpp.net.RequestType.MANIFEST) {
    console.log('Manifest request ...', request.uris);
  } else if (request.type === clpp.net.RequestType.SEGMENT) {
    console.log('Segment request ...');
    // E.g. add a custom header
    request.headers['custom-header'] = 'custom-value';
  }
});
```

#### clpp.net.NetworkEngine#addResponseModifier

```ts
addResponseModifier(callback: clpp.net.ResponseModifier)
```

Registers callbacks for to modify network responses.

You can use this to intercept and manipulate the network responses for manifest and segment downloads. For example, use this if you need to adjust fetched data.

These responses can be removed through the `clpp.net.NetworkEngine#removeResponseModifier` function.

Note that fetching HLS data on Safari is not handled by NetworkEngine and thus response modifiers will not be called.

Parameters:

- `callback` (`clpp.net.ResponseModifier`): The function which is called when a network response is fired. It allows the modification of the response before it's processed.

Example: Adding a network response modifier

```js
const player = new clpp.Player(...);
 ...
const networkEngine = player.getNetworkEngine();

networkEngine.addResponseModifier(function (response) {
  if (response.request.type === clpp.net.RequestType.MANIFEST) {
    console.log('Manifest response ...');
  } else if (response.request.type === clpp.net.RequestType.SEGMENT) {
    console.log('Segment response ...');
  }
  console.log('Associated request', response.request);
});
```

#### clpp.net.NetworkEngine#removeRequestModifier

```ts
removeRequestModifier(callback: clpp.net.RequestModifier)
```

Remove registered network request modifier added via `addRequestModifier()` (`clpp.net.NetworkEngine#addRequestModifier`).

Parameters:

- `callback` (`clpp.net.RequestModifier`): A reference to the function that was previously registered

Example: Unregistering a network request modifier

```js
const player = new clpp.Player(...);

function myModifier (request) {
  console.log('A network request!');
}

const networkEngine = player.getNetworkEngine();

// registering the request modifier
networkEngine.addRequestModifier(myModifier);

...
// removing the network request modifier
networkEngine.removeRequestModifier(myModifier);
```

#### clpp.net.NetworkEngine#removeResponseModifier

```ts
removeResponseModifier(callback: clpp.net.ResponseModifier)
```

Remove registered network response modifier added via `addResponseModifier()` (`clpp.net.NetworkEngine#addResponseModifier`).

Parameters:

- `callback` (`clpp.net.ResponseModifier`): A reference to the function that was previously registered

Example: Unregistering a network response modifier

```js
const player = new clpp.Player(...);

function myModifier (response) {
  console.log('A network response!');
}

const networkEngine = player.getNetworkEngine();

// registering the response modifier
networkEngine.addRequestModifier(myModifier);

...
// removing the network response modifier
networkEngine.removeRequestModifier(myModifier);
```

#### clpp.net.NetworkEngine#fetch

```ts
fetch(request: clpp.net.Request): clpp.net.PendingRequest
```

Fetch data over the network.

Parameters:

- `request` (`clpp.net.Request`): a request

Returns: `clpp.net.PendingRequest` - an abortable promise of a response

## clpp.net.ProgressCallback (callback)

```ts
function(size: number, durationMs: number)
```

The progress callback is called during the ongoing download.

The size and time only refers to the chunk. If you want to get the numbers of the overall progress, you can query `bytesLoaded`, `bytesRemaining` and `bytesTotal` of this request object.

Parameters:

- `size` (`number`): number of bytes of the progress chunk
- `durationMs` (`number`): time in milliseconds it took to download that chunk

## clpp.net.Request (typedef)

A network request.

Properties:

- `uris` (`Array<string>`): An array of URIs to attempt. They will be tried in the order they are given.
- `uriIndex` (`number`): The uri index into the array of URIs
- `method` (`string`): The HTTP method to use for the request.
- `body` (`ArrayBuffer`, optional): The body of the request.
- `headers` (`Record<string, string>`): A mapping of headers for the request.  e.g.: {'HEADER': 'VALUE'}
- `allowCrossSiteCredentials` (`boolean`): Make requests with credentials.  This will allow cookies in cross-site requests.  See [http://goo.gl/YBRKPe](http://goo.gl/YBRKPe)
- `type` (`clpp.net.RequestType`): The request type
- `onProgress` (`clpp.net.ProgressCallback`, optional): Callback to notify about progress of ongoing download.
- `onFragment` (`clpp.net.FragmentCallback`, optional): If this callback is defined, fMP4 files or media segments will be downloaded and parsed progressively and the fMP4 fragments will be reported to this callback as they come.
- `maxAttempts` (`number`): The maximum number of times the request should be attempted.
- `currentAttempt` (`number`): The current attempt
- `baseDelay` (`number`): The delay before the first retry, in milliseconds.
- `backoffFactor` (`number`): The multiplier for successive retry delays.
- `fuzzFactor` (`number`): The maximum amount of fuzz to apply to each retry delay. For example, 0.5 means "between 50% below and 50% above the retry delay."
- `timeout` (`number`): The request timeout, in milliseconds.  Zero means "unlimited".
- `requestModifiers` (`Array<clpp.net.RequestModifier>`): The list of request modifiers that will be applied to this request
- `responseModifiers` (`Array<clpp.net.ResponseModifier>`): The list of response modifiers that will be applied to this request
- `startTime` (`number`, optional): The media start time in seconds or null
- `endTime` (`number`, optional): The media end time in seconds or null
- `contentType` (`string`, optional): The media content type or null
- `licenseRequestType` (`string`, optional): The license request type for DRM license requests
- `sessionId` (`string`, optional): If this is a LICENSE request, this field contains the session ID of the EME session that made the request.
- `bytesRemaining` (`number`): Remaining bytes of this request or -1 if unknown
- `bytesTotal` (`number`): Total bytes of this request or -1 if unknown
- `bytesLoaded` (`number`): Loaded bytes of this request or -1 if unknown
- `timescale` (`number`, optional): The media timescale or null
- `rateLimitBps` (`number`, optional): Add a rate limit to the download speed. Note that this is for debug purposes only and artificially delays the download but can not actually rate limit the connection.
- `disableFragmentSupport` (`boolean`, optional): Disable support for fragment parsing
- `disableMergedFragments` (`boolean`, optional): Disable support for merged fragments. By default `clpp.net.Request#onFragment` receives MP4 fragments that may be composed of multiple chunks. If this is set to true, each chunk will be reported as a separate fragment.
- `fatalStatusCodes` (`Array<number>`, optional): List of http status codes that will not trigger a retry and will be considered fatal.
- `requestStartTimestamp` (`number`, optional): Timestamp when the request was started. Optional and only set and used now for purposes of analytics.

## clpp.net.RequestModifier (callback)

```ts
function(request: clpp.net.Request): Promise<clpp.net.Request> | void
```

This callback can modify a network request before sending it to the server.

A request modifier can return a promise, if it rejects the download is cancelled and the player will dispatch an error.

Parameters:

- `request` (`clpp.net.Request`): The request that is about to be sent. It can be modified in place.

Returns: `Promise<clpp.net.Request> | void` - Nothing if the request was modified in place, or a promise that resolves to the request that should be sent.

## clpp.net.RequestType (enum)

Requests types that are used to identify requests and responses in modifiers.

Values:

- `MANIFEST` = `1`: Request for a DASH manifest or an HLS playlist.
- `SEGMENT` = `2`: Request for a media segment (audio, video, text or init segment).
- `LICENSE` = `3`: DRM license or certificate request.
- `APP` = `4`: Request made on behalf of the application.
- `TIMING` = `5`: Clock synchronization request, e.g. for DASH `UTCTiming`.
- `OTHER` = `6`: Any other request, e.g. for thumbnails. Used when no type is specified.
- `CONTENT_STEERING` = `7`: Request for a content steering manifest.

## clpp.net.Response (typedef)

A network response.

Properties:

- `uri` (`string`): The URI which was loaded. Request filters and server redirects can cause this to be different from the original request URIs.
- `data` (`ArrayBuffer`): The body of the response.
- `headers` (`Record<string, string>`): A map of response headers, if supported by the underlying protocol. All keys should be lowercased. For HTTP/HTTPS, may not be available cross-origin.
- `status` (`number`, optional): The HTTP status code
- `timeMs` (`number`, optional): Optional.  The time it took to get the response, in milliseconds.  If not given, NetworkingEngine will calculate it using Date.now.
- `responseStartMs` (`number`, optional): Optional.  The time it took to get the first byte of the response, in ms.
- `fromCache` (`boolean`, optional): Optional. If true, this response was from a cache and should be ignored for bandwidth estimation.
- `request` (`clpp.net.Request`, optional): The associated request

## clpp.net.ResponseModifier (callback)

```ts
function(response: clpp.net.Response): clpp.net.Response | Promise<clpp.net.Response> | void
```

This callback can modify a network response right after it is received from the server. It can also be used to listen to network responses without modifying them.

A response modifier can return a promise, if it rejects the download is considered a failure and the player will dispatch an error.

Parameters:

- `response` (`clpp.net.Response`): The response received from the server. It can be modified in place.

Returns: `clpp.net.Response | Promise<clpp.net.Response> | void` - Nothing, the response, or a promise that resolves to the response once processing is done.

## clpp.npaw.NpawPlugin (class)

Constructor:

```ts
new clpp.npaw.NpawPlugin()
```

NPAW V7 Analytics plugin.

### Static properties

#### clpp.npaw.NpawPlugin.Id

Type: `string`

The ID of the NPAW plugin, e.g. to get the plugin instance with `clpp.Player#getPlugin`.

### Methods

#### clpp.npaw.NpawPlugin#setNpawPlugin

```ts
setNpawPlugin(plugin: clpp.npaw.NpawPlugin | null)
```

Sets NPAW V7 Plugin. Use it before playback if you want to use Castlabs Player with App Analytics Integration

Options added in player configuration will be passed to NPAW Plugin.

Parameters:

- `plugin` (`clpp.npaw.NpawPlugin | null`): The NPAW plugin instance to connect to the player, or null to disconnect the current one.

Example: Set the NPAW plugin.

```js
import "@castlabs/prestoplay/cl.youbora";

const plugin = new NpawPlugin({
  // your custom options
});
const player = new clpp.Player('video', {
  license: '...',
  npaw: {
    accountCode: 'account_code',
  },
});
player.getPlugin(clpp.npaw.NpawPlugin.Id).setNpawPlugin(plugin);

// Now you can start playback.
player.open('http://example.com/Manifest.mpd');
```

#### clpp.npaw.NpawPlugin#getNpawPlugin

```ts
getNpawPlugin(): clpp.npaw.NpawPlugin | null
```

Gives access to the underlying NPAW Plugin instance. Can be used e.g. to set custom options using `setAnalyticsOptions` For more details, check [https://documentation.npaw.com/integration-docs/docs/options-analytics-js](https://documentation.npaw.com/integration-docs/docs/options-analytics-js)

Returns: `clpp.npaw.NpawPlugin | null` - plugin

Example:

```js
const plugin = player.getPlugin(clpp.npaw.NpawPlugin.Id).getNpawPlugin()
plugin.setAnalyticsOptions({
  'content.isLive': true
})
```

#### clpp.npaw.NpawPlugin#getAdapter

```ts
getAdapter(): NpawPluginAdapters.video.Shaka | null
```

Gives access to the underlying NPAW Plugin Video Adapter. Can be used i.e. to emit custom errors using `fireError(code, message)` or `fireFatalError(code, message)` or to emit specific events. Use it with caution and only if you know what you are doing, as it might break integration. For more details, check [https://documentation.npaw.com/integration-docs/docs/custom-video-events-js#custom-event-code-example](https://documentation.npaw.com/integration-docs/docs/custom-video-events-js#custom-event-code-example)

Returns: `NpawPluginAdapters.video.Shaka | null` - Npaw Plugin Adapter Shaka or null if there is no active session

#### clpp.npaw.NpawPlugin#getAdsAdapter

```ts
getAdsAdapter(): NpawPluginAdapters.ads.Ima | null
```

Gives access to the underlying NPAW Plugin Ads Adapter. Can be used i.e. to emit custom errors using `fireError(code, message)` or `fireFatalError(code, message)` or to emit specific events. Use it with caution and only if you know what you are doing, as it might break integration. For more details, check [https://documentation.npaw.com/integration-docs/docs/custom-video-events-js#custom-event-code-example](https://documentation.npaw.com/integration-docs/docs/custom-video-events-js#custom-event-code-example)

Returns: `NpawPluginAdapters.ads.Ima | null` - NPAW Plugin Adapter Ima or null if there is no active session

## clpp.npaw.YouboraPlugin (class)

Constructor:

```ts
new clpp.npaw.YouboraPlugin()
```

Youbora analytics plugin.

### Static properties

#### clpp.npaw.YouboraPlugin.Id

Type: `string`

The ID of the Youbora plugin, e.g. to get the plugin instance with `clpp.Player#getPlugin`.

### Methods

#### clpp.npaw.YouboraPlugin#setYouboraPlugin

```ts
setYouboraPlugin(plugin: youbora.Plugin | null)
```

Sets Youbora Plugin. Use it before playback if you want to use Castlabs Player with Youbora Sessions.

Options added in player configuration will be passed to Youbora Plugin.

Parameters:

- `plugin` (`youbora.Plugin | null`): The Youbora plugin instance to connect to the player, or null to disconnect the current one.

Example: Set the Youbora plugin.

```js
import "@castlabs/prestoplay/cl.youbora";

const player = new clpp.Player('video', {
  license: '...',
  youbora: {
    accountCode: 'account_code',
  },
});

const plugin = new youbora.Plugin({
  // your custom options
});
player.getPlugin(clpp.npaw.YouboraPlugin.Id).setYouboraPlugin(plugin);

// Now you can start playback.
player.open('http://example.com/Manifest.mpd');
```

#### clpp.npaw.YouboraPlugin#getAdapter

```ts
getAdapter(): youbora.Adapter | null
```

Gives access to the underlying Youbora Adapter. Can be used i.e. to emit custom errors using `fireError(code, message)` or `fireFatalError(code, message)` or to emit specific events. Use it with caution and only if you know what you are doing, as it might break integration. For more details, check Youbora Documentation.

Returns: `youbora.Adapter | null` - Youbora adapter or null if there is no active session

#### clpp.npaw.YouboraPlugin#getAdsAdapter

```ts
getAdsAdapter(): youbora.Adapter | null
```

Gives access to the underlying Youbora Ads Adapter. Can be used i.e. to emit custom errors using `fireError(code, message)` or `fireFatalError(code, message)` or to emit specific events. Use it with caution and only if you know what you are doing, as it might break integration. For more details, check Youbora Documentation.

Returns: `youbora.Adapter | null` - Youbora ads adapter or null if there is no active session

## clpp.onboard (namespace)

DRMtoday Onboard functionality.

### Static methods

#### clpp.onboard.register

```ts
register(name: string, config: clpp.OnboardConfiguration)
```

Registers new DRMtoday Onboard environment.

Parameters:

- `name` (`string`): The name of the environment.
- `config` (`clpp.OnboardConfiguration`): The DRMtoday Onboard configuration.

Example:

```js
clpp.onboard.register('DRMtodayOnboard', {
  baseUrl: 'https://ife.castlabs.com/'
});

let player = new clpp.Player(...);

// Acquire license
player.open({
  source: 'https://demo.castlabs.com/media/onboard-test/Manifest.mpd',
  drm: {
    env: 'DRMtodayOnboard'
  }
});
```

## clpp.onboard.OnboardComponent (class)

Constructor:

```ts
new clpp.onboard.OnboardComponent()
```

This component adds DRMtoday Onboard support to the player.

Example:

```js
import "@castlabs/prestoplay/cl.onboard";

// Acquire license
player.open({
  source: 'https://demo.castlabs.com/media/onboard-test/Manifest.mpd',
  drm: {
    env: 'DRMtodayOnboard',
    customData: {
      baseUrl: 'https://ife.castlabs.com/'
    }
  }
});
```

## clpp.persistent (namespace)

Methods and a component for working with persistent DRM licenses.

### Static methods

#### clpp.persistent.useStorage

```ts
useStorage(storageImpl: clpp.persistent.ISessionStorage)
```

Use this method to provide a session storage implementation.

The storage implementation will be used by the player to save and load offline session. If no storage implementation is provided, the default, built-in storage implementation which is based on the localStorage browser API.

Parameters:

- `storageImpl` (`clpp.persistent.ISessionStorage`): The storage engine.

Throws:

- `clpp.Error` If the storage implementation is missing required methods (`INVALID_SESSION_STORAGE_IMPLEMENTATION`).

Example: Use custom storage implementation for persistent DRM licenses.

```js
// implements clpp.persistent.ISessionStorage
 const MySessionStorage = class {
   ...
 };

 try {
   clpp.persistent.useStorage(new MySessionStorage());
 } catch (error) {
   console.log(error);
 }

 const player = new clpp.Player(...);
```

#### clpp.persistent.fetchLicense

```ts
fetchLicense(source: clpp.Source | string, drmConfig: clpp.DrmConfiguration, ...opt_components: any): Promise<void>
```

Fetches and persists a DRM session/license.

Parameters:

- `source` (`clpp.Source | string`): Manifest source in form of URL string or clpp.Source object.
- `drmConfig` (`clpp.DrmConfiguration`): DRM configuration. Offline ID must be set.
- `...opt_components` (`any`): Optional components to use, i.e. DASH component to allow us to parse its manifest. Not needed if you already have a working player instance with loaded modules. Note that this param is deprecated and will be removed in v7.0.0.

Returns: `Promise<void>` - Resolves once the license has been fetched and the session stored. Rejects with a `clpp.Error` on failure.

#### clpp.persistent.removeLicense

```ts
removeLicense(offlineId: string): Promise<void>
```

Remove an offline Media Key Session.

Parameters:

- `offlineId` (`string`): The offlineId associated with the license to be removed

Returns: `Promise<void>` - Resolves once the session has been removed from the CDM and the storage, or if no session is stored for the ID. Rejects with a `clpp.Error` (`FAILED_TO_REMOVE_SESSION`) on failure.

## clpp.persistent.ISessionStorage (interface)

A storage for offline DRM session information, so that persistent media key sessions can be re-used later, e.g. to play downloaded content offline.

The player uses a built-in implementation based on the `localStorage` browser API by default. Provide your own implementation with `clpp.persistent.useStorage`.

### Methods

#### clpp.persistent.ISessionStorage#store

```ts
store(offlineId: string, sessionInfo: clpp.persistent.SessionInfo): Promise<unknown>
```

Stores the session information, replacing any stored under the same ID.

Parameters:

- `offlineId` (`string`): The ID to store the session information under.
- `sessionInfo` (`clpp.persistent.SessionInfo`): The session information.

Returns: `Promise<unknown>` - Resolves once the session information is stored.

#### clpp.persistent.ISessionStorage#get

```ts
get(offlineId: string): Promise<?clpp.persistent.SessionInfo>
```

Loads the session information.

Parameters:

- `offlineId` (`string`): The ID the session information is stored under.

Returns: `Promise<?clpp.persistent.SessionInfo>` - Resolves with the session information, or null if none is stored under the ID.

#### clpp.persistent.ISessionStorage#delete

```ts
delete(offlineId: string): Promise<unknown>
```

Deletes the session information.

Parameters:

- `offlineId` (`string`): The ID the session information is stored under.

Returns: `Promise<unknown>` - Resolves once the session information is deleted.

#### clpp.persistent.ISessionStorage#clear

```ts
clear(): Promise<unknown>
```

Deletes all stored session information.

Returns: `Promise<unknown>` - Resolves once all session information is deleted.

#### clpp.persistent.ISessionStorage#getName

```ts
getName(): string
```

Returns: `string` - The name of the storage implementation.

## clpp.persistent.PersistentLicenseComponent (class)

Constructor:

```ts
new clpp.persistent.PersistentLicenseComponent()
```

This component adds the capability to store DRM licenses for later use on supported platforms.

Example: Persist DRM license under key "myOfflineId".

```js
import "@castlabs/prestoplay/cl.persistent";

// The DRM licenses will be persisted and stored
// under the storage key `myOfflineId`.
player.open({
  source: ...,
  drm: {
    offlineId: 'myOfflineId',
    ...
  }
});
```

## clpp.persistent.SessionInfo (typedef)

Offline DRM session information. This information is needed in order to load a persistent media key session for re-use.

Properties:

- `sessionIds` (`Array<string>`): Contains the session ids.
- `keySystem` (`clpp.drm.KeySystem`): The key system, e.g., "com.widevine.alpha".
- `licenseServerUri` (`string`): The license server URI.
- `serverCertificate` (`Uint8Array | null`): A key-system-specific server certificate used to encrypt license requests.
- `audioCapabilities` (`Array<MediaKeySystemMediaCapability>`): A list of supported audio type and capability pairs.
- `videoCapabilities` (`Array<MediaKeySystemMediaCapability>`): A list of supported video type and capability pairs.
- `drmConfig` (`clpp.DrmConfiguration`): The DRM configuration.

## clpp.playlist.McPlaylist (class)

Constructor:

```ts
new clpp.playlist.McPlaylist(options: clpp.plist.Options)
```

**Experimental:** may change without a major release.

Multi-controller playlist intended for fast live TV channel zapping.

It is based on an architecture which leverages multiple video elements and multiple instances of `clpp.Player` to preload assets in order to reduce zap time.

**Known limitations:**

- It does not support multi-period DASH or discontinuous HLS.
- It does not support plugins (e.g. analytics).
- `setItems()` can only be called once.
- `setIndex()` can only be called once.
- Only one next item and one previous item are preloaded and it is only possible to go to the next / previous item, it is not possible to jump to an arbitrary item.
- It only works in auto-play mode (`autoplay: true` must be configured).

Parameters:

- `options` (`clpp.plist.Options`): configuration options of the playlist

### Methods

#### clpp.playlist.McPlaylist#getCurrent

```ts
getCurrent(): clpp.plist.Item | null
```

Returns the currently playing/loading item.

Returns: `clpp.plist.Item | null` - the currently playing or selected item

#### clpp.playlist.McPlaylist#getCurrentPlayer

```ts
getCurrentPlayer(): clpp.Player | null
```

Returns the currently playing player.

Returns: `clpp.Player | null` - the currently playing player

#### clpp.playlist.McPlaylist#getNext

```ts
getNext(): clpp.plist.Item | null
```

Returns the next (preloaded) item.

Returns: `clpp.plist.Item | null` - The item after the current one, or `null` if it is not preloaded.

#### clpp.playlist.McPlaylist#getPrev

```ts
getPrev(): clpp.plist.Item | null
```

Returns the previous (preloaded) item.

Returns: `clpp.plist.Item | null` - The item before the current one, or `null` if it is not preloaded.

#### clpp.playlist.McPlaylist#getPreloading

```ts
getPreloading(): Array<clpp.plist.Item>
```

Returns all the currently preloading items.

Returns: `Array<clpp.plist.Item>` - The preloaded previous and next items, if any.

#### clpp.playlist.McPlaylist#setItems

```ts
setItems(configs: Array<clpp.PlayerConfiguration>)
```

Sets playlist items to be played.

Parameters:

- `configs` (`Array<clpp.PlayerConfiguration>`): source configs of items in the playlist

#### clpp.playlist.McPlaylist#setIndex

```ts
setIndex(index: number)
```

Sets the index of the item to start with.

Parameters:

- `index` (`number`): index of the current item to play

#### clpp.playlist.McPlaylist#hasNext

```ts
hasNext(): boolean
```

Returns true if there is a next item to play.

Returns: `boolean` - true if it has a next item to play

#### clpp.playlist.McPlaylist#hasPrev

```ts
hasPrev(): boolean
```

Returns true if there is a previous item to play.

Returns: `boolean` - true if it has a previous item to play

#### clpp.playlist.McPlaylist#playFirst

```ts
playFirst(): Promise<void>
```

Play the first item.

Make sure to set items via `clpp.playlist.McPlaylist.setItems` and select the index to start from via `clpp.playlist.McPlaylist.setIndex` before calling this method.

To switch to the next or previous item use methods `clpp.playlist.McPlaylist.playNext` and `clpp.playlist.McPlaylist.playPrev`.

Returns: `Promise<void>` - resolves when the item starts playing

#### clpp.playlist.McPlaylist#playNext

```ts
playNext(): Promise<void>
```

Play the next item in the playlist.

Returns: `Promise<void>` - resolves when the item starts playing

#### clpp.playlist.McPlaylist#playPrev

```ts
playPrev(): Promise<void>
```

Play the previous item in the playlist.

Returns: `Promise<void>` - resolves when the item starts playing

#### clpp.playlist.McPlaylist#destroy

```ts
destroy(): Promise<void>
```

Destroy the playlist and all of its players. The instance will not be usable after it was destroyed.

Returns: `Promise<void>` - A promise that resolves once the playlist is fully destroyed.

## clpp.playlist.ScPlaylist (class)

Constructor:

```ts
new clpp.playlist.ScPlaylist(element: HTMLMediaElement | string, opt_configuration?: clpp.ConstructorPlayerConfiguration, opt_viewConfiguration?: clpp.PlayerSurfaceConfiguration)
```

**Experimental:** may change without a major release.

The single-controller playlist is intended for smooth continuous back-to-back playback of multiple items. The playlist class inherits from `clpp.Player` so all methods defined there can also be called on the playlist instance (including `on()` (`clpp.Player#on`), `off()` (`clpp.Player#off`), `getPosition()` (`clpp.Player#getPosition`), `setPosition()` (`clpp.Player#setPosition`), etc).

**Limitations:** Plugins are disabled. Encrypted streams are supported only if all the items are encrypted with the same method and key.

Create a new instance of the single-controller playlist. You should pass in the Castlabs license via the second parameter.

Parameters:

- `element` (`HTMLMediaElement | string`): The media element or the ID of the media element to use as the underlying player
- `opt_configuration` (`clpp.ConstructorPlayerConfiguration`, optional): The global player configuration
- `opt_viewConfiguration` (`clpp.PlayerSurfaceConfiguration`, optional): The global player view configuration

Throws:

- `clpp.Error` with different codes

  - `clpp.Error.Code.NO_ELEMENT` if no element is provided
  - `clpp.Error.Code.INVALID_LICENSE` if no license was provided in the configuration

Example: Construct the playlist and pass in the Castlabs license.

```js
const playlist = new clpp.playlist.ScPlaylist('video', {
  license: '...'
});
```

Example: Listen to item changes.

```js
playlist.on(clpp.events.SC_PLAYLIST_ITEM_CHANGED, (event) => {
  // event.id contains the `id` property of the current item
});
```

Example: Listen to changes in the timeline.

```js
playlist.on(clpp.events.SC_PLAYLIST_TIMELINE_CHANGED, () => {
  // maybe redraw the timeline UI
});
```

Example: Listen to end of playlist.

```js
playlist.on(clpp.events.SC_PLAYLIST_ENDED, () => {
  // ...
});
```

### Methods

#### clpp.playlist.ScPlaylist#openPlaylist

```ts
openPlaylist(index: number, configs: Array<clpp.PlayerConfiguration>): Promise<void>
```

Load items to the playlist and start playing the first one.

Parameters:

- `index` (`number`): the index of the item to start playback at. Currently only 0 is supported.
- `configs` (`Array<clpp.PlayerConfiguration>`): a list of items where each config must contain at least an `id` and a `source`.

Returns: `Promise<void>` - A promise that resolves once the first item of the playlist is loaded.

Throws:

- `clpp.Error` with codes

  - `clpp.Error.Code.CANNOT_LOAD_SOURCE` if no items are provided
  - `clpp.Error.Code.INVALID_CONFIGURATION` if any config lacks required properties `id` or `source`; or if the `id`s are not unique
  - `clpp.Error.Code.INVALID_ARGUMENT` if an unsupported is passed in for index

Example: Open a playlist of two items, start from the position of 2 minutes and automatically start playback.

```js
await playlist.openPlaylist(0, [
  {
    id: 'ASSET1',
    source: { url: '...' },
    autoplay: true,
    playlist: {
      startTime: 120,
    }
  },
  {
    id: 'ASSET2',
    source: { url: '...' }
  }
]);
```

#### clpp.playlist.ScPlaylist#addItem

```ts
addItem(config: clpp.PlayerConfiguration): Promise<void>
```

Append an item to the end of the playlist. This method cannot be called before `openPlaylist()` (`clpp.playlist.ScPlaylist#openPlaylist`).

Parameters:

- `config` (`clpp.PlayerConfiguration`): an item which must contain at least an `id` and a `source`.

Returns: `Promise<void>` - A promise that resolves once the item is added to the playlist.

Throws:

- `clpp.Error` with codes

  - `clpp.Error.Code.WRONG_ORDER_OF_OPERATIONS` when attempting to call this method earlier than openPlaylist().
  - `clpp.Error.Code.INVALID_CONFIGURATION` when the config lacks required properties `id` or `source`; or when the config's `id` already exists in the playlist.

Example: Append an item to the playlist.

```js
await playlist.addItem({
  id: 'ASSET3',
  source: { url: '...' }
});
```

#### clpp.playlist.ScPlaylist#getCurrentItem

```ts
getCurrentItem(): clpp.PlayerConfiguration | null
```

Get the currently playing item.

Returns: `clpp.PlayerConfiguration | null` - the currently playing item or null if no item is playing

Example: Get the config of the current item.

```js
const item = playlist.getCurrentItem(); // { id: 'ASSET1', ... }
```

#### clpp.playlist.ScPlaylist#getCurrentItemIndex

```ts
getCurrentItemIndex(): number
```

Get the index of the currently playing item.

Returns: `number` - the index of the currently playing item

Example: Get the index of the current item.

```js
const index = playlist.getCurrentItemIndex(); // 0
```

#### clpp.playlist.ScPlaylist#getPlaylist

```ts
getPlaylist(): Array<clpp.PlayerConfiguration>
```

Get all the items of the playlist.

Returns: `Array<clpp.PlayerConfiguration>` - an array of all the items in this playlist

Example: Get playlist items.

```js
const items = playlist.getPlaylist(); // [...]
```

#### clpp.playlist.ScPlaylist#getSize

```ts
getSize(): number
```

Get the number of items in the playlist.

Returns: `number` - the count of items in this playlist

Example: Get the number of items in the playlist.

```js
const countItems = playlist.getSize(); // 4
```

#### clpp.playlist.ScPlaylist#getTimeline

```ts
getTimeline(): clpp.media.Timeline | null
```

Get the timeline of the playlist.

Returns: `clpp.media.Timeline | null` - the timeline of the playlist

Example: Get timeline windows.

```js
const timeline = playlist.getTimeline();
const windows = timeline?.getWindows();
```

Example: Get the current timeline window.

```js
const timeline = playlist.getTimeline();
const timelineWindow = timeline?.getCurrentWindow();
```

#### clpp.playlist.ScPlaylist#seekWith

```ts
seekWith(offset: number): Promise<unknown>
```

Seek to a position relative to the current position. This may result in seeking to one of the following/preceding items in the playlist.

Parameters:

- `offset` (`number`): the offset in seconds relative to the current position to seek by. A positive value seeks forward, a negative value seeks backward.

Returns: `Promise<unknown>` - A promise that resolves once the seek is done.

Example: Seek 2 minutes forward.

```js
await playlist.seekWith(120);
```

Example: Seek 2 minutes backward.

```js
await playlist.seekWith(-120);
```

#### clpp.playlist.ScPlaylist#release

```ts
release(): Promise<void>
```

Release the playlist instance resources. The playlist can load another source after it was released.

Returns: `Promise<void>` - A promise that resolved once all resources of the playlist are released

Example: Release and reset the playlist.

```js
await playlist.release();
```

#### clpp.playlist.ScPlaylist#destroy

```ts
destroy(): Promise<void>
```

Destroy this playlist instance. The instance will not be usable after it was destroyed.

Returns: `Promise<void>` - A promise that resolves once the playlist is fully destroyed

Example: Destroy the playlist.

```js
await playlist.destroy();
// Do not call any methods on the playlist after this point
```

#### clpp.playlist.ScPlaylist#setCdnErrorCallback

```ts
setCdnErrorCallback()
```

**Deprecated.** This method is inherited from clpp.Player but the playlist does not support it.

Not supported by the playlist, always throws a `clpp.Error.Code.NOT_SUPPORTED` error.

## clpp.plist.Item (typedef)

**Experimental:** may change without a major release.

A playlist item. It consists of an asset/config, a player instances selected to play this asset and the underlying video element to which the player is attached.

Properties:

- `config` (`clpp.PlayerConfiguration`): Source configuration.
- `index` (`number`): The index of the item in the playlist.
- `player` (`clpp.Player | null`): A player instance.
- `preloadPromise` (`Promise<unknown>`): A promise that resolves when the item is preloaded.
- `role` (`string`, optional): The role of the item.
- `state` (`string`, optional): The state of the item (e.g. 'preloading', 'preloaded', 'preload-failed').
- `videoEl` (`HTMLVideoElement | null`): The video element attached to the player.

## clpp.plist.Options (typedef)

**Experimental:** may change without a major release.

Playlist options.

Properties:

- `anchorId` (`string`): ID of the HTML element to be used as a container for video elements created by this playlist.
- `autoplayNext` (`boolean`, optional), default `false`: If true, when one item finishes playback the next item is played automatically and so on until the end of the playlist.
- `config` (`clpp.PlayerConfiguration`): Default configuration for player instances.
- `preloadMedia` (`boolean`, optional), default `false`: If true, preloaded items will have also their media segments preloaded thus reducing the time to start playback to minimum. This option is intended to be used with VOD streams.
- `transition` (`string`, optional), default `"pause"`: Transition method, can be "pause" or "keep-playing". In cause of "pause" the current video will be paused when calling `clpp.playlist.McPlaylist.playNext` or `clpp.playlist.McPlaylist.playPrev`.
- `toggleVisible` (`function`, optional): A custom callback to toggle the visibility of a video element. By default this is done via z-index.

## clpp.smooth.SmoothComponent (class)

Constructor:

```ts
new clpp.smooth.SmoothComponent()
```

This component adds the capability to play Microsoft Smooth Streaming (MSS) streams.

Example:

```js
import "@castlabs/prestoplay/cl.smooth";

// Load Smooth Streaming content
player.open('https://example.com/ism/Manifest');
```

## clpp.text (namespace)

Classes representing subtitle cues and regions.

## clpp.text.Cue (class)

Constructor:

```ts
new clpp.text.Cue(startTime: number, endTime: number, payload: string, payloadType?: clpp.text.Cue.payloadType)
```

A text cue representing a line or multiple lines of subtitle text or an image in case of image-based subtitles.

Parameters:

- `startTime` (`number`): The start time of the cue in seconds, relative to the start of the presentation.
- `endTime` (`number`): The end time of the cue in seconds, relative to the start of the presentation.
- `payload` (`string`): The cue content, interpreted according to `payloadType`.
- `payloadType` (`clpp.text.Cue.payloadType`, optional), default `clpp.text.Cue.payloadType.TEXT`: The format of the payload. Defaults to plain text.

### Properties

#### clpp.text.Cue#startTime

Type: `number`

The start time of the cue in seconds, relative to the start of the presentation.

#### clpp.text.Cue#endTime

Type: `number`

The end time of the cue in seconds, relative to the start of the presentation.

#### clpp.text.Cue#payload

Type: `string`

The payload of the cue.

#### clpp.text.Cue#payloadType

Type: `clpp.text.Cue.payloadType`

The type of the cue payload.

#### clpp.text.Cue#region

Type: `clpp.text.CueRegion | null`

The region to render the cue into.

#### clpp.text.Cue#cssClassList

Type: `Array<string>`

CSS classes associated with the cue.

#### clpp.text.Cue#position

Type: `number | null`

The indent (in percent) of the cue box in the direction defined by the writing direction.

#### clpp.text.Cue#positionAlign

Type: `clpp.text.Cue.positionAlign | null`

Position alignment of the cue.

#### clpp.text.Cue#size

Type: `number`

Size of the cue box (in percents).

#### clpp.text.Cue#textAlign

Type: `clpp.text.Cue.textAlign`

Alignment of the text inside the cue box.

#### clpp.text.Cue#direction

Type: `clpp.text.Cue.direction`

Text direction of the cue.

#### clpp.text.Cue#writingMode

Type: `clpp.text.Cue.writingMode`

Text writing mode of the cue.

#### clpp.text.Cue#lineInterpretation

Type: `clpp.text.Cue.lineInterpretation`

The way to interpret line field. (Either as an integer line number or percentage from the display box).

#### clpp.text.Cue#line

Type: `number | null`

The offset from the display box in either number of lines or percentage depending on the value of lineInterpretation.

#### clpp.text.Cue#lineAlign

Type: `clpp.text.Cue.lineAlign`

Line Alignment is set to start by default.

#### clpp.text.Cue#backgroundImage

Type: `string`

Image background represented by any string that would be accepted in image HTML element. E. g. 'data:[mime type];base64,[data]'.

#### clpp.text.Cue#id

Type: `string`

Id of the cue.

#### clpp.text.Cue#containerRows

Type: `number | null`

Number of rows used to calculate base font size.

## clpp.text.Cue.direction (enum)

Base direction of the cue text.

Values:

- `HORIZONTAL_LEFT_TO_RIGHT` = `ltr`: Text runs from left to right.
- `HORIZONTAL_RIGHT_TO_LEFT` = `rtl`: Text runs from right to left.

## clpp.text.Cue.lineAlign (enum)

Alignment of the cue box relative to its `line` position.

Values:

- `CENTER` = `center`: The cue box is centered at the line.
- `START` = `start`: The cue box's top side (for horizontal cues), left side (for vertical cues growing right) or right side (for vertical cues growing left) is aligned at the line.
- `END` = `end`: The cue box's bottom side (for horizontal cues), right side (for vertical cues growing right) or left side (for vertical cues growing left) is aligned at the line.

## clpp.text.Cue.lineInterpretation (enum)

Defines how the `line` value of a cue is interpreted.

Values:

- `LINE_NUMBER` = `0`: `line` is an integer line number; the cue snaps to that line of the display box.
- `PERCENTAGE` = `1`: `line` is an offset in percent (0-100) of the display box.

## clpp.text.Cue.payloadType (enum)

Format of the cue payload, which determines how it is rendered.

Values:

- `TEXT` = `text`: Plain text, rendered as is without interpreting any markup.
- `VTT_XML` = `vtt-xml`: WebVTT cue text with markup such as `<b>`, `<i>` or `<c>` tags.
- `TTML_XML` = `ttml-xml`: HTML markup produced from a TTML cue.

## clpp.text.Cue.positionAlign (enum)

Alignment of the cue box relative to its `position`, in the direction of the line (WebVTT `position` alignment).

Values:

- `LEFT` = `line-left`: The cue box starts at the position (its line-left edge is there).
- `RIGHT` = `line-right`: The cue box ends at the position (its line-right edge is there).
- `CENTER` = `center`: The cue box is centered at the position.
- `AUTO` = `auto`: The alignment is derived from the cue's text alignment.

## clpp.text.Cue.textAlign (enum)

Alignment of the text inside the cue box.

Values:

- `LEFT` = `left`: Text is aligned to the left edge of the cue box.
- `RIGHT` = `right`: Text is aligned to the right edge of the cue box.
- `CENTER` = `center`: Text is centered in the cue box.
- `START` = `start`: Text is aligned to the start edge of the cue box, i.e. left for left-to-right and right for right-to-left text.
- `END` = `end`: Text is aligned to the end edge of the cue box, i.e. right for left-to-right and left for right-to-left text.

## clpp.text.Cue.writingMode (enum)

Writing mode of the cue, i.e. the orientation of text lines and the direction in which new lines are added (CSS `writing-mode`).

Values:

- `HORIZONTAL_TOP_TO_BOTTOM` = `horizontal-tb`: Horizontal lines, stacked from top to bottom.
- `VERTICAL_LEFT_TO_RIGHT` = `vertical-lr`: Vertical lines, stacked from left to right.
- `VERTICAL_RIGHT_TO_LEFT` = `vertical-rl`: Vertical lines, stacked from right to left.

## clpp.text.CueRegion (class)

Constructor:

```ts
new clpp.text.CueRegion()
```

A region of the video area into which cues are rendered, as defined by WebVTT regions or TTML regions.

### Properties

#### clpp.text.CueRegion#id

Type: `string`

Region identifier.

#### clpp.text.CueRegion#viewportAnchorX

Type: `number`

The X offset to start the rendering area in anchorUnits of the video width.

#### clpp.text.CueRegion#viewportAnchorY

Type: `number`

The X offset to start the rendering area in anchorUnits of the video height.

#### clpp.text.CueRegion#regionAnchorX

Type: `number`

The X offset to start the rendering area in percentage (0-100) of the region width.

#### clpp.text.CueRegion#regionAnchorY

Type: `number`

The Y offset to start the rendering area in percentage (0-100) of the region height.

#### clpp.text.CueRegion#width

Type: `number`

The width of the rendering area in widthUnits.

#### clpp.text.CueRegion#height

Type: `number`

The width of the rendering area in heightUnits.

#### clpp.text.CueRegion#heightUnits

Type: `clpp.text.CueRegion.units`

The units (percentage, pixels or lines) the region height is in.

#### clpp.text.CueRegion#widthUnits

Type: `clpp.text.CueRegion.units`

The units (percentage or pixels) the region width is in.

#### clpp.text.CueRegion#viewportAnchorUnits

Type: `clpp.text.CueRegion.units`

The units (percentage or pixels) the region viewportAnchors are in.

#### clpp.text.CueRegion#scroll

Type: `clpp.text.CueRegion.scrollMode`

If scroll=UP, it means that cues in the region will be added to the bottom of the region and will push any already displayed cues in the region up. Otherwise (scroll=NONE) cues will stay fixed at the location they were first painted in.

#### clpp.text.CueRegion#cssClassList

Type: `Array<string>`

CSS classes associated with the region.

#### clpp.text.CueRegion#displayAlign

Type: `clpp.text.CueRegion.displayAlign | null`

Set the captions at the bottom of the text container by default.

#### clpp.text.CueRegion#writingMode

Type: `clpp.text.CueRegion.writingMode | null`

Text writing mode of the cue.

## clpp.text.CueRegion.displayAlign (enum)

Vertical alignments of the cues within their extents. 'BEFORE' means displaying at the top of the captions container box, 'CENTER' means in the middle, 'AFTER' means at the bottom.

Values:

- `BEFORE` = `flex-end`: Cues are displayed at the before edge of the region (the top for horizontal text).
- `CENTER` = `center`: Cues are displayed in the middle of the region.
- `AFTER` = `flex-start`: Cues are displayed at the after edge of the region (the bottom for horizontal text).

## clpp.text.CueRegion.scrollMode (enum)

Defines how cues added to a region are laid out over time.

Values:

- `NONE` = ``: Cues stay fixed at the location they were first painted in.
- `UP` = `up`: New cues are added at the bottom of the region and push already displayed cues up.

## clpp.text.CueRegion.units (enum)

Units in which region dimensions and anchors are expressed.

Values:

- `PX` = `0`: Pixels.
- `PERCENTAGE` = `1`: Percent (0-100) of the corresponding video area dimension.
- `LINES` = `2`: Number of text lines (only supported for the region height).

## clpp.text.CueRegion.writingMode (enum)

Writing mode of a region, i.e. the direction in which the cues within the region are stacked.

Values:

- `HORIZONTAL_TOP_TO_BOTTOM` = `column-reverse`: Horizontal text, cues stacked from top to bottom.
- `VERTICAL_LEFT_TO_RIGHT` = `row-reverse`: Vertical text, cues stacked from left to right.
- `VERTICAL_RIGHT_TO_LEFT` = `row`: Vertical text, cues stacked from right to left.

## clpp.text.EdgeType (enum)

The type of edge (outline, shadow, etc.) around subtitle text.

Values:

- `NONE` = `none`: No edge is displayed around text.
- `RAISED` = `raised`: Text is embossed on background.
- `DEPRESSED` = `depressed`: Text is debossed on background.
- `DROP_SHADOW` = `dropshadow`: A fading shadow is casted around text.
- `UNIFORM` = `uniform`: A solid border is around text.

## clpp.thumbnails.Thumbnail (class)

Constructor:

```ts
new clpp.thumbnails.Thumbnail(imageUrl: string, time: number, duration: number, opt_x?: number, opt_y?: number, opt_width?: number, opt_height?: number, opt_cols?: number, opt_rows?: number, opt_gridCol?: number, opt_gridRow?: number, imageElement?: HTMLImageElement)
```

An instance of this class represents a single Thumbnail.

You can get the thumbnail for a specified playback time using the `clpp.thumbnails.ThumbnailsPlugin`. Use `player.getPlugin(clpp.thumbnails.ThumbnailsPlugin.Id)` (`clpp.Player#getPlugin`) to access the plugin.

Parameters:

- `imageUrl` (`string`): The image URL
- `time` (`number`): The start time in seconds for this thumbnail
- `duration` (`number`): The duration in seconds for this thumbnail
- `opt_x` (`number`, optional), default `0`: The x coordinate in the source grid if the source is a grid
- `opt_y` (`number`, optional), default `0`: The y coordinate in the source grid if the source is a grid
- `opt_width` (`number`, optional), default `0`: The width of the thumbnail
- `opt_height` (`number`, optional), default `0`: The height of the thumbnail
- `opt_cols` (`number`, optional), default `1`: The number of columns in a grid
- `opt_rows` (`number`, optional), default `1`: The number of rows in a grid
- `opt_gridCol` (`number`, optional), default `0`: The column index in the grid
- `opt_gridRow` (`number`, optional), default `0`: The row index in the grid
- `imageElement` (`HTMLImageElement`, optional): optional ImageElement to use

Example: Render a thumbnail for position 12 s and 180 px wide.

```js
const thumbnailPlugin = player.getPlugin(clpp.thumbnails.ThumbnailsPlugin.Id);
thumbnailPlugin.get(12)
  .then(thumb => thumb.load())
  .then(thumb => thumb.element(180))
  .then(container.appendChild)
```

### Properties

#### clpp.thumbnails.Thumbnail#time

Type: `number`

The start time of this thumbnail in seconds.

#### clpp.thumbnails.Thumbnail#src

Type: `string`

The URL to the source image. In case of gridded images this points to the grid image. In case of container formats such as BIF, this is not specified

#### clpp.thumbnails.Thumbnail#duration

Type: `number`

The duration of this thumbnail in seconds.

#### clpp.thumbnails.Thumbnail#x

Type: `number`

The x coordinate of the target image in case the thumb source is a grid. This might not be set until the image is loaded.

#### clpp.thumbnails.Thumbnail#y

Type: `number`

The y coordinate of the target image in case the thumb source is a grid. This might not be set until the image is loaded.

#### clpp.thumbnails.Thumbnail#width

Type: `number`

The width of the target image. This might not be set until the image is loaded.

#### clpp.thumbnails.Thumbnail#height

Type: `number`

The height of the target image. This might not be set until the image is loaded.

### Methods

#### clpp.thumbnails.Thumbnail#raw

```ts
raw(): HTMLImageElement
```

Returns the raw image element that holds the thumbnail source. Please note that in case of gridded thumbnails, this is the raw image grid. Make sure the image is loaded using `load()` (`clpp.thumbnails.Thumbnail#load`) before you call this method.

Returns: `HTMLImageElement` - The RAW image element

#### clpp.thumbnails.Thumbnail#element

```ts
element(opt_width?: number, opt_height?: number): HTMLElement
```

Returns a div element that represents the image. You can pass optional width and height to scale the image. If either width or height is undefined or 0, the image will be scaled preserving the aspect ratio.

Make sure the image is loaded using `load()` (`clpp.thumbnails.Thumbnail#load`) before you call this method.

Parameters:

- `opt_width` (`number`, optional): The target width
- `opt_height` (`number`, optional): The target height

Returns: `HTMLElement` - The element that can be added to the DOM to show the thumbnail.

Example: Get an unscaled version of the element.

```js
let container = ...

thumbnail.load().then(() => {
 container.appendChild(thumbnail.element());
})
```

Example: Scale both width and height. This may change the aspect ratio.

```js
let container = ...

thumbnail.load().then(() => {
 container.appendChild(thumbnail.element(100, 80));
})
```

Example: Scale to width of 100 px and preserve the aspect ratio.

```js
let container = ...

thumbnail.load().then(() => {
 container.appendChild(thumbnail.element(100));
})
```

Example: Scale to height of 80 px and preserve the aspect ratio.

```js
let container = ...

thumbnail.load().then(() => {
 container.appendChild(thumbnail.element(0, 80));
})
```

#### clpp.thumbnails.Thumbnail#load

```ts
load(): Promise<clpp.thumbnails.Thumbnail>
```

Returns a promise that resolves when the raw source image is loaded.

Call this method before you access the `raw()` (`clpp.thumbnails.Thumbnail#raw`) or `element()` (`clpp.thumbnails.Thumbnail#element`). The promise will resolve with the load thumbnail to simplify chaining.

Returns: `Promise<clpp.thumbnails.Thumbnail>` - A promise that resolves with this thumbnail once its image is loaded.

Throws:

- `clpp.Error` - `clpp.Error.Code.THUMBNAIL_ERROR` if the thumbnail failed to load

## clpp.thumbnails.ThumbnailsPlugin (class)

Constructor:

```ts
new clpp.thumbnails.ThumbnailsPlugin()
```

The thumbnail plugin can load thumbnails in various formats.

It provides thumbnail images for a given media position via `plugin.get()` (`clpp.thumbnails.ThumbnailsPlugin#get`).

The plugin supports HLS and DASH thumbnails, images and grids of images, as well as side-loaded WebVTT and BIF thumbnails.

Depending on the thumbnail format you might need to use different configuration properties for the `clpp.ThumbnailsConfiguration`.

Once the plugin is configured, you can access it through the player and request thumbnail images for media positions. The examples below use the `thumb.element()` (`clpp.thumbnails.Thumbnail#element`) method to get a DOM element that will render the thumbnail to screen. You can also use properties of `clpp.thumbnails.Thumbnail` and its `thumb.raw()` (`clpp.thumbnails.Thumbnail#raw`) method to access the underlying raw image, for instance if you want to render the image to a canvas. In that case though, be aware that thumbnail images might be gridded and you need to extract the sub-image using the thumbnail properties manually.

Example: Configure the thumbnail plugin.

```js
const configuration = {
  // ...
  thumbnails: {
    url: 'https://demo.cf.castlabs.com/media/Route66/dash/thumbs/$index$_7.jpg',
    duration: 10, // Required for SINGLE and GRID mode
    gridSize: '10x10', // Required for GRID mode
    // Required only if you not use $index$ in the URL template
    templateKey: '$index$',
    mode: 'GRID' // Supports 'GRID', 'SINGLE', 'WEBVTT', 'BIF'
  }
};
player.open(configuration);
```

Example: Access the thumbnail plugin.

```js
const thumbsPlugin = player.getPlugin(clpp.thumbnails.ThumbnailsPlugin.Id);
```

Example: Render a thumbnail for position of 12 s.

```js
thumbsPlugin.get(12)
  .then(thumb => thumb.element(180))
  .then(el => container.appendChild(el));
```

### Static properties

#### clpp.thumbnails.ThumbnailsPlugin.Id

Type: `string`

The thumbnail plugin component ID to access the plugin via `player.getPlugin()` (`clpp.Player#getPlugin`).

### Methods

#### clpp.thumbnails.ThumbnailsPlugin#get

```ts
get(position: number): Promise<clpp.thumbnails.Thumbnail>
```

Request a thumbnail for the given media position in seconds.

Parameters:

- `position` (`number`): The media position in seconds that the thumbnail is requested for.

Returns: `Promise<clpp.thumbnails.Thumbnail>` - The promise that resolves to the loaded thumbnail.

Throws:

- `clpp.Error` - `clpp.Error.Code.THUMBNAIL_ERROR` If `position` is out of bounds or if thumbnail is not found at the given `position` or if the thumbnail format is not supported.

Example: Access the thumbnails plugin and add a thumbnail to a container element, scaling the thumbnail to a width of 180 pixels.

```js
const container = document.getElementById('thumbnail-container');
const thumbsPlugin = player.getPlugin(clpp.thumbnails.ThumbnailsPlugin.Id);

// Get a thumbnail at 12 seconds
thumbsPlugin.get(12)
  .then(thumb => thumb.element(180))
  .then(container.appendChild);
```

## clpp.tizen.TizenComponent (class)

Constructor:

```ts
new clpp.tizen.TizenComponent()
```

This component adds native playback (AVPlay) capabilities on Tizen platforms. This component is useful e.g. for multi-DRM playback of asset on legacy Tizen platforms or Tizen versions with limited support for MSE/EME APIs.

If the component is in use, native playback will be preferred over MSE/EME based playback on Tizen version 2.x.

NOTE: This component depends on the MSE module. Make sure `cl.mse.js` is loaded before this component.

Example: Add support for Tizen 2

```js
clpp.install(clpp.tizen.TizenComponent);
```

## clpp.ttml (namespace)

TTML subtitles functionality.

## clpp.ttml.TtmlComponent (class)

Constructor:

```ts
new clpp.ttml.TtmlComponent()
```

This component adds the capability to display TTML subtitles.

Example:

```js
import "@castlabs/prestoplay/cl.ttml";
```

## clpp.utils.BufferUtils (class)

Constructor:

```ts
new clpp.utils.BufferUtils()
```

Set of buffer utility functions.

### Static methods

#### clpp.utils.BufferUtils.equal

```ts
equal(arr1: BufferSource | null, arr2: BufferSource | null): boolean
```

Compare two buffers for equality.  For buffers of different types, this compares the underlying buffers as binary data.

Parameters:

- `arr1` (`BufferSource | null`): The first buffer, or null.
- `arr2` (`BufferSource | null`): The second buffer, or null.

Returns: `boolean` - True if both buffers contain the same bytes or both are null.

#### clpp.utils.BufferUtils.toUint8Array

```ts
toUint8Array(data: BufferSource, offset?: number, length?: number): Uint8Array
```

Creates a new Uint8Array view on the same buffer. This clamps the values to be within the same view (i.e. you can't use this to move past the end of the view, even if the underlying buffer is larger). However, you can pass a negative offset to access the data before the view.

Parameters:

- `data` (`BufferSource`): The buffer or view to create the view on.
- `offset` (`number`, optional), default `0`: The offset into `data`, in bytes. Defaults to 0.
- `length` (`number`, optional), default `Infinity`: The maximum length of the view, in bytes. Defaults to the rest of `data`.

Returns: `Uint8Array` - A new Uint8Array sharing the underlying buffer of `data`.

#### clpp.utils.BufferUtils.toUint16Array

```ts
toUint16Array(data: BufferSource, offset?: number, length?: number): Uint16Array
```

Creates a new Uint16Array view on the same buffer. This clamps the values to be within the same view (i.e. you can't use this to move past the end of the view, even if the underlying buffer is larger). However, you can pass a negative offset to access the data before the view.

Parameters:

- `data` (`BufferSource`): The buffer or view to create the view on.
- `offset` (`number`, optional), default `0`: The offset into `data`, in Uint16 elements. Defaults to 0.
- `length` (`number`, optional), default `Infinity`: The maximum length of the view, in Uint16 elements. Defaults to the rest of `data`.

Returns: `Uint16Array` - A new Uint16Array sharing the underlying buffer of `data`.

#### clpp.utils.BufferUtils.toUint32Array

```ts
toUint32Array(data: BufferSource, offset?: number, length?: number): Uint32Array
```

Creates a new Uint32Array view on the same buffer. This clamps the values to be within the same view (i.e. you can't use this to move past the end of the view, even if the underlying buffer is larger). However, you can pass a negative offset to access the data before the view.

Parameters:

- `data` (`BufferSource`): The buffer or view to create the view on.
- `offset` (`number`, optional), default `0`: The offset into `data`, in Uint32 elements. Defaults to 0.
- `length` (`number`, optional), default `Infinity`: The maximum length of the view, in Uint32 elements. Defaults to the rest of `data`.

Returns: `Uint32Array` - A new Uint32Array sharing the underlying buffer of `data`.

#### clpp.utils.BufferUtils.toInt32Array

```ts
toInt32Array(data: BufferSource, offset?: number, length?: number): Int32Array
```

Creates a new Int32Array view on the same buffer. This clamps the values to be within the same view (i.e. you can't use this to move past the end of the view, even if the underlying buffer is larger). However, you can pass a negative offset to access the data before the view.

Parameters:

- `data` (`BufferSource`): The buffer or view to create the view on.
- `offset` (`number`, optional), default `0`: The offset into `data`, in Int32 elements. Defaults to 0.
- `length` (`number`, optional), default `Infinity`: The maximum length of the view, in Int32 elements. Defaults to the rest of `data`.

Returns: `Int32Array` - A new Int32Array sharing the underlying buffer of `data`.

#### clpp.utils.BufferUtils.toDataView

```ts
toDataView(buffer: BufferSource, offset?: number, length?: number): DataView
```

Creates a DataView over the given buffer. The values are clamped to be within the given view, like in `clpp.utils.BufferUtils.toUint8Array`.

Parameters:

- `buffer` (`BufferSource`): The buffer or view to create the DataView on.
- `offset` (`number`, optional), default `0`: The offset into `buffer`, in bytes. Defaults to 0.
- `length` (`number`, optional), default `Infinity`: The maximum length of the DataView, in bytes. Defaults to the rest of `buffer`.

Returns: `DataView` - A new DataView sharing the underlying buffer of `buffer`.

#### clpp.utils.BufferUtils.toArrayBuffer

```ts
toArrayBuffer(view: BufferSource): ArrayBuffer
```

Gets an ArrayBuffer that contains the data from the given TypedArray.  Note this will allocate a new ArrayBuffer if the object is a partial view of the data.

Parameters:

- `view` (`BufferSource`): The ArrayBuffer or view to get the data from.

Returns: `ArrayBuffer` - The given ArrayBuffer, the view's underlying buffer if the view spans all of it, or otherwise a new ArrayBuffer with a copy of the data.

## clpp.utils.FairplayUtils (class)

Constructor:

```ts
new clpp.utils.FairplayUtils()
```

This class is a set of utility functions to help work with common Apple FairPlay Streaming (FPS) DRM tasks.

### Static methods

#### clpp.utils.FairplayUtils.extractExtXKeyUri

```ts
extractExtXKeyUri(skdInitData: BufferSource): string
```

Extracts #EXT-X-KEY:URI string from initData. e.g. skd://d192ebad-5097

Parameters:

- `skdInitData` (`BufferSource`): The initData of `skd` initDataType

Returns: `string` - The `#EXT-X-KEY:URI` extracted from the initData

#### clpp.utils.FairplayUtils.extractContentId

```ts
extractContentId(skdInitData: BufferSource): string
```

Default Content ID extraction method according to Apple's FairPlay Streaming examples. It takes initData of `skd` initDataType. It extracts a hostname part from HLS `#EXT-X-KEY:URI`.

E.g. if FPS encrypted playlist has the HLS #EXT-X-KEY tag:

```js
#EXT-X-KEY:METHOD=SAMPLE-AES,URI="skd://d192ebad-5097",
KEYFORMAT="com.apple.streamingkeydelivery",KEYFORMATVERSIONS="1"
```

then the Content ID extracted with this method will be:

```
d192ebad-5097
```

If your FPS license server is expecting other Content ID than this, you should use custom `clpp.drm.ContentIdExtractor` modifier for your `clpp.FairplayDrmSystem`.

In the most advanced configurations you could also decide to implement a custom `clpp.drm.InitDataTransformer` which allows you to directly parse and manipulate initData and construct a custom payload for a Key Session to provide context for message exchange with the FPS CDM. Based on that payload FPS CDM will return a SPC payload you could then send to the license server.

Parameters:

- `skdInitData` (`BufferSource`): The initData of `skd` initDataType

Returns: `string` - Content ID extracted from the initData

#### clpp.utils.FairplayUtils.createFairplayPayload

```ts
createFairplayPayload(skdInitData: BufferSource, contentId: BufferSource | string, certificate: BufferSource | null): Uint8Array
```

Default FairPlay payload creator according to Apple's FairPlay examples. It takes:

- the initData of `skd` initDataType;
- Content ID previously extracted from the initData using `clpp.utils.FairplayUtils.extractContentId`, custom `clpp.drm.ContentIdExtractor` or delivered by other means;
- the server certificate.

It returns a binary payload which is the result of concatenation of all these inputs in the following format:

```
[4 bytes] initDataSize
[initDataSize bytes] initData
[4 bytes] contentIdSize
[contentIdSize bytes] contentId
[4 bytes] certificateSize
[certificateSize bytes] certificate
```

This payload is then meant to be used to create a new MediaKeySession.

**Note:** This version of FairPlay payload format is dedicated to use with older Apple's [WebKit-prefixed EME](https://dvcs.w3.org/hg/html-media/raw-file/tip/encrypted-media/encrypted-media.html) in Safari browser.

Parameters:

- `skdInitData` (`BufferSource`): The initData of `skd` initDataType
- `contentId` (`BufferSource | string`): The Content ID
- `certificate` (`BufferSource | null`): The server certificate.

Returns: `Uint8Array` - The binary payload which is the result of concatenation of all the input parameters in the defined format.

Throws:

- `clpp.Error` with the code

  - `clpp.Error.Code.SERVER_CERTIFICATE_REQUIRED` when the server certificate is not provided.

#### clpp.utils.FairplayUtils.formatFairPlayRequest

```ts
formatFairPlayRequest(request: clpp.net.Request)
```

Default FairPlay license request formatter based on Apple's FairPlay Streaming examples. It modifies the request in place: the SPC body is base64url-encoded and sent as the `spc` form field with the `application/x-www-form-urlencoded` content type.

Parameters:

- `request` (`clpp.net.Request`): The license request to modify.

#### clpp.utils.FairplayUtils.parseFairPlayResponse

```ts
parseFairPlayResponse(response: clpp.net.Response)
```

Default FairPlay license response parser based on Apple's FairPlay Streaming examples. It modifies the response in place: the base64-encoded CKC is extracted from a plain, `<ckc>`-wrapped or JSON (`ckc`, `CkcMessage` or `License` field) text response and decoded to binary. Non-text responses are left unchanged.

Parameters:

- `response` (`clpp.net.Response`): The license response to modify.

## clpp.utils.Mp4Parser (class)

Constructor:

```ts
new clpp.utils.Mp4Parser()
```

Create a new MP4 Parser.

### Static methods

#### clpp.utils.Mp4Parser.children

```ts
children(box: clpp.ParsedMp4Box)
```

A callback that tells the Mp4 parser to treat the body of a box as a series of boxes. The number of boxes is limited by the size of the parent box.

Parameters:

- `box` (`clpp.ParsedMp4Box`): The parent box whose payload contains the child boxes.

#### clpp.utils.Mp4Parser.sampleDescription

```ts
sampleDescription(box: clpp.ParsedMp4Box)
```

A callback that tells the Mp4 parser to treat the body of a box as a sample description. A sample description box has a fixed number of children. The number of children is represented by a 4 byte unsigned integer. Each child is a box.

Parameters:

- `box` (`clpp.ParsedMp4Box`): The sample description box.

#### clpp.utils.Mp4Parser.allData

```ts
allData(callback: function): clpp.utils.Mp4Parser.CallbackType
```

Create a callback that tells the Mp4 parser to treat the body of a box as a binary blob and to parse the body's contents using the provided callback.

Parameters:

- `callback` (`function`): The callback called with the remaining payload of the box.

Returns: `clpp.utils.Mp4Parser.CallbackType` - A box callback to pass to `clpp.utils.Mp4Parser#box` or `clpp.utils.Mp4Parser#fullBox`.

#### clpp.utils.Mp4Parser.typeToString

```ts
typeToString(type: number): string
```

Convert an integer type from a box into an ascii string name. Useful for debugging.

Parameters:

- `type` (`number`): The type of the box, a uint32.

Returns: `string` - The four-character box name, e.g. `moov`.

#### clpp.utils.Mp4Parser.headerSize

```ts
headerSize(box: clpp.ParsedMp4Box): number
```

Find the header size of the box. Useful for modifying boxes in place or finding the exact offset of a field.

Parameters:

- `box` (`clpp.ParsedMp4Box`): The parsed box.

Returns: `number` - The header size in bytes, including the 64-bit size field and the version and flags of a full box, if present.

### Methods

#### clpp.utils.Mp4Parser#box

```ts
box(type: string, definition: clpp.utils.Mp4Parser.CallbackType): clpp.utils.Mp4Parser
```

Declare a box type as a Box.

Parameters:

- `type` (`string`): The four-character box type, e.g. `moov`.
- `definition` (`clpp.utils.Mp4Parser.CallbackType`): The callback called for each box of this type.

Returns: `clpp.utils.Mp4Parser` - This parser, to allow chaining.

#### clpp.utils.Mp4Parser#fullBox

```ts
fullBox(type: string, definition: clpp.utils.Mp4Parser.CallbackType): clpp.utils.Mp4Parser
```

Declare a box type as a Full Box. A full box has a version and flags field after the basic box header.

Parameters:

- `type` (`string`): The four-character box type, e.g. `tenc`.
- `definition` (`clpp.utils.Mp4Parser.CallbackType`): The callback called for each box of this type.

Returns: `clpp.utils.Mp4Parser` - This parser, to allow chaining.

#### clpp.utils.Mp4Parser#stop

```ts
stop()
```

Stop parsing. Useful for extracting information from partial segments and avoiding an out-of-bounds error once you find what you are looking for.

#### clpp.utils.Mp4Parser#parse

```ts
parse(data: BufferSource, partialOkay?: boolean)
```

Parse the given data using the added callbacks.

Parameters:

- `data` (`BufferSource`): The MP4 data to parse.
- `partialOkay` (`boolean`, optional): If true, allow reading partial payloads from some boxes. If the goal is a child box, we can sometimes find it without enough data to find all child boxes.

#### clpp.utils.Mp4Parser#parseNext

```ts
parseNext(absStart: number, reader: clpp.utils.dataview.DataViewReader, partialOkay?: boolean)
```

Parse the next box on the current level.

Parameters:

- `absStart` (`number`): The absolute start position in the original byte array.
- `reader` (`clpp.utils.dataview.DataViewReader`): The reader positioned at the start of the next box.
- `partialOkay` (`boolean`, optional): If true, allow reading partial payloads from some boxes. If the goal is a child box, we can sometimes find it without enough data to find all child boxes.

## clpp.utils.Mp4Parser.CallbackType (callback)

```ts
function(box: clpp.ParsedMp4Box): any
```

A callback that is called by `clpp.utils.Mp4Parser` for each parsed box of the type it was registered for.

Parameters:

- `box` (`clpp.ParsedMp4Box`): The parsed box.

Returns: `any` - Any value. The return value is ignored by the parser.

## clpp.utils.Platform (class)

Constructor:

```ts
new clpp.utils.Platform()
```

A wrapper for platform-specific functions.

### Static methods

#### clpp.utils.Platform.getInfo

```ts
getInfo(): clpp.PlatformInfo
```

Returns platform object that provides information about the current operating system and browsers.

Returns: `clpp.PlatformInfo` - The platform information

## clpp.utils.PlayerConfiguration (class)

Constructor:

```ts
new clpp.utils.PlayerConfiguration()
```

Utilities for working with player configuration.

### Static methods

#### clpp.utils.PlayerConfiguration.create

```ts
create(...configs: Array<unknown>): clpp.PlayerConfiguration
```

**Deprecated.**

Creates a configuration out of the data object and the default configuration.

Parameters:

- `...configs` (`Array<unknown>`): The configuration objects to merge into the defaults, in order. A string is treated as a `source` URL.

Returns: `clpp.PlayerConfiguration` - The merged player configuration.

## clpp.utils.Timer (class)

Constructor:

```ts
new clpp.utils.Timer(onTick: function)
```

A timer allows a single function to be executed at a later time or at regular intervals.

Create a new timer. A timer is committed to a single callback function. While there is no technical reason to do this, it is far easier to understand and use timers when they are connected to one functional idea.

Parameters:

- `onTick` (`function`): The function called each time the timer ticks.

### Methods

#### clpp.utils.Timer#tickNow

```ts
tickNow(): clpp.utils.Timer
```

Have the timer call |onTick| now.

Returns: `clpp.utils.Timer` - timer

#### clpp.utils.Timer#tickAfter

```ts
tickAfter(seconds: number): clpp.utils.Timer
```

Have the timer call |onTick| after |seconds| has elapsed unless |stop| is called first. Any previously scheduled tick is cancelled.

Parameters:

- `seconds` (`number`): The delay before the tick, in seconds.

Returns: `clpp.utils.Timer` - This timer, to allow chaining.

#### clpp.utils.Timer#tickEvery

```ts
tickEvery(seconds: number): clpp.utils.Timer
```

Have the timer call |onTick| every |seconds| until |stop| is called. Any previously scheduled tick is cancelled.

Parameters:

- `seconds` (`number`): The interval between ticks, in seconds.

Returns: `clpp.utils.Timer` - This timer, to allow chaining.

#### clpp.utils.Timer#stop

```ts
stop()
```

Stop the timer and clear the previous behavior. The timer is still usable after calling |stop|.

## clpp.utils.Uint8ArrayUtils (class)

Constructor:

```ts
new clpp.utils.Uint8ArrayUtils()
```

This class contains Uint8Array utilities.

### Static methods

#### clpp.utils.Uint8ArrayUtils.toBase64Url

```ts
toBase64Url(data: BufferSource, opt_padding?: boolean): string
```

Convert a Uint8Array to a base64 string.  The output will always use the alternate encoding/alphabet also known as "base64url".

Parameters:

- `data` (`BufferSource`): The binary data to encode.
- `opt_padding` (`boolean`, optional), default `true`: If true, pad the output with equals signs. Defaults to true.

Returns: `string` - The base64url-encoded string.

#### clpp.utils.Uint8ArrayUtils.fromBase64

```ts
fromBase64(str: string): Uint8Array
```

Convert a base64 string to a Uint8Array.  Accepts either the standard alphabet or the alternate "base64url" alphabet.

Parameters:

- `str` (`string`): The base64 or base64url-encoded string.

Returns: `Uint8Array` - A new Uint8Array with the decoded bytes.

#### clpp.utils.Uint8ArrayUtils.fromHex

```ts
fromHex(str: string): Uint8Array
```

Convert a hex string to a Uint8Array.

Parameters:

- `str` (`string`): The hex string, with two hex digits per byte and no prefix.

Returns: `Uint8Array` - A new Uint8Array with the decoded bytes.

#### clpp.utils.Uint8ArrayUtils.toHex

```ts
toHex(arr: Uint8Array): string
```

Convert a Uint8Array to a hex string.

Parameters:

- `arr` (`Uint8Array`): The bytes to encode.

Returns: `string` - The lowercase hex string, with two digits per byte.

#### clpp.utils.Uint8ArrayUtils.equal

```ts
equal(arr1: Uint8Array | null, arr2: Uint8Array | null): boolean
```

Compare two Uint8Arrays for equality.

Parameters:

- `arr1` (`Uint8Array | null`): The first array, or null.
- `arr2` (`Uint8Array | null`): The second array, or null.

Returns: `boolean` - True if both arrays contain the same bytes or both are null.

#### clpp.utils.Uint8ArrayUtils.concat

```ts
concat(...arrays: Array<Uint8Array>): Uint8Array
```

Concatenate Uint8Arrays.

Parameters:

- `...arrays` (`Array<Uint8Array>`): The arrays to concatenate, in order.

Returns: `Uint8Array` - A new Uint8Array containing the bytes of all given arrays.

#### clpp.utils.Uint8ArrayUtils.toStandardBase64

```ts
toStandardBase64(data: BufferSource): string
```

Convert a Uint8Array to a base64 string. The output will be standard alphabet as opposed to base64url safe alphabet.

Parameters:

- `data` (`BufferSource`): The binary data to encode.

Returns: `string` - The base64-encoded string, with padding.

## clpp.utils.dataview.DataViewReader (class)

Constructor:

```ts
new clpp.utils.dataview.DataViewReader(dataView: DataView, endian?: boolean)
```

DataView Reader is an abstraction over DataView which adds a couple of utilities and introduces a cursor which moves forward on each read thus providing something like an iterator interface.

Creates a DataViewReader, which abstracts a DataView object.

Parameters:

- `dataView` (`DataView`): The data view
- `endian` (`boolean`, optional), default `true`: Endianness, by default little endian. True for little endian, false for big endian.

## clpp.utils.media (namespace)

Utilities for working with media.

### Static methods

#### clpp.utils.media.detectType

```ts
detectType(url: string): clpp.Type | null
```

Tries to detect the media type from the URL. i.e. detecting whether it is an MP4, DASH or HLS, manifest URL.

Parameters:

- `url` (`string`): The source URL

Returns: `clpp.Type | null` - The detected type of the URL or null if the type could not be identified

## clpp.utils.obj (namespace)

Utilities for working with objects.

### Static methods

#### clpp.utils.obj.cloneItem

```ts
cloneItem(item: T): T
```

Clones the given object. This creates a copy for primitives or plain objects.

Parameters:

- `item` (`T`): the item to clone

Returns: `T` - the cloned item

#### clpp.utils.obj.merge

```ts
merge(...args: Array<Record<string, unknown>>): Record<string, unknown>
```

Merge multiple plain objects from left to right. This copies over primitive values, plain Objects, functions, DOM Elements and arrays.

If an item is null or undefined, it is ignored.

Parameters:

- `...args` (`Array<Record<string, unknown>>`): two or more objects to be merged

Returns: `Record<string, unknown>` - merged object

## clpp.utils.strings (namespace)

Utilities for working with strings.

### Static methods

#### clpp.utils.strings.fromUtf8

```ts
fromUtf8(data: BufferSource | null): string
```

Creates a string from the given buffer as UTF-8 encoding.

Parameters:

- `data` (`BufferSource | null`): binary data encoded as UTF-8

Returns: `string` - text

Throws:

- `clpp.Error` With code `clpp.Error.Code.BAD_ENCODING` if it cannot decode the string, e.g. the buffer is not UTF-8

#### clpp.utils.strings.fromBytesAutoDetect

```ts
fromBytesAutoDetect(sourceData: BufferSource | string | null, escapeStr?: boolean): string
```

Creates a string from the given buffer, auto-detecting the encoding. If it cannot detect the encoding, it will throw an exception.

Parameters:

- `sourceData` (`BufferSource | string | null`): The bytes to decode. A string is returned unchanged.
- `escapeStr` (`boolean`, optional): If true, the decoded string is escaped with the global `escape()` function.

Returns: `string` - The decoded string.

Throws:

- `clpp.Error` With code

  - `clpp.Error.Code.UNABLE_TO_DETECT_ENCODING` if the text encoding cannot be detected, or `clpp.Error.Code.BAD_ENCODING` if the data cannot be decoded in the detected encoding.

#### clpp.utils.strings.toUtf8

```ts
toUtf8(str: string): Uint8Array
```

Creates a Uint8Array from the given string, converting to UTF-8 encoding.

Parameters:

- `str` (`string`): The string to encode.

Returns: `Uint8Array` - The UTF-8 encoded bytes.

#### clpp.utils.strings.toUtf16

```ts
toUtf16(str: string, littleEndian: boolean): ArrayBuffer
```

Creates a ArrayBuffer from the given string, converting to UTF-16 encoding.

Parameters:

- `str` (`string`): The string to encode.
- `littleEndian` (`boolean`): If true, the bytes are written in little-endian order, otherwise in big-endian order.

Returns: `ArrayBuffer` - The UTF-16 encoded bytes, without a byte order mark.

#### clpp.utils.strings.toByteArray

```ts
toByteArray(s: string, opt_size?: number): ArrayBuffer
```

Converts an ASCII string to a byte array. ASCII is converted using the specified number of bytes per character.

Parameters:

- `s` (`string`): The string
- `opt_size` (`number`, optional), default `1`: Number of bytes per character

Returns: `ArrayBuffer` - A buffer holding one element of `opt_size` bytes, in platform byte order, per character.

#### clpp.utils.strings.startsWith

```ts
startsWith(str: string, query: string): boolean
```

Returns true if the given string starts with the given query.

Parameters:

- `str` (`string`): The source string which we search in
- `query` (`string`): The target string that we search for

Returns: `boolean` - True if `str` starts with `query`.

#### clpp.utils.strings.endsWith

```ts
endsWith(str: string, query: string): boolean
```

Returns true if the given string ends with the given query.

Parameters:

- `str` (`string`): The source string which we search in
- `query` (`string`): The target string that we search for

Returns: `boolean` - True if `str` ends with `query`.

#### clpp.utils.strings.bitrateToString

```ts
bitrateToString(bps: number | string | null): string
```

Takes a bitrate and returns a string representation. Units are in bps, Kbps, Mbps.

Parameters:

- `bps` (`number | string | null`): The bitrate in bps

Returns: `string` - The string representation of the given bitrate or empty string

#### clpp.utils.strings.durationToString

```ts
durationToString(duration: number, opt_format?: string): string
```

Translates a duration in seconds to a human readable format.

You can use the following format specifiers:

- `%h` for Hours
- `%m` for Minutes
- `%s` for Seconds

The formatters can be repeated to pad the output. For example, `'%m'` will return '1' if you pass 60 seconds, while `'%mm'` will left pad the output and return '01'.

Parameters:

- `duration` (`number`): The duration in seconds
- `opt_format` (`string`, optional), default `%h:%mm:%ss`: The output format

Returns: `string` - The formatted duration as a string

#### clpp.utils.strings.hashCode

```ts
hashCode(str: string): number
```

Generate the hash code from the given input.

Parameters:

- `str` (`string`): the input string

Returns: `number` - the hash code

## clpp.verimatrix.Vcas (class)

Constructor:

```ts
new clpp.verimatrix.Vcas(vcasConfig: clpp.VerimatrixVcasConfiguration)
```

The Verimatrix VCAS Ultra DRM environment.

It can be used as a stand-alone or in conjunction with `clpp.verimatrix.VcasComponent`.

Parameters:

- `vcasConfig` (`clpp.VerimatrixVcasConfiguration`): The VCAS configuration, e.g. the device ID and the license server URLs.

### Static properties

#### clpp.verimatrix.Vcas.NAME

Type: `string`

The name of this DRM environment.

## clpp.verimatrix.Vcas.FairPlayAssetIdStrategy (enum)

FairPlay assetId acquisition strategy.

Values:

- `KEYID` = `keyid`: AssetId will be retrieved from HLS playlist #EXT-X-KEY:URI

  E.g. if your HLS playlist ` #EXT-X-KEY` tag is:

  ```
  #EXT-X-KEY:METHOD=SAMPLE-AES,URI="skd://b63831eed2170ce1235b167a9a6d6802",KEYFORMAT="com.apple.streamingkeydelivery",KEYFORMATVERSIONS="1"
  ```

  Then the extracted assetId will be: `b63831eed2170ce1235b167a9a6d6802`

  This is the default strategy.
- `CONTENTID_SITEID` = `contentid-siteid`: AssetId will consist of a contentId (such as the name of the content item) and a siteId:

  ```
  assetId: r=<contentId>&s=<siteId>
  ```

  where:

  - <contentId> = URL encoded content identifier (SMSCONTENTID).
  - <siteId> = Unique identifier of the site to which the subscriber is associated.

  E.g. if `contentId = "sample test"` and `siteId = 123`, then the assetId is `r=sample%20test&s=123`

## clpp.verimatrix.Vcas.LicenseRequestHttpHeader (enum)

License request custom headers identifiers.

Values:

- `DEVICE_ID_HEADER` = `DeviceId`: Device ID custom HTTP header
- `AUTHENTICATOR_HEADER` = `Authenticator`: Authenticator custom HTTP header

## clpp.verimatrix.Vcas.LicenseRequestVuidLocation (enum)

Methods for passing VUID to the license servers. Methods for passing the device's Verimatrix unique identifier (VUID) (`deviceId`) and optional third-party authentication to the Subscriber Management System (SMS) (`authenticator`) to the license servers.

Values:

- `QUERY_STRING` = `query-string`: Pass VUID in the license server URL query string.
- `HTTP_HEADER` = `http-header`: Pass VUID in the license request HTTP headers.

## clpp.verimatrix.VcasComponent (class)

Constructor:

```ts
new clpp.verimatrix.VcasComponent()
```

This component adds Verimatrix VCAS Ultra support to the player.

Example: Use Verimatrix Component

```js
import "@castlabs/prestoplay/cl.verimatrix";

// Acquire license
player.open({
  source: 'https://your.server/encyrpted-asset.mpd',
  drm: {
    env: 'VerimatrixVCAS',
    customData: {
      deviceId: "myDeviceID",
      authenticator: "myAuthenticatorToken",
      widevineLicenseUrl: 'https://widevine.keyserver:port/',
      playReadyLicenseUrl: 'https://playready.keyserver:port/',
      fairPlayLicenseUrl: 'https://fairplay.keyserver:port/',
      fairPlayCertificateUrl: 'https://fairplay.cert/fairplay.cer'
    }
  }
});
```

## clpp.vr.VrPlugin (class)

Constructor:

```ts
new clpp.vr.VrPlugin()
```

Adds 360-degree video playback support to the player. Once loaded the plugin feature needs to be enabled in the player configuration.

The plugin can be configured to add mouse and touch listeners to the canvas that is used to render the VR environment. The default mouse listeners will move the camera around both while dragging the mouse and on touch events. This behavior can be turned off and instead the camera can be moved with custom logic using `clpp.vr.VrPlugin#moveCamera`.

To use this plugin, make sure you load the `cl.vr` module and enable to plugin in your player configuration.

Example: Enable the VR Plugin

```js
import '@castlabs/prestoplay/cl.vr'
...
player.open({
  source: 'https://demo.cf.castlabs.com/public/Client/tmp/marathon-hls/playlist.m3u8',
  muted: true,
  autoplay: true,
  vr: {
    enable: true,
    attachMouseListener: true
  }
})
```

Example: Change sensitivity of mouse/touch control or invert mouse/touch controls

```js
import '@castlabs/prestoplay/cl.vr'
...
player.open({
  source: 'https://demo.cf.castlabs.com/public/Client/tmp/marathon-hls/playlist.m3u8',
  muted: true,
  autoplay: true,
  vr: {
    enable: true,
    attachMouseListener: true
    sensitivity: 1.5, // increase the sensitivity of mouse controls
    invertHorizontalControl: true // invert the horizontal axis movement
    invertVerticalControl: true // invert the vertical axis movement
  }
})
```

Example: Access the plugin and change the camera angle

```js
import '@castlabs/prestoplay/cl.vr'
...
player.open({
  source: 'https://demo.cf.castlabs.com/public/Client/tmp/marathon-hls/playlist.m3u8',
  muted: true,
  autoplay: true,
  vr: {
    enable: true,
    // we do not want the default mouse listeners attached
    attachMouseListener: false
  }
})

// instead of the default mouse listeners, we manually change where the
// camera looks at.
//
// For that we get the instance of the plugin
const vrPlugin = player.getPlugin(clpp.vr.VrPlugin.Id);
// and move the camera to the left
const coords = vrPlugin.getCameraCoordinates();
vrPlugin.moveCamera(coords.x + 5, coords.y);
```

### Static properties

#### clpp.vr.VrPlugin.Id

Type: `string`

The ID of the VR plugin, e.g. to get the plugin instance with `clpp.Player#getPlugin`.

### Methods

#### clpp.vr.VrPlugin#moveCamera

```ts
moveCamera(x: number, y: number)
```

Update the camera position.

Parameters:

- `x` (`number`): The horizontal rotation (yaw) of the camera in degrees.
- `y` (`number`): The vertical rotation (pitch) of the camera in degrees.

#### clpp.vr.VrPlugin#getCameraCoordinates

```ts
getCameraCoordinates(): Object
```

Get the current camera coordinates.

Returns: `Object` - An object containing number attributes "x" and "y" which correspond to the degrees of rotation of the camera along the "x" and "y" axis.

#### clpp.vr.VrPlugin#setCameraFieldOfView

```ts
setCameraFieldOfView(fov: number)
```

Set the camera field of view. A smaller value will "zoom in" and a larger value will "zoom out" and provide a larger field of view.

Parameters:

- `fov` (`number`): The vertical field of view in degrees.

## clpp.vtt (namespace)

WebVTT and SRT subtitles functionality.

## clpp.vtt.VttComponent (class)

Constructor:

```ts
new clpp.vtt.VttComponent()
```

This component adds the capability to display WebVTT and SRT subtitles.

Example:

```js
import "@castlabs/prestoplay/cl.vtt";
```

## clpp.yospace (namespace)

Yospace analytics.

## clpp.yospace.StreamType (enum)

Yospace Stream type.

Values:

- `VOD` = `VOD`: Video on demand stream, played in a Yospace VOD session.
- `LIVE` = `LIVE`: Live stream, played in a Yospace live session.
- `DVR` = `DVR`: Live stream with seekable DVR window, played in a Yospace DVR live session.

## clpp.yospace.YospacePlugin (class)

Constructor:

```ts
new clpp.yospace.YospacePlugin()
```

Yospace plugin.

This plugin integrates the Yospace Ad Management SDK with PRESTOplay for web. The Yospace SDK provides analytics and playback policy management for Yospace streams.

### Static properties

#### clpp.yospace.YospacePlugin.Id

Type: `string`

The ID of the Yospace plugin, e.g. to get the plugin instance with `clpp.Player#getPlugin`.

### Methods

#### clpp.yospace.YospacePlugin#getSession

```ts
getSession(): YospaceAdManagement.Session | null
```

Get the current [Yospace playback session](https://developer.yospace.com/sdk-documentation/javascript/api/yosdk/latest/Session.html).

Returns: `YospaceAdManagement.Session | null` - the current session

## clpp.AdobeConfiguration (typedef)

**Deprecated.** This is deprecated and will be removed in next major version.

Configuration section for the Adobe analytics plugin.

Properties:

- `enabled` (`boolean`, optional), default `true`: Enables the Adobe analytics plugin.

## clpp.VimondConfiguration (typedef)

**Deprecated.** This is deprecated and will be removed in next major version.

Configuration section for Vimond analytics. For more information please visit the [Vimond Player Session API](https://vimond-experience-api.readme.io/docs/player-session-api).

Properties:

- `authToken` (`string`, optional): The authentication token acquired from the Vimond Token Service.
- `playerEventRequest` (`clpp.VimondPlayerEventRequest`, optional): The response acquired from the Vimond Play Service.
- `failIfUnreachable` (`boolean`, optional), default `true`: Stop playback if can't connect to Vimond Player Session. For example request timeout or request blocked by an ad block.
- `failOnError` (`boolean`, optional), default `true`: Stop playback if Vimond Player Session returns 400/401/403/5xx.

## clpp.YouboraConfiguration (typedef)

**Deprecated.** Use `clpp.NpawConfiguration` instead, it is a newer version of the same plugins.

Configuration section for Youbora analytics. In addition to the listed options, all options defined by Nice People At Work are available and will be passed over to Youboralib.

Please remember to include Youbora SDK in order to use Youbora analytics. For more information please visit the [NPAW Developer Site](https://documentation.npaw.com/integration-docs/docs/setting-options-and-metadata).

Properties:

- `accountCode` (`string`): Account code for Youbora analytics.
- `errorFilter` (`clpp.YouboraErrorFilter`, optional): A custom function that converts a `clpp.Error` to a payload for Youbora. If it returns `null`, the error will not be sent.
- `disabledSubtitlesLabel` (`string`, optional), default `"off"`: This label is used to identify disabled subtitles.

## clpp.adobe.AdobeAnalyticsPlugin (class)

Constructor:

```ts
new clpp.adobe.AdobeAnalyticsPlugin()
```

**Deprecated.** This is deprecated and will be removed in next major version.

Adobe Analytics plugin. Depends on `s.Media` API only, does not use Media Analytics API v3 or earlier.

### Static properties

#### clpp.adobe.AdobeAnalyticsPlugin.Id

Type: `string`

The ID of the Adobe Analytics plugin, e.g. to get the plugin instance with `clpp.Player#getPlugin`.

## clpp.drm.DrmToday.Environment (enum)

**Deprecated.**

DRMtoday environment names.

Use these constants to specify which DRMtoday environment you are using when preparing the player for DRM protected playback with DRMtoday

Values:

- `PRODUCTION` = `PRODUCTION`: The DRMtoday production environment.
- `STAGING` = `STAGING`: The DRMtoday staging environment.
- `DEMO` = `DEMO`: The DRMtoday demo environment.
- `TEST` = `TEST`: The DRMtoday test environment.

## clpp.htmlcue.HtmlTextDisplayer (class)

**Deprecated.**

HTML Text Displayer.

This is a custom implementation of a subtitle renderer, which displays subtitles using basic HTML and CSS. It provides great compatibility with old browsers and is especially useful on platforms that do not support the `HTMLTrackElement`.

Note that this text displayer is not supported on iOS due to its limited fullscreen API.

### Methods

#### clpp.htmlcue.HtmlTextDisplayer#append

```ts
append(cues: Array<clpp.text.Cue>, styles: Array<string>)
```

Append given text cues to the list of cues to be displayed.

Parameters:

- `cues` (`Array<clpp.text.Cue>`): Text cues to be appended.
- `styles` (`Array<string>`): Styles to be applied.

#### clpp.htmlcue.HtmlTextDisplayer#destroy

```ts
destroy(): Promise<void>
```

Request that this object be destroyed, releasing all resources and shutting down all operations. Returns a Promise which is resolved when destruction is complete. This Promise should never be rejected.

Returns: `Promise<void>` - A promise that resolves once the displayer is destroyed.

#### clpp.htmlcue.HtmlTextDisplayer#remove

```ts
remove(start: number, end: number): boolean
```

Remove the cues that lie entirely within the given time range, i.e. cues that start at or after `start` and end before `end`.

Parameters:

- `start` (`number`): Start of the time range in seconds.
- `end` (`number`): End of the time range in seconds.

Returns: `boolean` - False if the displayer was already destroyed, true otherwise.

#### clpp.htmlcue.HtmlTextDisplayer#isTextVisible

```ts
isTextVisible(): boolean
```

Check whether text rendering is enabled.

Returns: `boolean` - True if text is currently shown, false if it is hidden.

#### clpp.htmlcue.HtmlTextDisplayer#setTextVisibility

```ts
setTextVisibility(on: boolean)
```

Show or hide the rendered text. Hiding stops caption updates and clears the displayed cues; showing resumes updates and renders the current cues. Does nothing if the displayer was destroyed.

Parameters:

- `on` (`boolean`): True to show text, false to hide it.

## clpp.vimond.VimondPlugin (class)

Constructor:

```ts
new clpp.vimond.VimondPlugin()
```

**Deprecated.** This is deprecated and will be removed in next major version.

Vimond plugin.

### Static properties

#### clpp.vimond.VimondPlugin.Id

Type: `string`

The ID of the Vimond plugin, e.g. to get the plugin instance with `clpp.Player#getPlugin`.

### Methods

#### clpp.vimond.VimondPlugin#updateAuthToken

```ts
updateAuthToken(authToken: string)
```

Update the auth token.

The auth token may expire during playback. Pass a fresh auth token regularly to prevent failure.

Parameters:

- `authToken` (`string`): Authentication token
