dashjs
Version:
A reference client implementation for the playback of MPEG DASH via Javascript and compliant browsers.
1,064 lines (950 loc) • 106 kB
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>dash.js Source: streaming/MediaPlayer.js</title>
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link type="text/css" rel="stylesheet" href="styles/sunlight.default.css">
<link type="text/css" rel="stylesheet" href="styles/site.spacelab.css">
</head>
<body>
<div class="navbar navbar-default navbar-fixed-top navbar-inverse">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="index.html">dash.js</a>
<button class="navbar-toggle" type="button" data-toggle="collapse" data-target="#topNavigation">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div class="navbar-collapse collapse" id="topNavigation">
<ul class="nav navbar-nav">
<li class="dropdown">
<a href="modules.list.html" class="dropdown-toggle" data-toggle="dropdown">Modules<b class="caret"></b></a>
<ul class="dropdown-menu ">
<li><a href="module-DashAdapter.html">DashAdapter</a></li><li><a href="module-DashMetrics.html">DashMetrics</a></li><li><a href="module-MediaPlayer.html">MediaPlayer</a></li><li><a href="module-OfflineController.html">OfflineController</a></li><li><a href="module-ProtectionController.html">ProtectionController</a></li><li><a href="module-Settings.html">Settings</a></li>
</ul>
</li>
<li class="dropdown">
<a href="classes.list.html" class="dropdown-toggle" data-toggle="dropdown">Classes<b class="caret"></b></a>
<ul class="dropdown-menu ">
<li><a href="Errors.html">Errors</a></li><li><a href="MediaPlayerEvents.html">MediaPlayerEvents</a></li><li><a href="MediaPlayerModel.html">MediaPlayerModel</a></li><li><a href="MetricsReportingEvents.html">MetricsReportingEvents</a></li><li><a href="MssErrors.html">MssErrors</a></li><li><a href="OfflineErrors.html">OfflineErrors</a></li><li><a href="OfflineEvents.html">OfflineEvents</a></li><li><a href="ProtectionErrors.html">ProtectionErrors</a></li><li><a href="ProtectionEvents.html">ProtectionEvents</a></li>
</ul>
</li>
<li class="dropdown">
<a href="events.list.html" class="dropdown-toggle" data-toggle="dropdown">Events<b class="caret"></b></a>
<ul class="dropdown-menu ">
<li><a href="MediaPlayerEvents.html#event:ADAPTATION_SET_REMOVED_NO_CAPABILITIES">MediaPlayerEvents#event:ADAPTATION_SET_REMOVED_NO_CAPABILITIES</a></li><li><a href="MediaPlayerEvents.html#event:AST_IN_FUTURE">MediaPlayerEvents#event:AST_IN_FUTURE</a></li><li><a href="MediaPlayerEvents.html#event:BUFFER_EMPTY">MediaPlayerEvents#event:BUFFER_EMPTY</a></li><li><a href="MediaPlayerEvents.html#event:BUFFER_LEVEL_STATE_CHANGED">MediaPlayerEvents#event:BUFFER_LEVEL_STATE_CHANGED</a></li><li><a href="MediaPlayerEvents.html#event:BUFFER_LEVEL_UPDATED">MediaPlayerEvents#event:BUFFER_LEVEL_UPDATED</a></li><li><a href="MediaPlayerEvents.html#event:BUFFER_LOADED">MediaPlayerEvents#event:BUFFER_LOADED</a></li><li><a href="MediaPlayerEvents.html#event:CAN_PLAY">MediaPlayerEvents#event:CAN_PLAY</a></li><li><a href="MediaPlayerEvents.html#event:CAN_PLAY_THROUGH">MediaPlayerEvents#event:CAN_PLAY_THROUGH</a></li><li><a href="MediaPlayerEvents.html#event:CAPTION_CONTAINER_RESIZE">MediaPlayerEvents#event:CAPTION_CONTAINER_RESIZE</a></li><li><a href="MediaPlayerEvents.html#event:CAPTION_RENDERED">MediaPlayerEvents#event:CAPTION_RENDERED</a></li><li><a href="MediaPlayerEvents.html#event:CONFORMANCE_VIOLATION">MediaPlayerEvents#event:CONFORMANCE_VIOLATION</a></li><li><a href="MediaPlayerEvents.html#event:CONTENT_STEERING_REQUEST_COMPLETED">MediaPlayerEvents#event:CONTENT_STEERING_REQUEST_COMPLETED</a></li><li><a href="MediaPlayerEvents.html#event:DYNAMIC_TO_STATIC">MediaPlayerEvents#event:DYNAMIC_TO_STATIC</a></li><li><a href="MediaPlayerEvents.html#event:ERROR">MediaPlayerEvents#event:ERROR</a></li><li><a href="MediaPlayerEvents.html#event:EVENT_MODE_ON_RECEIVE">MediaPlayerEvents#event:EVENT_MODE_ON_RECEIVE</a></li><li><a href="MediaPlayerEvents.html#event:EVENT_MODE_ON_START">MediaPlayerEvents#event:EVENT_MODE_ON_START</a></li><li><a href="MediaPlayerEvents.html#event:FRAGMENT_LOADING_ABANDONED">MediaPlayerEvents#event:FRAGMENT_LOADING_ABANDONED</a></li><li><a href="MediaPlayerEvents.html#event:FRAGMENT_LOADING_COMPLETED">MediaPlayerEvents#event:FRAGMENT_LOADING_COMPLETED</a></li><li><a href="MediaPlayerEvents.html#event:FRAGMENT_LOADING_PROGRESS">MediaPlayerEvents#event:FRAGMENT_LOADING_PROGRESS</a></li><li><a href="MediaPlayerEvents.html#event:FRAGMENT_LOADING_STARTED">MediaPlayerEvents#event:FRAGMENT_LOADING_STARTED</a></li><li><a href="MediaPlayerEvents.html#event:LOG">MediaPlayerEvents#event:LOG</a></li><li><a href="MediaPlayerEvents.html#event:MANIFEST_LOADED">MediaPlayerEvents#event:MANIFEST_LOADED</a></li><li><a href="MediaPlayerEvents.html#event:MANIFEST_VALIDITY_CHANGED">MediaPlayerEvents#event:MANIFEST_VALIDITY_CHANGED</a></li><li><a href="MediaPlayerEvents.html#event:METRIC_ADDED">MediaPlayerEvents#event:METRIC_ADDED</a></li><li><a href="MediaPlayerEvents.html#event:METRIC_CHANGED">MediaPlayerEvents#event:METRIC_CHANGED</a></li><li><a href="MediaPlayerEvents.html#event:METRIC_UPDATED">MediaPlayerEvents#event:METRIC_UPDATED</a></li><li><a href="MediaPlayerEvents.html#event:METRICS_CHANGED">MediaPlayerEvents#event:METRICS_CHANGED</a></li><li><a href="MediaPlayerEvents.html#event:PERIOD_SWITCH_COMPLETED">MediaPlayerEvents#event:PERIOD_SWITCH_COMPLETED</a></li><li><a href="MediaPlayerEvents.html#event:PERIOD_SWITCH_STARTED">MediaPlayerEvents#event:PERIOD_SWITCH_STARTED</a></li><li><a href="MediaPlayerEvents.html#event:PLAYBACK_ENDED">MediaPlayerEvents#event:PLAYBACK_ENDED</a></li><li><a href="MediaPlayerEvents.html#event:PLAYBACK_ERROR">MediaPlayerEvents#event:PLAYBACK_ERROR</a></li><li><a href="MediaPlayerEvents.html#event:PLAYBACK_LOADED_DATA">MediaPlayerEvents#event:PLAYBACK_LOADED_DATA</a></li><li><a href="MediaPlayerEvents.html#event:PLAYBACK_METADATA_LOADED">MediaPlayerEvents#event:PLAYBACK_METADATA_LOADED</a></li><li><a href="MediaPlayerEvents.html#event:PLAYBACK_NOT_ALLOWED">MediaPlayerEvents#event:PLAYBACK_NOT_ALLOWED</a></li><li><a href="MediaPlayerEvents.html#event:PLAYBACK_PAUSED">MediaPlayerEvents#event:PLAYBACK_PAUSED</a></li><li><a href="MediaPlayerEvents.html#event:PLAYBACK_PLAYING">MediaPlayerEvents#event:PLAYBACK_PLAYING</a></li><li><a href="MediaPlayerEvents.html#event:PLAYBACK_PROGRESS">MediaPlayerEvents#event:PLAYBACK_PROGRESS</a></li><li><a href="MediaPlayerEvents.html#event:PLAYBACK_RATE_CHANGED">MediaPlayerEvents#event:PLAYBACK_RATE_CHANGED</a></li><li><a href="MediaPlayerEvents.html#event:PLAYBACK_SEEKED">MediaPlayerEvents#event:PLAYBACK_SEEKED</a></li><li><a href="MediaPlayerEvents.html#event:PLAYBACK_SEEKING">MediaPlayerEvents#event:PLAYBACK_SEEKING</a></li><li><a href="MediaPlayerEvents.html#event:PLAYBACK_STALLED">MediaPlayerEvents#event:PLAYBACK_STALLED</a></li><li><a href="MediaPlayerEvents.html#event:PLAYBACK_STARTED">MediaPlayerEvents#event:PLAYBACK_STARTED</a></li><li><a href="MediaPlayerEvents.html#event:PLAYBACK_TIME_UPDATED">MediaPlayerEvents#event:PLAYBACK_TIME_UPDATED</a></li><li><a href="MediaPlayerEvents.html#event:PLAYBACK_VOLUME_CHANGED">MediaPlayerEvents#event:PLAYBACK_VOLUME_CHANGED</a></li><li><a href="MediaPlayerEvents.html#event:PLAYBACK_WAITING">MediaPlayerEvents#event:PLAYBACK_WAITING</a></li><li><a href="MediaPlayerEvents.html#event:QUALITY_CHANGE_RENDERED">MediaPlayerEvents#event:QUALITY_CHANGE_RENDERED</a></li><li><a href="MediaPlayerEvents.html#event:QUALITY_CHANGE_REQUESTED">MediaPlayerEvents#event:QUALITY_CHANGE_REQUESTED</a></li><li><a href="MediaPlayerEvents.html#event:REPRESENTATION_SWITCH">MediaPlayerEvents#event:REPRESENTATION_SWITCH</a></li><li><a href="MediaPlayerEvents.html#event:STREAM_ACTIVATED">MediaPlayerEvents#event:STREAM_ACTIVATED</a></li><li><a href="MediaPlayerEvents.html#event:STREAM_DEACTIVATED">MediaPlayerEvents#event:STREAM_DEACTIVATED</a></li><li><a href="MediaPlayerEvents.html#event:STREAM_INITIALIZED">MediaPlayerEvents#event:STREAM_INITIALIZED</a></li><li><a href="MediaPlayerEvents.html#event:STREAM_INITIALIZING">MediaPlayerEvents#event:STREAM_INITIALIZING</a></li><li><a href="MediaPlayerEvents.html#event:STREAM_TEARDOWN_COMPLETE">MediaPlayerEvents#event:STREAM_TEARDOWN_COMPLETE</a></li><li><a href="MediaPlayerEvents.html#event:STREAM_UPDATED">MediaPlayerEvents#event:STREAM_UPDATED</a></li><li><a href="MediaPlayerEvents.html#event:TEXT_TRACK_ADDED">MediaPlayerEvents#event:TEXT_TRACK_ADDED</a></li><li><a href="MediaPlayerEvents.html#event:TEXT_TRACKS_ADDED">MediaPlayerEvents#event:TEXT_TRACKS_ADDED</a></li><li><a href="MediaPlayerEvents.html#event:TRACK_CHANGE_RENDERED">MediaPlayerEvents#event:TRACK_CHANGE_RENDERED</a></li><li><a href="MediaPlayerEvents.html#event:TTML_PARSED">MediaPlayerEvents#event:TTML_PARSED</a></li><li><a href="MediaPlayerEvents.html#event:TTML_TO_PARSE">MediaPlayerEvents#event:TTML_TO_PARSE</a></li><li><a href="MetricsReportingEvents.html#event:CMCD_DATA_GENERATED">MetricsReportingEvents#event:CMCD_DATA_GENERATED</a></li><li><a href="OfflineEvents.html#event:OFFLINE_RECORD_FINISHED">OfflineEvents#event:OFFLINE_RECORD_FINISHED</a></li><li><a href="OfflineEvents.html#event:OFFLINE_RECORD_LOADEDMETADATA">OfflineEvents#event:OFFLINE_RECORD_LOADEDMETADATA</a></li><li><a href="OfflineEvents.html#event:OFFLINE_RECORD_STARTED">OfflineEvents#event:OFFLINE_RECORD_STARTED</a></li><li><a href="OfflineEvents.html#event:OFFLINE_RECORD_STOPPED">OfflineEvents#event:OFFLINE_RECORD_STOPPED</a></li><li><a href="ProtectionEvents.html#event:KEY_ADDED">ProtectionEvents#event:KEY_ADDED</a></li><li><a href="ProtectionEvents.html#event:KEY_ERROR">ProtectionEvents#event:KEY_ERROR</a></li><li><a href="ProtectionEvents.html#event:KEY_MESSAGE">ProtectionEvents#event:KEY_MESSAGE</a></li><li><a href="ProtectionEvents.html#event:KEY_SESSION_CLOSED">ProtectionEvents#event:KEY_SESSION_CLOSED</a></li><li><a href="ProtectionEvents.html#event:KEY_SESSION_CREATED">ProtectionEvents#event:KEY_SESSION_CREATED</a></li><li><a href="ProtectionEvents.html#event:KEY_SESSION_REMOVED">ProtectionEvents#event:KEY_SESSION_REMOVED</a></li><li><a href="ProtectionEvents.html#event:KEY_STATUSES_CHANGED">ProtectionEvents#event:KEY_STATUSES_CHANGED</a></li><li><a href="ProtectionEvents.html#event:KEY_SYSTEM_SELECTED">ProtectionEvents#event:KEY_SYSTEM_SELECTED</a></li><li><a href="ProtectionEvents.html#event:LICENSE_REQUEST_COMPLETE">ProtectionEvents#event:LICENSE_REQUEST_COMPLETE</a></li><li><a href="ProtectionEvents.html#event:LICENSE_REQUEST_SENDING">ProtectionEvents#event:LICENSE_REQUEST_SENDING</a></li><li><a href="ProtectionEvents.html#event:PROTECTION_CREATED">ProtectionEvents#event:PROTECTION_CREATED</a></li><li><a href="ProtectionEvents.html#event:PROTECTION_DESTROYED">ProtectionEvents#event:PROTECTION_DESTROYED</a></li>
</ul>
</li>
<li class="dropdown">
<a href="global.html" class="dropdown-toggle" data-toggle="dropdown">Global<b class="caret"></b></a>
<ul class="dropdown-menu ">
<li><a href="global.html#LICENSE_SERVER_MANIFEST_CONFIGURATIONS">LICENSE_SERVER_MANIFEST_CONFIGURATIONS</a></li>
</ul>
</li>
</ul>
<div class="col-sm-3 col-md-3">
<form class="navbar-form" role="search">
<div class="input-group">
<input type="text" class="form-control" placeholder="Search" name="q" id="search-input">
<div class="input-group-btn">
<button class="btn btn-default" id="search-submit"><i class="glyphicon glyphicon-search"></i></button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<div class="container" id="toc-content">
<div class="row">
<div class="col-md-12">
<div id="main">
<h1 class="page-title">Source: streaming/MediaPlayer.js</h1>
<section>
<article>
<pre
class="sunlight-highlight-javascript linenums">/**
* The copyright in this software is being made available under the BSD License,
* included below. This software may be subject to other third party and contributor
* rights, including patent rights, and no such rights are granted under this license.
*
* Copyright (c) 2013, Dash Industry Forum.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
* * Neither the name of Dash Industry Forum nor the names of its
* contributors may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
import cea608parser from '../../externals/cea608-parser';
import Constants from './constants/Constants';
import DashConstants from '../dash/constants/DashConstants';
import MetricsConstants from './constants/MetricsConstants';
import PlaybackController from './controllers/PlaybackController';
import StreamController from './controllers/StreamController';
import GapController from './controllers/GapController';
import CatchupController from './controllers/CatchupController';
import ServiceDescriptionController from '../dash/controllers/ServiceDescriptionController';
import ContentSteeringController from '../dash/controllers/ContentSteeringController';
import MediaController from './controllers/MediaController';
import BaseURLController from './controllers/BaseURLController';
import ManifestLoader from './ManifestLoader';
import ErrorHandler from './utils/ErrorHandler';
import Capabilities from './utils/Capabilities';
import CapabilitiesFilter from './utils/CapabilitiesFilter';
import RequestModifier from './utils/RequestModifier';
import URIFragmentModel from './models/URIFragmentModel';
import ManifestModel from './models/ManifestModel';
import MediaPlayerModel from './models/MediaPlayerModel';
import AbrController from './controllers/AbrController';
import SchemeLoaderFactory from './net/SchemeLoaderFactory';
import VideoModel from './models/VideoModel';
import CmcdModel from './models/CmcdModel';
import DOMStorage from './utils/DOMStorage';
import Debug from './../core/Debug';
import Errors from './../core/errors/Errors';
import EventBus from './../core/EventBus';
import Events from './../core/events/Events';
import MediaPlayerEvents from './MediaPlayerEvents';
import FactoryMaker from '../core/FactoryMaker';
import Settings from '../core/Settings';
import {
getVersionString
}
from '../core/Version';
//Dash
import SegmentBaseController from '../dash/controllers/SegmentBaseController';
import DashAdapter from '../dash/DashAdapter';
import DashMetrics from '../dash/DashMetrics';
import TimelineConverter from '../dash/utils/TimelineConverter';
import {
HTTPRequest
} from './vo/metrics/HTTPRequest';
import BASE64 from '../../externals/base64';
import ISOBoxer from 'codem-isoboxer';
import DashJSError from './vo/DashJSError';
import {checkParameterType} from './utils/SupervisorTools';
import ManifestUpdater from './ManifestUpdater';
import URLUtils from '../streaming/utils/URLUtils';
import BoxParser from './utils/BoxParser';
import TextController from './text/TextController';
import CustomParametersModel from './models/CustomParametersModel';
/**
* The media types
* @typedef {("video" | "audio" | "text" | "image")} MediaType
*/
/**
* @module MediaPlayer
* @description The MediaPlayer is the primary dash.js Module and a Facade to build your player around.
* It will allow you access to all the important dash.js properties/methods via the public API and all the
* events to build a robust DASH media player.
*/
function MediaPlayer() {
/**
* @constant {string} STREAMING_NOT_INITIALIZED_ERROR error string thrown when a function is called before the dash.js has been fully initialized
* @inner
*/
const STREAMING_NOT_INITIALIZED_ERROR = 'You must first call initialize() and set a source before calling this method';
/**
* @constant {string} PLAYBACK_NOT_INITIALIZED_ERROR error string thrown when a function is called before the dash.js has been fully initialized
* @inner
*/
const PLAYBACK_NOT_INITIALIZED_ERROR = 'You must first call initialize() and set a valid source and view before calling this method';
/**
* @constant {string} ELEMENT_NOT_ATTACHED_ERROR error string thrown when a function is called before the dash.js has received a reference of an HTML5 video element
* @inner
*/
const ELEMENT_NOT_ATTACHED_ERROR = 'You must first call attachView() to set the video element before calling this method';
/**
* @constant {string} SOURCE_NOT_ATTACHED_ERROR error string thrown when a function is called before the dash.js has received a valid source stream.
* @inner
*/
const SOURCE_NOT_ATTACHED_ERROR = 'You must first call attachSource() with a valid source before calling this method';
/**
* @constant {string} MEDIA_PLAYER_NOT_INITIALIZED_ERROR error string thrown when a function is called before the dash.js has been fully initialized.
* @inner
*/
const MEDIA_PLAYER_NOT_INITIALIZED_ERROR = 'MediaPlayer not initialized!';
const context = this.context;
const eventBus = EventBus(context).getInstance();
let settings = Settings(context).getInstance();
const debug = Debug(context).getInstance({ settings: settings });
let instance,
logger,
source,
protectionData,
mediaPlayerInitialized,
streamingInitialized,
playbackInitialized,
autoPlay,
abrController,
schemeLoaderFactory,
timelineConverter,
mediaController,
protectionController,
metricsReportingController,
mssHandler,
offlineController,
adapter,
mediaPlayerModel,
customParametersModel,
errHandler,
baseURLController,
capabilities,
capabilitiesFilter,
streamController,
textController,
gapController,
playbackController,
serviceDescriptionController,
contentSteeringController,
catchupController,
dashMetrics,
manifestModel,
cmcdModel,
videoModel,
uriFragmentModel,
domStorage,
segmentBaseController;
/*
---------------------------------------------------------------------------
INIT FUNCTIONS
---------------------------------------------------------------------------
*/
function setup() {
logger = debug.getLogger(instance);
mediaPlayerInitialized = false;
playbackInitialized = false;
streamingInitialized = false;
autoPlay = true;
protectionController = null;
offlineController = null;
protectionData = null;
adapter = null;
segmentBaseController = null;
Events.extend(MediaPlayerEvents);
mediaPlayerModel = MediaPlayerModel(context).getInstance();
customParametersModel = CustomParametersModel(context).getInstance();
videoModel = VideoModel(context).getInstance();
uriFragmentModel = URIFragmentModel(context).getInstance();
}
/**
* Configure media player with customs controllers. Helpful for tests
*
* @param {object=} config controllers configuration
* @memberof module:MediaPlayer
* @instance
*/
function setConfig(config) {
if (!config) {
return;
}
if (config.capabilities) {
capabilities = config.capabilities;
}
if (config.capabilitiesFilter) {
capabilitiesFilter = config.capabilitiesFilter;
}
if (config.streamController) {
streamController = config.streamController;
}
if (config.textController) {
textController = config.textController;
}
if (config.gapController) {
gapController = config.gapController;
}
if (config.playbackController) {
playbackController = config.playbackController;
}
if (config.serviceDescriptionController) {
serviceDescriptionController = config.serviceDescriptionController
}
if (config.contentSteeringController) {
contentSteeringController = config.contentSteeringController;
}
if (config.catchupController) {
catchupController = config.catchupController;
}
if (config.mediaPlayerModel) {
mediaPlayerModel = config.mediaPlayerModel;
}
if (config.customParametersModel) {
customParametersModel = config.customParametersModel;
}
if (config.abrController) {
abrController = config.abrController;
}
if (config.schemeLoaderFactory) {
schemeLoaderFactory = config.schemeLoaderFactory;
}
if (config.mediaController) {
mediaController = config.mediaController;
}
if (config.settings) {
settings = config.settings;
}
}
/**
* Upon creating the MediaPlayer you must call initialize before you call anything else.
* There is one exception to this rule. It is crucial to call {@link module:MediaPlayer#extend extend()}
* with all your extensions prior to calling initialize.
*
* ALL arguments are optional and there are individual methods to set each argument later on.
* The args in this method are just for convenience and should only be used for a simple player setup.
*
* @param {HTML5MediaElement=} view - Optional arg to set the video element. {@link module:MediaPlayer#attachView attachView()}
* @param {string=} source - Optional arg to set the media source. {@link module:MediaPlayer#attachSource attachSource()}
* @param {boolean=} autoPlay - Optional arg to set auto play. {@link module:MediaPlayer#setAutoPlay setAutoPlay()}
* @param {number|string} startTime - For VoD content the start time is relative to the start time of the first period.
* For live content
* If the parameter starts from prefix posix: it signifies the absolute time range defined in seconds of Coordinated Universal Time (ITU-R TF.460-6). This is the number of seconds since 01-01-1970 00:00:00 UTC. Fractions of seconds may be optionally specified down to the millisecond level.
* If no posix prefix is used the starttime is relative to MPD@availabilityStartTime
* @see {@link module:MediaPlayer#attachSource attachSource()}
* @see {@link module:MediaPlayer#setAutoPlay setAutoPlay()}
* @memberof module:MediaPlayer
* @instance
*/
function initialize(view, source, autoPlay, startTime = NaN) {
if (!capabilities) {
capabilities = Capabilities(context).getInstance();
capabilities.setConfig({
settings
})
}
if (!errHandler) {
errHandler = ErrorHandler(context).getInstance();
}
if (!capabilities.supportsMediaSource()) {
errHandler.error(new DashJSError(Errors.CAPABILITY_MEDIASOURCE_ERROR_CODE, Errors.CAPABILITY_MEDIASOURCE_ERROR_MESSAGE));
return;
}
if (!mediaPlayerInitialized) {
mediaPlayerInitialized = true;
// init some controllers and models
timelineConverter = TimelineConverter(context).getInstance();
if (!abrController) {
abrController = AbrController(context).getInstance();
abrController.setConfig({
settings: settings
});
}
if (!schemeLoaderFactory) {
schemeLoaderFactory = SchemeLoaderFactory(context).getInstance();
}
if (!playbackController) {
playbackController = PlaybackController(context).getInstance();
}
if (!mediaController) {
mediaController = MediaController(context).getInstance();
}
if (!streamController) {
streamController = StreamController(context).getInstance();
}
if (!gapController) {
gapController = GapController(context).getInstance();
}
if (!catchupController) {
catchupController = CatchupController(context).getInstance();
}
if (!serviceDescriptionController) {
serviceDescriptionController = ServiceDescriptionController(context).getInstance();
}
if (!contentSteeringController) {
contentSteeringController = ContentSteeringController(context).getInstance();
}
if (!capabilitiesFilter) {
capabilitiesFilter = CapabilitiesFilter(context).getInstance();
}
adapter = DashAdapter(context).getInstance();
manifestModel = ManifestModel(context).getInstance();
cmcdModel = CmcdModel(context).getInstance();
dashMetrics = DashMetrics(context).getInstance({
settings: settings
});
domStorage = DOMStorage(context).getInstance({
settings: settings
});
adapter.setConfig({
constants: Constants,
cea608parser: cea608parser,
errHandler: errHandler,
BASE64: BASE64
});
if (!baseURLController) {
baseURLController = BaseURLController(context).create();
}
baseURLController.setConfig({
adapter
});
serviceDescriptionController.setConfig({
adapter
});
if (!segmentBaseController) {
segmentBaseController = SegmentBaseController(context).getInstance({
dashMetrics: dashMetrics,
mediaPlayerModel: mediaPlayerModel,
errHandler: errHandler,
baseURLController: baseURLController,
events: Events,
eventBus: eventBus,
debug: debug,
boxParser: BoxParser(context).getInstance(),
requestModifier: RequestModifier(context).getInstance(),
errors: Errors
});
}
// configure controllers
mediaController.setConfig({
domStorage,
settings,
customParametersModel
});
mediaPlayerModel.setConfig({
playbackController,
serviceDescriptionController
});
restoreDefaultUTCTimingSources();
setAutoPlay(autoPlay !== undefined ? autoPlay : true);
// Detect and initialize offline module to support offline contents playback
_detectOffline();
}
if (view) {
attachView(view);
}
if (source) {
attachSource(source, startTime);
}
logger.info('[dash.js ' + getVersion() + '] ' + 'MediaPlayer has been initialized');
}
/**
* Sets the MPD source and the video element to null. You can also reset the MediaPlayer by
* calling attachSource with a new source file.
*
* This call does not destroy the MediaPlayer. To destroy the MediaPlayer and free all of its
* memory, call destroy().
*
* @memberof module:MediaPlayer
* @instance
*/
function reset() {
attachSource(null);
attachView(null);
protectionData = null;
if (protectionController) {
protectionController.reset();
protectionController = null;
}
if (metricsReportingController) {
metricsReportingController.reset();
metricsReportingController = null;
}
if (customParametersModel) {
customParametersModel.reset();
}
settings.reset();
if (offlineController) {
offlineController.reset();
offlineController = null;
}
}
/**
* Completely destroys the media player and frees all memory.
*
* @memberof module:MediaPlayer
* @instance
*/
function destroy() {
reset();
FactoryMaker.deleteSingletonInstances(context);
}
/**
* The ready state of the MediaPlayer based on both the video element and MPD source being defined.
*
* @returns {boolean} The current ready state of the MediaPlayer
* @see {@link module:MediaPlayer#attachView attachView()}
* @see {@link module:MediaPlayer#attachSource attachSource()}
* @memberof module:MediaPlayer
* @instance
*/
function isReady() {
return (!!source && !!videoModel.getElement());
}
/**
* Use the on method to listen for public events found in MediaPlayer.events. {@link MediaPlayerEvents}
*
* @param {string} type - {@link MediaPlayerEvents}
* @param {Function} listener - callback method when the event fires.
* @param {Object} scope - context of the listener so it can be removed properly.
* @param {Object} options - object to define various options such as priority and mode
* @memberof module:MediaPlayer
* @instance
*/
function on(type, listener, scope, options) {
eventBus.on(type, listener, scope, options);
}
/**
* Use the off method to remove listeners for public events found in MediaPlayer.events. {@link MediaPlayerEvents}
*
* @param {string} type - {@link MediaPlayerEvents}
* @param {Function} listener - callback method when the event fires.
* @param {Object} scope - context of the listener so it can be removed properly.
* @memberof module:MediaPlayer
* @instance
*/
function off(type, listener, scope) {
eventBus.off(type, listener, scope);
}
/**
* Current version of Dash.js
* @returns {string} the current dash.js version string.
* @memberof module:MediaPlayer
* @instance
*/
function getVersion() {
return getVersionString();
}
/**
* Use this method to access the dash.js logging class.
*
* @returns {Debug}
* @memberof module:MediaPlayer
* @instance
*/
function getDebug() {
return debug;
}
/*
---------------------------------------------------------------------------
PLAYBACK FUNCTIONS
---------------------------------------------------------------------------
*/
/**
* The play method initiates playback of the media defined by the {@link module:MediaPlayer#attachSource attachSource()} method.
* This method will call play on the native Video Element.
*
* @see {@link module:MediaPlayer#attachSource attachSource()}
* @throws {@link module:MediaPlayer~PLAYBACK_NOT_INITIALIZED_ERROR PLAYBACK_NOT_INITIALIZED_ERROR} if called before initializePlayback function
* @memberof module:MediaPlayer
* @instance
*/
function play() {
if (!playbackInitialized) {
throw PLAYBACK_NOT_INITIALIZED_ERROR;
}
if (!autoPlay || (isPaused() && playbackInitialized)) {
playbackController.play(true);
}
}
/**
* This method will call pause on the native Video Element.
*
* @throws {@link module:MediaPlayer~PLAYBACK_NOT_INITIALIZED_ERROR PLAYBACK_NOT_INITIALIZED_ERROR} if called before initializePlayback function
* @memberof module:MediaPlayer
* @instance
*/
function pause() {
if (!playbackInitialized) {
throw PLAYBACK_NOT_INITIALIZED_ERROR;
}
playbackController.pause();
}
/**
* Returns a Boolean that indicates whether the Video Element is paused.
* @return {boolean}
* @throws {@link module:MediaPlayer~PLAYBACK_NOT_INITIALIZED_ERROR PLAYBACK_NOT_INITIALIZED_ERROR} if called before initializePlayback function
* @memberof module:MediaPlayer
* @instance
*/
function isPaused() {
if (!playbackInitialized) {
throw PLAYBACK_NOT_INITIALIZED_ERROR;
}
return playbackController.isPaused();
}
/**
* Sets the currentTime property of the attached video element. If it is a live stream with a
* timeShiftBufferLength, then the DVR window offset will be automatically calculated.
*
* @param {number} value - A relative time, in seconds, based on the return value of the {@link module:MediaPlayer#duration duration()} method is expected.
* For dynamic streams duration() returns DVRWindow.end - DVRWindow.start. Consequently, the value provided to this function should be relative to DVRWindow.start.
* @see {@link module:MediaPlayer#getDVRSeekOffset getDVRSeekOffset()}
* @throws {@link module:MediaPlayer~PLAYBACK_NOT_INITIALIZED_ERROR PLAYBACK_NOT_INITIALIZED_ERROR} if called before initializePlayback function
* @throws {@link Constants#BAD_ARGUMENT_ERROR BAD_ARGUMENT_ERROR} if called with an invalid argument, not number type or is NaN.
* @memberof module:MediaPlayer
* @instance
*/
function seek(value) {
if (!playbackInitialized) {
throw PLAYBACK_NOT_INITIALIZED_ERROR;
}
checkParameterType(value, 'number');
if (isNaN(value)) {
throw Constants.BAD_ARGUMENT_ERROR;
}
let s = playbackController.getIsDynamic() ? getDVRSeekOffset(value) : value;
playbackController.seek(s, false, false, true);
}
/**
* Seeks back to the original live edge (live edge as calculated at playback start). Only applies to live streams, for VoD streams this call will be ignored.
*/
function seekToOriginalLive() {
if (!playbackInitialized || !isDynamic()) {
return;
}
playbackController.seekToOriginalLive();
}
/**
* Returns a Boolean that indicates whether the media is in the process of seeking to a new position.
* @return {boolean}
* @throws {@link module:MediaPlayer~PLAYBACK_NOT_INITIALIZED_ERROR PLAYBACK_NOT_INITIALIZED_ERROR} if called before initializePlayback function
* @memberof module:MediaPlayer
* @instance
*/
function isSeeking() {
if (!playbackInitialized) {
throw PLAYBACK_NOT_INITIALIZED_ERROR;
}
return playbackController.isSeeking();
}
/**
* Returns a Boolean that indicates whether the media is in the process of dynamic.
* @return {boolean}
* @throws {@link module:MediaPlayer~PLAYBACK_NOT_INITIALIZED_ERROR PLAYBACK_NOT_INITIALIZED_ERROR} if called before initializePlayback function
* @memberof module:MediaPlayer
* @instance
*/
function isDynamic() {
if (!playbackInitialized) {
throw PLAYBACK_NOT_INITIALIZED_ERROR;
}
return playbackController.getIsDynamic();
}
/**
* Returns a boolean that indicates whether the player is operating in low latency mode.
* @return {boolean}
* @memberof module:MediaPlayer
* @instance
*/
function getLowLatencyModeEnabled() {
if (!playbackInitialized) {
throw PLAYBACK_NOT_INITIALIZED_ERROR;
}
return playbackController.getLowLatencyModeEnabled();
}
/**
* Use this method to set the native Video Element's playback rate.
* @param {number} value
* @memberof module:MediaPlayer
* @instance
*/
function setPlaybackRate(value) {
getVideoElement().playbackRate = value;
}
/**
* Returns the current playback rate.
* @returns {number}
* @memberof module:MediaPlayer
* @instance
*/
function getPlaybackRate() {
return getVideoElement().playbackRate;
}
/**
* Use this method to set the native Video Element's muted state. Takes a Boolean that determines whether audio is muted. true if the audio is muted and false otherwise.
* @param {boolean} value
* @memberof module:MediaPlayer
* @throws {@link Constants#BAD_ARGUMENT_ERROR BAD_ARGUMENT_ERROR} if called with an invalid argument, not boolean type.
* @instance
*/
function setMute(value) {
checkParameterType(value, 'boolean');
getVideoElement().muted = value;
}
/**
* A Boolean that determines whether audio is muted.
* @returns {boolean}
* @memberof module:MediaPlayer
* @instance
*/
function isMuted() {
return getVideoElement().muted;
}
/**
* A double indicating the audio volume, from 0.0 (silent) to 1.0 (loudest).
* @param {number} value
* @memberof module:MediaPlayer
* @throws {@link Constants#BAD_ARGUMENT_ERROR BAD_ARGUMENT_ERROR} if called with an invalid argument, not number type, or is NaN or not between 0 and 1.
* @instance
*/
function setVolume(value) {
if (typeof value !== 'number' || isNaN(value) || value < 0.0 || value > 1.0) {
throw Constants.BAD_ARGUMENT_ERROR;
}
getVideoElement().volume = value;
}
/**
* Returns the current audio volume, from 0.0 (silent) to 1.0 (loudest).
* @returns {number}
* @memberof module:MediaPlayer
* @instance
*/
function getVolume() {
return getVideoElement().volume;
}
/**
* The length of the buffer for a given media type, in seconds. Valid media
* types are "video", "audio" and "text". If no type is passed
* in, then the minimum of video, audio and text buffer length is
* returned. NaN is returned if an invalid type is requested, the
* presentation does not contain that type, or if no arguments are passed
* and the presentation does not include any adaption sets of valid media
* type.
*
* @param {MediaType} type - 'video', 'audio' or 'text'
* @returns {number} The length of the buffer for the given media type, in
* seconds, or NaN
* @memberof module:MediaPlayer
* @instance
*/
function getBufferLength(type) {
const types = [Constants.VIDEO, Constants.AUDIO, Constants.TEXT];
if (!type) {
const buffer = types.map(
t => getTracksFor(t).length > 0 ? getDashMetrics().getCurrentBufferLevel(t) : Number.MAX_VALUE
).reduce(
(p, c) => Math.min(p, c)
);
return buffer === Number.MAX_VALUE ? NaN : buffer;
} else {
if (types.indexOf(type) !== -1) {
const buffer = getDashMetrics().getCurrentBufferLevel(type);
return buffer ? buffer : NaN;
} else {
logger.warn('getBufferLength requested for invalid type');
return NaN;
}
}
}
/**
* The timeShiftBufferLength (DVR Window), in seconds.
*
* @returns {number} The window of allowable play time behind the live point of a live stream as defined in the manifest.
* @memberof module:MediaPlayer
* @instance
*/
function getDVRWindowSize() {
const type = streamController && streamController.hasVideoTrack() ? Constants.VIDEO : Constants.AUDIO;
let metric = dashMetrics.getCurrentDVRInfo(type);
if (!metric) {
return 0;
}
return metric.manifestInfo.dvrWindowSize;
}
/**
* This method should only be used with a live stream that has a valid timeShiftBufferLength (DVR Window).
* NOTE - If you do not need the raw offset value (i.e. media analytics, tracking, etc) consider using the {@link module:MediaPlayer#seek seek()} method
* which will calculate this value for you and set the video element's currentTime property all in one simple call.
*
* @param {number} value - A relative time, in seconds, based on the return value of the {@link module:MediaPlayer#duration duration()} method is expected.
* @returns {number} A value that is relative the available range within the timeShiftBufferLength (DVR Window).
* @see {@link module:MediaPlayer#seek seek()}
* @memberof module:MediaPlayer
* @instance
*/
function getDVRSeekOffset(value) {
const type = streamController && streamController.hasVideoTrack() ? Constants.VIDEO : Constants.AUDIO;
let metric = dashMetrics.getCurrentDVRInfo(type);
if (!metric) {
return 0;
}
let liveDelay = playbackController.getOriginalLiveDelay();
let val = metric.range.start + value;
if (val > (metric.range.end - liveDelay)) {
val = metric.range.end - liveDelay;
}
return val;
}
/**
* Returns the target live delay
* @returns {number} The target live delay
* @memberof module:MediaPlayer
* @instance
*/
function getTargetLiveDelay() {
if (!playbackInitialized) {
throw PLAYBACK_NOT_INITIALIZED_ERROR;
}
return playbackController.getOriginalLiveDelay();
}
/**
* Current time of the playhead, in seconds.
*
* If called with no arguments then the returned time value is time elapsed since the start point of the first stream, or if it is a live stream, then the time will be based on the return value of the {@link module:MediaPlayer#duration duration()} method.
* However if a stream ID is supplied then time is relative to the start of that stream, or is null if there is no such stream id in the manifest.
*
* @param {string} streamId - The ID of a stream that the returned playhead time must be relative to the start of. If undefined, then playhead time is relative to the first stream.
* @returns {number} The current playhead time of the media, or null.
* @throws {@link module:MediaPlayer~PLAYBACK_NOT_INITIALIZED_ERROR PLAYBACK_NOT_INITIALIZED_ERROR} if called before initializePlayback function
* @memberof module:MediaPlayer
* @instance
*/
function time(streamId) {
if (!playbackInitialized) {
throw PLAYBACK_NOT_INITIALIZED_ERROR;
}
let t = getVideoElement().currentTime;
if (streamId !== undefined) {
t = streamController.getTimeRelativeToStreamId(t, streamId);
} else if (playbackController.getIsDynamic()) {
const type = streamController && streamController.hasVideoTrack() ? Constants.VIDEO : Constants.AUDIO;
let metric = dashMetrics.getCurrentDVRInfo(type);
t = (metric === null || t === 0) ? 0 : Math.max(0, (t - metric.range.start));
}
return t;
}
/**
* Duration of the media's playback, in seconds.
*
* @returns {number} The current duration of the media. For a dynamic stream this will return DVRWindow.end - DVRWindow.start
* @memberof module:MediaPlayer
* @throws {@link module:MediaPlayer~PLAYBACK_NOT_INITIALIZED_ERROR PLAYBACK_NOT_INITIALIZED_ERROR} if called before initializePlayback function
* @instance
*/
function duration() {
if (!playbackInitialized) {
throw PLAYBACK_NOT_INITIALIZED_ERROR;
}
let d = getVideoElement().duration;
if (playbackController.getIsDynamic()) {
const type = streamController && streamController.hasVideoTrack() ? Constants.VIDEO : Constants.AUDIO;
let metric = dashMetrics.getCurrentDVRInfo(type);
d = metric ? (metric.range.end - metric.range.start) : 0;
}
return d;
}
/**
* Use this method to get the current playhead time as an absolute value, the time in seconds since midnight UTC, Jan 1 1970.
* Note - this property only has meaning for live streams. If called before play() has begun, it will return a value of NaN.
*
* @returns {number} The current playhead time as UTC timestamp.
* @throws {@link module:MediaPlayer~PLAYBACK_NOT_INITIALIZED_ERROR PLAYBACK_NOT_INITIALIZED_ERROR} if called before initializePlayback function
* @memberof module:MediaPlayer
* @instance
*/
function timeAsUTC() {
if (!playbackInitialized) {
throw PLAYBACK_NOT_INITIALIZED_ERROR;
}
if (time() < 0) {
return NaN;
}
return _getAsUTC(time());
}
/**
* Use this method to get the current duration as an absolute value, the time in seconds since midnight UTC, Jan 1 1970.
* Note - this property only has meaning for live streams.
*
* @returns {number} The current duration as UTC timestamp.
* @throws {@link module:MediaPlayer~PLAYBACK_NOT_INITIALIZED_ERROR PLAYBACK_NOT_INITIALIZED_ERROR} if called before initializePlayback function
* @memberof module:MediaPlayer
* @instance
*/
function durationAsUTC() {
if (!playbackInitialized) {
throw PLAYBACK_NOT_INITIALIZED_ERROR;
}
return _getAsUTC(duration());
}
/*
---------------------------------------------------------------------------
AUTO BITRATE
---------------------------------------------------------------------------
*/
/**
* Gets the top quality BitrateInfo checking portal limit and max allowed.
* It calls getMaxAllowedIndexFor internally
*
* @param {MediaType} type - 'video' or 'audio'
* @memberof module:MediaPlayer
* @returns {BitrateInfo | null}
* @throws {@link module:MediaPlayer~STREAMING_NOT_INITIALIZED_ERROR STREAMING_NOT_INITIALIZED_ERROR} if called before initializePlayback function
* @instance
*/
function getTopBitrateInfoFor(type) {
if (!streamingInitialized) {
throw STREAMING_NOT_INITIALIZED_ERROR;
}
return abrController.getTopBitrateInfoFor(type);
}
/**
* Gets the current download quality for media type video, audio or images. For video and audio types the ABR
* rules update this value before every new download unless autoSwitchBitrate is set to false. For 'image'
* type, thumbnails, there is no ABR algorithm and quality is set manually.
*
* @param {MediaType} type - 'video', 'audio' or 'image' (thumbnails)
* @returns {number} the quality index, 0 corresponding to the lowest bitrate
* @memberof module:MediaPlayer
* @see {@link module:MediaPlayer#setQualityFor setQualityFor()}
* @throws {@link module:MediaPlayer~STREAMING_NOT_INITIALIZED_ERROR STREAMING_NOT_INITIALIZED_ERROR} if called before initializePlayback function
* @instance
*/
function getQualityFor(type) {
if (!streamingInitialized) {
throw STREAMING_NOT_INITIALIZED_ERROR;
}
if (type === Constants.IMAGE) {
const activeStream = getActiveStream();
if (!activeStream) {
return -1;
}
const thumbnailController = activeStream.getThumbnailController();
return !thumbnailController ? -1 : thumbnailController.getCurrentTrackIndex();
}
return abrController.getQualityFor(type);
}
/**
* Sets the current quality for media type instead of letting the ABR Heuristics automatically selecting it.
* This value will be overwritten by the ABR rules unless autoSwitchBitrate is set to false.
*
* @param {MediaType} type - 'video', 'audio' or 'image'
* @param {number} value - the quality index, 0 corresponding to the lowest bitrate
* @param {boolean} forceReplace - true if segments have to be replaced by segments of the new quality
* @memberof module:MediaPlayer
* @see {@link module:MediaPlayer#getQualityFor getQualityFor()}
* @throws {@link module:MediaPlayer~STREAMING_NOT_INITIALIZED_ERROR STREAMING_NOT_INITIALIZED_ERROR} if called before initializePlayback function
* @instance
*/
function setQualityFor(type, value, forceReplace = false) {
if (!streamingInitialized) {
throw STREAMING_NOT_INITIALIZED_ERROR;
}
if (type === Constants.IMAGE) {
const activeStream = getActiveStream();
if (!activeStream) {
return;
}
const thumbnailController = activeStream.getThumbnail