Skip to content

Module: src/core/Media

The Media component is the heart of the player, as it controls the actual video. Also provides the media state and the basic media API to the player, and also wraps the various media events in publish topics. Note: this component is mandatory and required for normal player operations, so it cannot be switched off.

Version
1.1.0
Author
Frank Kudermann - alphanull
License
MIT
Requires
object
AsyncTask
ExtendedMediaError
Source
Media.js, line 17

Constructor

new Media(player, parent, optionsopt)

Creates an instance of the Media component.

Parameters:
Name Type Attributes Description
player Player

The player instance.

parent Player

Reference to the parent instance.

options Object optional

Additional options.

Parameters:
Name Type Attributes Description
apiKey symbol optional

Token for extended access to the player API.

Throws

If trying to disable this component.

Type Error

Members

Holds the instance configuration for this component.

Properties
Name Type Attributes Default Description
autoPlay boolean optional false

If true, the video plays as soon as it is loaded.

autoMute boolean optional true

If true, the player will automatically mute and retry playback if autoplay fails.

loop boolean optional false

If true, the video is loop.

muted boolean optional false

Sets the initial mute state of the media.

volume number optional 1

Sets the initial volume (range 0 to 1).

preload string optional 'metadata'

Determines how much of the data is preloaded. Possible values: 'metadata', 'auto' or 'none'. It is strongly recommended to leave this setting as it is, as many components require to have metadata loaded. In addition, not all browsers behave identically here, some seem to simply ignore values like „none“.

crossOrigin string optional 'anonymous'

Use 'anonymous' or 'use-credentials' to enable CORS support.

stallTimeout number optional 2

Timeout (in seconds) after which the stall event is triggered. Use 0 to disable stall checks.

Type
Object
Source
Media.js, line 31

Reference to the main player instance.

Type
Player
Source
Media.js, line 46

Holds tokens of subscriptions to player events, for later unsubscribe.

Type
Array<number>
Source
Media.js, line 52

Secret key only known to the player instance and initialized components. Used to be able to restrict access to API methods in conjunction with secure mode.

Type
symbol
Source
Media.js, line 59

A Map of registered plugins that may handle special media types or override source logic.

Type
Map
Source
Media.js, line 65

The current state of the Media. All of its properties should be using a getter, but no setter, so the state is always readonly in effect. Use the players' getState() API to read from this object.

Properties
Name Type Description
src string

The current media source URL.

width number

Original width of the video in pixels.

height number

Original height of the video in pixels.

preload string

Preload setting of the media element.

networkState number

Network state of the media element.

readyState number

Ready state of the media element.

error Object

Current error object if any, otherwise this returns 'null'.

duration number

Total duration of the current media in seconds.

currentTime number

Current playhead position, in seconds.

remainingTime number

Current remaining time (duration - currentTime), in seconds.

paused boolean

Whether the media is currently paused.

ended boolean

Whether the media has ended.

loop boolean

Whether looping is enabled.

muted boolean

Whether the media is muted.

volume number

The current volume, ranges from 0 (silent) to 1 (full Volume).

playbackRate number

The current playback speed (1 means normal speed).

seeking boolean

Whether the media is currently seeking.

seekable TimeRanges

Seekable time ranges.

buffered TimeRanges

Buffered time ranges.

played TimeRanges

Played time ranges.

liveStream boolean

Whether the media is a live stream.

frameRate number

The frameRate of the current stream (might not always be available).

Type
Object
Source
Media.js, line 94

Picture-in-Picture support flags for the current environment.

Type
Object
Source
Media.js, line 100

If loading a new source, the current state may be needed to be restored. If that's the case, the former state is saved in this object.

Properties
Name Type Attributes Description
src string

The src of the stream.

time number nullable

The currentTime value of the former media state.

paused boolean

Set to 'true' if the former media state was paused.

play boolean

If 'true', play when restoring.

ignoreAutoplay boolean

If 'true', ingore autoPlay when restoring.

Type
Object
Source
Media.js, line 112

Object containing stall related data.

Properties
Name Type Description
state 'clear' | 'delaying' | 'stalled'

Indicates current stall status: can be 'clear', 'delaying', or 'stalled'.

preStallTime number

Stores the playback time just before stalling begins, for stall detection logic.

checkId number

Timeout id for stall check.

Type
Object
Source
Media.js, line 124

Holds metadata information provided by media.load and loaded metadata.

Type
Media~metaData
Source
Media.js, line 134

Reference to the Async Task instance. Used to handle async tasks, which can be cancelled, resolved or rejected.

Type
AsyncTask
Source
Media.js, line 140

The underlying video element.

Type
HTMLVideoElement
Source
Media.js, line 146

This is a list of supported events by this engine. Corresponds to the HTML5 media event names.

Type
Array<string>
Source
Media.js, line 815

Methods

canPlay(metaData) → string

In essence, this is just a wrapper for the media elements' 'canPlay' method.

Parameters:
Name Type Description
metaData Media~metaData

The data to test.

Returns

Results are: 'probably': The specified media type appears to be playable. 'maybe': Cannot tell if the media type is playable without playing it. '' (empty string): The specified media type definitely cannot be played.

Type string
Source
Media.js, line 216

static registerPlugin(plugin)

Registers a new plugin. Plugins can 'takeover' certain functions, esp media.load to add their own functionality Used by Components like Dash or Hls.

Parameters:
Name Type Description
plugin Object

The plugin to add.

Source
Media.js, line 234

unregisterPlugin(plugin)

UNRegisters a plugin.

Parameters:
Name Type Description
plugin Object

The plugin to remove.

Source
Media.js, line 244

private #setupSubscriptions()

Wires Media to core player events, mainly to track stall state. Subscribes once and stores the unsubscribe callbacks for cleanup.

Source
Media.js, line 254

private #onDataReady()

Sets up the engine as soon as the media data is available.

Listens
data/ready
Source
Media.js, line 273

private #load(metaData, optionsopt) → Promise

Sets a new source for the media, in effect loading the video or audio. May delegate to plugins for formats with certain mine types and / or extensions.

Parameters:
Name Type Attributes Description
metaData Media~metaData

The source to load.

options Media~mediaLoadOptions optional

Options to control additional behavior.

Returns

A promise that resolves with the loaded metadata or rejects with the resulting media error.

Type Promise
Source
Media.js, line 305

private #onLoaded()

This method is called when a new source was successfully loaded. If saved state is found, it also tries to restore the former state (like the currentTime by seeking).

Fires
media/ready
Source
Media.js, line 363

private #getMetaData() Media~metaData

Returns a cpoy of the current media metadata.

Returns

Object with current metadata.

Type Media~metaData
Source
Media.js, line 410

private #play() → Promise|undefined

Starts playing the media.

Returns

If browser supports it, returns the play() promise.

Type Promise | undefined
Source
Media.js, line 416

private #pause()

Pauses the current media.

Source
Media.js, line 428

private #loop(doLoop)

Disables or enables looping.

Parameters:
Name Type Description
doLoop boolean

If true, media is looping.

Fires
media/loop
Source
Media.js, line 439

private #playbackRate(rate)

Changes current playback rate.

Parameters:
Name Type Description
rate number

The new rate to set.

Source
Media.js, line 450

private #seek(position)

Seeks the media to the specified position. This method also tries to mitigate rounding errors when frame precise seeking is required.

Parameters:
Name Type Description
position number

The position (measured in seconds) to seek to.

Source
Media.js, line 460

private #volume(vol)

Sets a new volume.

Parameters:
Name Type Description
vol number

The new volume, number should be in the range of 0...1.

Source
Media.js, line 485

private #mute(doMute)

Mutes, or unmutes the media.

Parameters:
Name Type Description
doMute boolean

If true, media is muted, otherwise it is unmuted.

Source
Media.js, line 496

private #requestPictureInPicture() → Promise<void>

Requests Picture-in-Picture if supported.

Returns
Type Promise<void>
Source
Media.js, line 506

private #exitPictureInPicture() → Promise<void>

Exits Picture-in-Picture if active.

Returns
Type Promise<void>
Source
Media.js, line 522

private #onStall()

Called when certain events indicate the stream might be stalling (e.g. Waiting, play).

Listens
media/waiting
media/play
Source
Media.js, line 539

private #onStallEnd()

Called when events suggest the stalling might have ended (e.g. Timeupdate, pause, data/ready).

Listens
media/pause
media/ready
media/playing
media/timeupdate
data/ready
Source
Media.js, line 575

private #onStreamEvent(event)

This listens to native media events and sends them through the pubsub library in order to abstract and wrap the native HTML5 media events. Any components should avoid listening to the native event directly on the video element, but subscribe to the various events emitted here.

Parameters:
Name Type Description
event Event

The native HTML5 media event.

Fires
media/abort
media/canplay
media/canplaythrough
media/durationchange
media/emptied
media/ended
media/error
media/loadeddata
media/loadedmetadata
media/loadstart
media/play
media/pause
media/progress
media/ratechange
media/seeked
media/seeking
media/stalled
media/suspend
media/timeupdate
media/volumechange
media/waiting
media/webkitbeginfullscreen
media/webkitendfullscreen
Source
Media.js, line 617

private #getMediaElement(apiKey) → HTMLElement

Used by components to retrieve the video element.

Parameters:
Name Type Description
apiKey symbol

Token needed to grant access in secure mode.

Returns

The element designated by the component as attachable container.

Type HTMLElement
Throws

If safe mode access was denied.

Type Error
Source
Media.js, line 660

private #enableElement()

Enables the media element, ie adds event listeners and sets the state functions.

Source
Media.js, line 670

private #disableElement()

Disables the media element, ie removes all event listeners and clears the state.

Source
Media.js, line 720

private #removeElement()

Removes the old media element, unsubscribes from native events, and clears state.

Source
Media.js, line 746

enable(options)

Enables the media engine.

Parameters:
Name Type Description
options Object

The options for the enable method.

Parameters:
Name Type Description
resume boolean

If true, the media will be resumed.

params Object

The parameters for the enable method.

Source
Media.js, line 760

disable(options)

Disables the media engine.

Parameters:
Name Type Description
options Object

The options for the disable method.

Parameters:
Name Type Description
suspend boolean

If true, the media will be suspended.

Source
Media.js, line 788

destroy()

This method removes all events, subscriptions and DOM nodes created by this component.

Source
Media.js, line 800

Type Definitions

The mediaSource is a representation of the currently selected media source.

Properties
Name Type Attributes Description
src string

The source url of the video (can be absolute, relative or blob:).

mediaType 'video' | 'audio'

The type of the current media (currently 'video' or 'audio' is supported).

mimeType string

The mimetype, optionally extended with codec param if available.

encodings Array<Object> optional

Available additional encodings.

Properties
Name Type Attributes Description
src string

Contains the encodings' Source.

mimeType string optional

Contains the encodings' Mime-Type.

width number optional

Width of the video in pixel.

height number optional

Height of the video in pixel.

frameRate number optional

Framerate of the video (might not always be available).

bitRate number optional

Bitrate of the video (might not always be available).

language string optional

The language of the current media.

langId string | number optional

The language id of the current media.

langName string optional

The language (extended) name of the current media.

Type
Object
Source
Media.js, line 1003
Properties
Name Type Attributes Default Description
rememberState boolean optional false

If true, player will attempt to restore seek position and play state after setting the new source. Useful for lang / quality switches.

ignoreAutoplay boolean optional false

If true, player does NOT autoplay if player was paused during the switch.

play boolean optional false

If true, stream is automatically played after switching, ignoring the play state before switch.

seek number optional 0

If number, stream is seeked to the specified position after loading.

Type
Object
Source
Media.js, line 1021

Events

media/ready

media/abort

This corresponds to the standard HTML5 media 'abort' event (wrapped by the pubsub engine).

Source
Media.js, line 854

media/canplay

media/canplaythrough

This corresponds to the standard HTML5 media 'canplaythrough' event (wrapped by the pubsub engine).

Source
Media.js, line 864

media/error

media/durationchange

This corresponds to the standard HTML5 media 'durationchange' event (wrapped by the pubsub engine).

Source
Media.js, line 874

media/emptied

This corresponds to the standard HTML5 media 'emptied' event (wrapped by the pubsub engine).

Source
Media.js, line 879

media/ended

This corresponds to the standard HTML5 media 'ended' event (wrapped by the pubsub engine).

Listeners
MediaSession#updatePlaybackState
Playlist#onMediaEnded
Overlays#update
UI#releaseWakeLock
Source
Media.js, line 884

media/loadstart

This corresponds to the standard HTML5 media 'loadstart' event (wrapped by the pubsub engine).

Source
Media.js, line 889

media/loadeddata

This corresponds to the standard HTML5 media 'loadeddata' event (wrapped by the pubsub engine).

Source
Media.js, line 894

media/loadedmetadata

This corresponds to the standard HTML5 media 'loadedmetadata' event (wrapped by the pubsub engine).

Source
Media.js, line 899

media/play

media/pause

media/playing

This corresponds to the standard HTML5 media 'playing' event (wrapped by the pubsub engine).

Listeners
Media#onStallEnd
Source
Media.js, line 914

media/progress

This corresponds to the standard HTML5 media 'progress' event (wrapped by the pubsub engine).

Listeners
Scrubber#render
Source
Media.js, line 919

media/ratechange

This corresponds to the standard HTML5 media 'ratechange' event (wrapped by the pubsub engine).

Listeners
ChromeCast#onPlaybackRateChange
PlaybackRate#onRateChange
Source
Media.js, line 924

media/seeked

This corresponds to the standard HTML5 media 'seeked' event (wrapped by the pubsub engine).

Listeners
Scrubber#render
Overlays#update
AnalyserVideo#refresh
VisualizerAmbient#refresh
Source
Media.js, line 929

media/seeking

This corresponds to the standard HTML5 media 'seeking' event (wrapped by the pubsub engine).

Source
Media.js, line 934

media/stalled

This corresponds to the standard HTML5 media 'stalled' event (wrapped by the pubsub engine).

Source
Media.js, line 939

media/suspend

This corresponds to the standard HTML5 media 'suspend' event (wrapped by the pubsub engine).

Source
Media.js, line 944

media/timeupdate

This corresponds to the standard HTML5 media 'timeupdate' event (wrapped by the pubsub engine).

Listeners
MediaSession#onTimeUpdate
Scrubber#onTimeUpdate
Media#onStallEnd
Chapters#onTimeUpdate
Overlays#update
Time#onTimeUpdate
Source
Media.js, line 949

media/volumechange

This corresponds to the standard HTML5 media 'volumechange' event (wrapped by the pubsub engine).

Listeners
Volume#onVolumeUpdate
Source
Media.js, line 954

media/waiting

This corresponds to the standard HTML5 media 'waiting' event (wrapped by the pubsub engine).

Listeners
Media#onStall
Source
Media.js, line 959

media/loop

This event is fired when looping starts or ends.

Listeners
Loop#onLoopChange
Source
Media.js, line 964

media/webkitbeginfullscreen

This event is fired by iOS only, when the media tag enters fullscreen. (On these systems, only the media itself can enter fullscreen, not an arbitrary HTML element).

Listeners
FullScreen#enterFullScreen
Source
Media.js, line 969

media/webkitendfullscreen

This event is fired by iOS only, when the media tag leaves fullscreen. (On these systems, only the media itself can enter fullscreen, not an arbitrary HTML element).

Listeners
FullScreen#exitFullScreen
Source
Media.js, line 975

media/enterpictureinpicture

This event is fired when the media enters Picture in Picture mode.

Listeners
PictureInPicture#onPipEnter
VisualizerAmbient#stopLoop
Source
Media.js, line 981

media/leavepictureinpicture

This event is fired when the media leaves Picture in Picture mode.

Listeners
PictureInPicture#onPipExit
VisualizerAmbient#startLoop
Source
Media.js, line 986

media/stall/begin

Fired when media playback begins to stall, usually because bandwidth is not sufficient to achieve continuous playback, or also if the buffer is not filled with data yet. Note that there are similar media events like 'stalled', but these are not really reliable and browser implementation varies. This event tries to solve these inconsistencies and should also cover edge cases the browser don't handle.

Listeners
Quality#onStallBegin
Spinner#show
Source
Media.js, line 991

media/stall/end

Fired when media playback has recovered from stalling and is playing (or playable when paused) again.

Listeners
Quality#onStallEnd
Spinner#hide
Source
Media.js, line 998