@l5i/dashjs
Version:
A reference client implementation for the playback of MPEG DASH via Javascript and compliant browsers.
1,339 lines (1,223 loc) • 113 kB
JavaScript
/**
* 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 Constants from './constants/Constants';
import MetricsConstants from './constants/MetricsConstants';
import UTCTiming from '../dash/vo/UTCTiming';
import PlaybackController from './controllers/PlaybackController';
import StreamController from './controllers/StreamController';
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 TextTracks from './text/TextTracks';
import RequestModifier from './utils/RequestModifier';
import TextController from './text/TextController';
import URIFragmentModel from './models/URIFragmentModel';
import ManifestModel from './models/ManifestModel';
import MediaPlayerModel from './models/MediaPlayerModel';
import MetricsModel from './models/MetricsModel';
import AbrController from './controllers/AbrController';
import VideoModel from './models/VideoModel';
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 {
getVersionString
}
from './../core/Version';
//Dash
import DashAdapter from '../dash/DashAdapter';
import DashManifestModel from '../dash/models/DashManifestModel';
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';
/**
* @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() {
const STREAMING_NOT_INITIALIZED_ERROR = 'You must first call initialize() and set a source before calling this method';
const PLAYBACK_NOT_INITIALIZED_ERROR = 'You must first call initialize() and set a valid source and view before calling this method';
const ELEMENT_NOT_ATTACHED_ERROR = 'You must first call attachView() to set the video element before calling this method';
const SOURCE_NOT_ATTACHED_ERROR = 'You must first call attachSource() with a valid source before calling this method';
const MEDIA_PLAYER_NOT_INITIALIZED_ERROR = 'MediaPlayer not initialized!';
const MEDIA_PLAYER_BAD_ARGUMENT_ERROR = 'MediaPlayer Invalid Arguments!';
const PLAYBACK_CATCHUP_RATE_BAD_ARGUMENT_ERROR = 'Playback catchup rate invalid argument! Use a number from 0 to 0.2';
const context = this.context;
const eventBus = EventBus(context).getInstance();
const debug = Debug(context).getInstance();
let instance,
logger,
source,
protectionData,
mediaPlayerInitialized,
streamingInitialized,
playbackInitialized,
autoPlay,
abrController,
timelineConverter,
mediaController,
protectionController,
metricsReportingController,
mssHandler,
adapter,
metricsModel,
mediaPlayerModel,
errHandler,
capabilities,
streamController,
playbackController,
dashMetrics,
dashManifestModel,
manifestModel,
videoModel,
textController,
domStorage;
/*
---------------------------------------------------------------------------
INIT FUNCTIONS
---------------------------------------------------------------------------
*/
function setup() {
logger = debug.getLogger(instance);
mediaPlayerInitialized = false;
playbackInitialized = false;
streamingInitialized = false;
autoPlay = true;
protectionController = null;
protectionData = null;
adapter = null;
Events.extend(MediaPlayerEvents);
mediaPlayerModel = MediaPlayerModel(context).getInstance();
videoModel = VideoModel(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.streamController) {
streamController = config.streamController;
}
if (config.playbackController) {
playbackController = config.playbackController;
}
if (config.mediaPlayerModel) {
mediaPlayerModel = config.mediaPlayerModel;
}
if (config.abrController) {
abrController = config.abrController;
}
if (config.mediaController) {
mediaController = config.mediaController;
}
}
/**
* 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()}
* @see {@link module:MediaPlayer#attachView attachView()}
* @see {@link module:MediaPlayer#attachSource attachSource()}
* @see {@link module:MediaPlayer#setAutoPlay setAutoPlay()}
* @memberof module:MediaPlayer
* @instance
*/
function initialize(view, source, AutoPlay) {
if (!capabilities) {
capabilities = Capabilities(context).getInstance();
}
errHandler = ErrorHandler(context).getInstance();
if (!capabilities.supportsMediaSource()) {
errHandler.capabilityError('mediasource');
errHandler.error(new DashJSError(Errors.CAPABILITY_MEDIASOURCE_ERROR_CODE, Errors.CAPABILITY_MEDIASOURCE_ERROR_MESSAGE));
return;
}
if (mediaPlayerInitialized) return;
mediaPlayerInitialized = true;
// init some controllers and models
timelineConverter = TimelineConverter(context).getInstance();
if (!abrController) {
abrController = AbrController(context).getInstance();
}
if (!playbackController) {
playbackController = PlaybackController(context).getInstance();
}
if (!mediaController) {
mediaController = MediaController(context).getInstance();
}
adapter = DashAdapter(context).getInstance();
dashManifestModel = DashManifestModel(context).getInstance({
mediaController: mediaController,
timelineConverter: timelineConverter,
adapter: adapter,
errHandler: errHandler
});
manifestModel = ManifestModel(context).getInstance();
dashMetrics = DashMetrics(context).getInstance({
manifestModel: manifestModel,
dashManifestModel: dashManifestModel
});
metricsModel = MetricsModel(context).getInstance();
textController = TextController(context).getInstance();
domStorage = DOMStorage(context).getInstance({
mediaPlayerModel: mediaPlayerModel
});
adapter.setConfig({
dashManifestModel: dashManifestModel
});
metricsModel.setConfig({
adapter: adapter
});
restoreDefaultUTCTimingSources();
setAutoPlay(AutoPlay !== undefined ? AutoPlay : true);
if (view) {
attachView(view);
}
if (source) {
attachSource(source);
}
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.
*
* Calling this method is all that is necessary to destroy a MediaPlayer instance.
*
* @memberof module:MediaPlayer
* @instance
*/
function reset() {
attachSource(null);
attachView(null);
protectionData = null;
if (protectionController) {
protectionController.reset();
protectionController = null;
}
if (metricsReportingController) {
metricsReportingController.reset();
metricsReportingController = null;
}
}
/**
* 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.
* @memberof module:MediaPlayer
* @instance
*/
function on(type, listener, scope) {
eventBus.on(type, listener, scope);
}
/**
* 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
---------------------------------------------------------------------------
*/
/**
* Causes the player to begin streaming the media as set by the {@link module:MediaPlayer#attachSource attachSource()}
* method in preparation for playing. It specifically does not require a view to be attached with {@link module:MediaPlayer#attachSource attachView()} to begin preloading.
* When a view is attached after preloading, the buffered data is transferred to the attached mediaSource buffers.
*
* @see {@link module:MediaPlayer#attachSource attachSource()}
* @see {@link module:MediaPlayer#attachView attachView()}
* @memberof module:MediaPlayer
* @instance
*/
function preload() {
if (videoModel.getElement() || streamingInitialized) {
return false;
}
if (source) {
initializePlayback();
} else {
throw SOURCE_NOT_ATTACHED_ERROR;
}
}
/**
* 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()}
* @memberof module:MediaPlayer
* @instance
*/
function play() {
if (!playbackInitialized) {
throw PLAYBACK_NOT_INITIALIZED_ERROR;
}
if (!autoPlay || (isPaused() && playbackInitialized)) {
playbackController.play();
}
}
/**
* This method will call pause on the native Video Element.
*
* @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}
* @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
* @see {@link module:MediaPlayer#getDVRSeekOffset getDVRSeekOffset()}
* @memberof module:MediaPlayer
* @instance
*/
function seek(value) {
if (!playbackInitialized) {
throw PLAYBACK_NOT_INITIALIZED_ERROR;
}
if (typeof value !== 'number' || isNaN(value)) {
throw MEDIA_PLAYER_BAD_ARGUMENT_ERROR;
}
let s = playbackController.getIsDynamic() ? getDVRSeekOffset(value) : value;
playbackController.seek(s);
}
/**
* Returns a Boolean that indicates whether the media is in the process of seeking to a new position.
* @return {boolean}
* @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}
* @memberof module:MediaPlayer
* @instance
*/
function isDynamic() {
if (!playbackInitialized) {
throw PLAYBACK_NOT_INITIALIZED_ERROR;
}
return playbackController.getIsDynamic();
}
/**
* Use this method to set the native Video Element's playback rate.
* @param {number} value
* @memberof module:MediaPlayer
* @instance
*/
function setPlaybackRate(value) {
if (!videoModel.getElement()) {
throw ELEMENT_NOT_ATTACHED_ERROR;
}
getVideoElement().playbackRate = value;
}
/**
* Returns the current playback rate.
* @returns {number}
* @memberof module:MediaPlayer
* @instance
*/
function getPlaybackRate() {
if (!videoModel.getElement()) {
throw ELEMENT_NOT_ATTACHED_ERROR;
}
return getVideoElement().playbackRate;
}
/**
* Use this method to set the catch up rate, as a percentage, for low latency live streams. In low latency mode,
* when measured latency is higher than the target one ({@link module:MediaPlayer#setLiveDelay setLiveDelay()}),
* dash.js increases playback rate the percentage defined with this method until target is reached.
*
* Valid values for catch up rate are in range 0-20%. Set it to 0% to turn off live catch up feature.
*
* Note: Catch-up mechanism is only applied when playing low latency live streams.
*
* @param {number} value Percentage in which playback rate is increased when live catch up mechanism is activated.
* @memberof module:MediaPlayer
* @see {@link module:MediaPlayer#setLiveDelay setLiveDelay()}
* @default {number} 0.05
* @instance
*/
function setCatchUpPlaybackRate(value) {
if ( typeof value !== 'number' || isNaN(value) || value < 0.0 || value > 0.20) {
throw PLAYBACK_CATCHUP_RATE_BAD_ARGUMENT_ERROR;
}
playbackController.setCatchUpPlaybackRate(value);
}
/**
* Returns the current catchup playback rate.
* @returns {number}
* @see {@link module:MediaPlayer#setCatchUpPlaybackRate setCatchUpPlaybackRate()}
* @memberof module:MediaPlayer
* @instance
*/
function getCatchUpPlaybackRate() {
return playbackController.getCatchUpPlaybackRate();
}
/**
* 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
* @instance
*/
function setMute(value) {
if (!videoModel.getElement()) {
throw ELEMENT_NOT_ATTACHED_ERROR;
}
getVideoElement().muted = value;
}
/**
* A Boolean that determines whether audio is muted.
* @returns {boolean}
* @memberof module:MediaPlayer
* @instance
*/
function isMuted() {
if (!videoModel.getElement()) {
throw ELEMENT_NOT_ATTACHED_ERROR;
}
return getVideoElement().muted;
}
/**
* A double indicating the audio volume, from 0.0 (silent) to 1.0 (loudest).
* @param {number} value
* @memberof module:MediaPlayer
* @instance
*/
function setVolume(value) {
if (!videoModel.getElement()) {
throw ELEMENT_NOT_ATTACHED_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() {
if (!videoModel.getElement()) {
throw ELEMENT_NOT_ATTACHED_ERROR;
}
return getVideoElement().volume;
}
/**
* The length of the buffer for a given media type, in seconds. Valid media
* types are "video", "audio" and "fragmentedText". If no type is passed
* in, then the minimum of video, audio and fragmentedText 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 {string} type - the media type of the buffer
* @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.FRAGMENTED_TEXT];
if (!type) {
const buffer = types.map(
t => getTracksFor(t).length > 0 ? getDashMetrics().getCurrentBufferLevel(getMetricsFor(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(getMetricsFor(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.
* @memberof module:MediaPlayer
* @instance
*/
function getDVRWindowSize() {
let metric = getDVRInfoMetric();
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) {
let metric = getDVRInfoMetric();
if (!metric) {
return 0;
}
let liveDelay = playbackController.getLiveDelay();
let val = metric.range.start + value;
if (val > (metric.range.end - liveDelay)) {
val = metric.range.end - liveDelay;
}
return val;
}
/**
* 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.
* @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()) {
let metric = getDVRInfoMetric();
t = (metric === null) ? 0 : duration() - (metric.range.end - metric.time);
}
return t;
}
/**
* Duration of the media's playback, in seconds.
*
* @returns {number} The current duration of the media.
* @memberof module:MediaPlayer
* @instance
*/
function duration() {
if (!playbackInitialized) {
throw PLAYBACK_NOT_INITIALIZED_ERROR;
}
let d = getVideoElement().duration;
if (playbackController.getIsDynamic()) {
let metric = getDVRInfoMetric();
let range;
if (!metric) {
return 0;
}
range = metric.range.end - metric.range.start;
d = range < metric.manifestInfo.DVRWindowSize ? range : metric.manifestInfo.DVRWindowSize;
}
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.
* @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.
* @memberof module:MediaPlayer
* @instance
*/
function durationAsUTC() {
if (!playbackInitialized) {
throw PLAYBACK_NOT_INITIALIZED_ERROR;
}
return getAsUTC(duration());
}
/*
---------------------------------------------------------------------------
AUTO BITRATE
---------------------------------------------------------------------------
*/
/**
* When switching multi-bitrate content (auto or manual mode) this property specifies the maximum bitrate allowed.
* If you set this property to a value lower than that currently playing, the switching engine will switch down to
* satisfy this requirement. If you set it to a value that is lower than the lowest bitrate, it will still play
* that lowest bitrate.
*
* You can set or remove this bitrate cap at anytime before or during playback. To clear this setting you must use the API
* and set the value param to NaN.
*
* This feature is typically used to reserve higher bitrates for playback only when the player is in large or full-screen format.
*
* @param {string} type - 'video' or 'audio' are the type options.
* @param {number} value - Value in kbps representing the maximum bitrate allowed.
* @memberof module:MediaPlayer
* @instance
*/
function setMaxAllowedBitrateFor(type, value) {
abrController.setMaxAllowedBitrateFor(type, value);
}
/**
* When switching multi-bitrate content (auto or manual mode) this property specifies the minimum bitrate allowed.
* If you set this property to a value higher than that currently playing, the switching engine will switch up to
* satisfy this requirement. If you set it to a value that is lower than the lowest bitrate, it will still play
* that lowest bitrate.
*
* You can set or remove this bitrate limit at anytime before or during playback. To clear this setting you must use the API
* and set the value param to NaN.
*
* This feature is used to force higher quality playback.
*
* @param {string} type - 'video' or 'audio' are the type options.
* @param {number} value - Value in kbps representing the minimum bitrate allowed.
* @memberof module:MediaPlayer
* @instance
*/
function setMinAllowedBitrateFor(type, value) {
abrController.setMinAllowedBitrateFor(type, value);
}
/**
* @param {string} type - 'video' or 'audio' are the type options.
* @memberof module:MediaPlayer
* @see {@link module:MediaPlayer#setMaxAllowedBitrateFor setMaxAllowedBitrateFor()}
* @instance
*/
function getMaxAllowedBitrateFor(type) {
return abrController.getMaxAllowedBitrateFor(type);
}
/**
* Gets the top quality BitrateInfo checking portal limit and max allowed.
*
* It calls getTopQualityIndexFor internally
*
* @param {string} type - 'video' or 'audio' are the type options.
* @memberof module:MediaPlayer
* @returns {BitrateInfo | null}
* @instance
*/
function getTopBitrateInfoFor(type) {
if (!streamingInitialized) {
throw STREAMING_NOT_INITIALIZED_ERROR;
}
return abrController.getTopBitrateInfoFor(type);
}
/**
* @param {string} type - 'video' or 'audio' are the type options.
* @memberof module:MediaPlayer
* @see {@link module:MediaPlayer#setMinAllowedBitrateFor setMinAllowedBitrateFor()}
* @instance
*/
function getMinAllowedBitrateFor(type) {
return abrController.getMinAllowedBitrateFor(type);
}
/**
* When switching multi-bitrate content (auto or manual mode) this property specifies the maximum representation allowed,
* as a proportion of the size of the representation set.
*
* You can set or remove this cap at anytime before or during playback. To clear this setting you must use the API
* and set the value param to NaN.
*
* If both this and maxAllowedBitrate are defined, maxAllowedBitrate is evaluated first, then maxAllowedRepresentation,
* i.e. the lowest value from executing these rules is used.
*
* This feature is typically used to reserve higher representations for playback only when connected over a fast connection.
*
* @param {string} type - 'video' or 'audio' are the type options.
* @param {number} value - number between 0 and 1, where 1 is allow all representations, and 0 is allow only the lowest.
* @memberof module:MediaPlayer
* @instance
*/
function setMaxAllowedRepresentationRatioFor(type, value) {
abrController.setMaxAllowedRepresentationRatioFor(type, value);
}
/**
* @param {string} type - 'video' or 'audio' are the type options.
* @returns {number} The current representation ratio cap.
* @memberof module:MediaPlayer
* @see {@link module:MediaPlayer#setMaxAllowedRepresentationRatioFor setMaxAllowedRepresentationRatioFor()}
* @instance
*/
function getMaxAllowedRepresentationRatioFor(type) {
return abrController.getMaxAllowedRepresentationRatioFor(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 setAutoSwitchQualityFor(type, false) is called. For 'image'
* type, thumbnails, there is no ABR algorithm and quality is set manually.
*
* @param {string} type - 'video', 'audio' or 'image' (thumbnails)
* @returns {number} the quality index, 0 corresponding to the lowest bitrate
* @memberof module:MediaPlayer
* @see {@link module:MediaPlayer#setAutoSwitchQualityFor setAutoSwitchQualityFor()}
* @see {@link module:MediaPlayer#setQualityFor setQualityFor()}
* @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();
if (!thumbnailController) {
return -1;
}
return thumbnailController.getCurrentTrackIndex();
}
return abrController.getQualityFor(type, streamController.getActiveStreamInfo());
}
/**
* 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 setAutoSwitchQualityFor(type, false) is called.
*
* @param {string} type - 'video', 'audio' or 'image'
* @param {number} value - the quality index, 0 corresponding to the lowest bitrate
* @memberof module:MediaPlayer
* @see {@link module:MediaPlayer#setAutoSwitchQualityFor setAutoSwitchQualityFor()}
* @see {@link module:MediaPlayer#getQualityFor getQualityFor()}
* @instance
*/
function setQualityFor(type, value) {
if (!streamingInitialized) {
throw STREAMING_NOT_INITIALIZED_ERROR;
}
if (type === Constants.IMAGE) {
const activeStream = getActiveStream();
if (!activeStream) {
return;
}
const thumbnailController = activeStream.getThumbnailController();
if (thumbnailController) {
thumbnailController.setTrackByIndex(value);
}
}
abrController.setPlaybackQuality(type, streamController.getActiveStreamInfo(), value);
}
/**
* Update the video element size variables
* Should be called on window resize (or any other time player is resized). Fullscreen does trigger a window resize event.
*
* Once windowResizeEventCalled = true, abrController.checkPortalSize() will use element size variables rather than querying clientWidth every time.
*
* @memberof module:MediaPlayer
* @instance
*/
function updatePortalSize() {
abrController.setElementSize();
abrController.setWindowResizeEventCalled(true);
}
/**
* @memberof module:MediaPlayer
* @instance
*/
function getLimitBitrateByPortal() {
return abrController.getLimitBitrateByPortal();
}
/**
* Sets whether to limit the representation used based on the size of the playback area
*
* @param {boolean} value
* @memberof module:MediaPlayer
* @instance
*/
function setLimitBitrateByPortal(value) {
abrController.setLimitBitrateByPortal(value);
}
/**
* @memberof module:MediaPlayer
* @instance
*/
function getUsePixelRatioInLimitBitrateByPortal() {
return abrController.getUsePixelRatioInLimitBitrateByPortal();
}
/**
* Sets whether to take into account the device's pixel ratio when defining the portal dimensions.
* Useful on, for example, retina displays.
*
* @param {boolean} value
* @memberof module:MediaPlayer
* @instance
* @default {boolean} false
*/
function setUsePixelRatioInLimitBitrateByPortal(value) {
abrController.setUsePixelRatioInLimitBitrateByPortal(value);
}
/**
* Use this method to explicitly set the starting bitrate for audio | video
*
* @param {string} type
* @param {number} value - A value of the initial bitrate, kbps
* @memberof module:MediaPlayer
* @instance
*/
function setInitialBitrateFor(type, value) {
abrController.setInitialBitrateFor(type, value);
}
/**
* @param {string} type
* @returns {number} A value of the initial bitrate, kbps
* @memberof module:MediaPlayer
* @instance
*/
function getInitialBitrateFor(type) {
if (!streamingInitialized) {
throw STREAMING_NOT_INITIALIZED_ERROR; //abrController.getInitialBitrateFor is overloaded with ratioDict logic that needs manifest force it to not be callable pre play.
}
return abrController.getInitialBitrateFor(type);
}
/**
* @param {string} type
* @param {number} value - A value of the initial Representation Ratio
* @memberof module:MediaPlayer
* @instance
*/
function setInitialRepresentationRatioFor(type, value) {
abrController.setInitialRepresentationRatioFor(type, value);
}
/**
* @param {string} type
* @returns {number} A value of the initial Representation Ratio
* @memberof module:MediaPlayer
* @instance
*/
function getInitialRepresentationRatioFor(type) {
return abrController.getInitialRepresentationRatioFor(type);
}
/**
* @param {string} type - 'audio' | 'video'
* @returns {boolean} Current state of adaptive bitrate switching
* @memberof module:MediaPlayer
* @instance
*/
function getAutoSwitchQualityFor(type) {
return abrController.getAutoSwitchBitrateFor(type);
}
/**
* Set to false to switch off adaptive bitrate switching.
*
* @param {string} type - 'audio' | 'video'
* @param {boolean} value
* @default true
* @memberof module:MediaPlayer
* @instance
*/
function setAutoSwitchQualityFor(type, value) {
abrController.setAutoSwitchBitrateFor(type, value);
}
/**
* Get the value of useDeadTimeLatency in AbrController. @see setUseDeadTimeLatencyForAbr
*
* @returns {boolean}
*
* @memberof module:MediaPlayer
* @instance
*/
function getUseDeadTimeLatencyForAbr() {
return abrController.getUseDeadTimeLatency();
}
/**
* Set the value of useDeadTimeLatency in AbrController. If true, only the download
* portion will be considered part of the download bitrate and latency will be
* regarded as static. If false, the reciprocal of the whole transfer time will be used.
* Defaults to true.
*
* @param {boolean=} useDeadTimeLatency - True or false flag.
*
* @memberof module:MediaPlayer
* @instance
*/
function setUseDeadTimeLatencyForAbr(useDeadTimeLatency) {
if (typeof useDeadTimeLatency !== 'boolean') {
throw MEDIA_PLAYER_BAD_ARGUMENT_ERROR;
}
abrController.setUseDeadTimeLatency(useDeadTimeLatency);
}
/*
---------------------------------------------------------------------------
MEDIA PLAYER CONFIGURATION
---------------------------------------------------------------------------
*/
/**
* <p>Set to false to prevent stream from auto-playing when the view is attached.</p>
*
* @param {boolean} value
* @default true
* @memberof module:MediaPlayer
* @see {@link module:MediaPlayer#attachView attachView()}
* @instance
*
*/
function setAutoPlay(value) {
autoPlay = value;
}
/**
* @returns {boolean} The current autoPlay state.
* @memberof module:MediaPlayer
* @instance
*/
function getAutoPlay() {
return autoPlay;
}
/**
* <p>Changing this value will lower or increase live stream latency. The detected segment duration will be multiplied by this value
* to define a time in seconds to delay a live stream from the live edge.</p>
* <p>Lowering this value will lower latency but may decrease the player's ability to build a stable buffer.</p>
*
* @param {number} value - Represents how many segment durations to delay the live stream.
* @default 4
* @memberof module:MediaPlayer
* @see {@link module:MediaPlayer#useSuggestedPresentationDelay useSuggestedPresentationDelay()}
* @instance
*/
function setLiveDelayFragmentCount(value) {
mediaPlayerModel.setLiveDelayFragmentCount(value);
}
/**
* <p>Equivalent in seconds of setLiveDelayFragmentCount</p>
* <p>Lowering this value will lower latency but may decrease the player's ability to build a stable buffer.</p>
* <p>This value should be less than the manifest duration by a couple of segment durations to avoid playback issues</p>
* <p>If set, this parameter will take precedence over setLiveDelayFragmentCount and manifest info</p>
*
* @param {number} value - Represents how many seconds to delay the live stream.
* @default undefined
* @memberof module:MediaPlayer
* @see {@link module:MediaPlayer#useSuggestedPresentationDelay useSuggestedPresentationDelay()}
* @instance
*/
function setLiveDelay(value) {
mediaPlayerModel.setLiveDelay(value);
}
/**
* @memberof module:MediaPlayer
* @see {@link module:MediaPlayer#setLiveDelay setLiveDelay()}
* @instance
* @returns {number|undefined} Current live stream delay in seconds when previously set, or `undefined`
*/
function getLiveDelay() {
return mediaPlayerModel.getLiveDelay();
}
/**
* @memberof module:MediaPlayer
* @instance
* @returns {number|NaN} Current live stream latency in seconds. It is the difference between current time and time position at the playback head.
*/
function getCurrentLiveLatency() {
if (!mediaPlayerInitialized) {
throw MEDIA_PLAYER_NOT_INITIALIZED_ERROR;
}
if (!playbackInitialized) {
return NaN;
}
return playbackController.getCurrentLiveLatency();
}
/**
* <p>Set to true if you would like to override the default live delay and honor the SuggestedPresentationDelay attribute in by the manifest.</p>
* @param {boolean} value
* @default false
* @memberof module:MediaPlayer
* @see {@link module:MediaPlayer#setLiveDelayFragmentCount setLiveDelayFragmentCount()}
* @instance
*/
function useSuggestedPresentationDelay(value) {
mediaPlayerModel.setUseSuggestedPresentationDelay(value);
}
/**
* Set to false if you would like to disable the last known bit rate from being stored during playback and used
* to set the initial bit rate for subsequent playback within the expiration window.
*
* The default expiration is one hour, defined in milliseconds. If expired, the default initial bit rate (closest to 1000 kbps) will be used
* for that session and a new bit rate will be stored during that session.
*
* @param {boolean} enable - Will toggle if feature is enabled. True to enable, False to disable.
* @param {number=} ttl - (Optional) A value defined in milliseconds representing how long to cache the bit rate for. Time to live.
* @default enable = True, ttl = 360000 (1 hour)
* @memberof module:MediaPlayer
* @instance
*
*/
function enableLastBitrateCaching(enable, ttl) {
mediaPlayerModel.setLastBitrateCachingInfo(enable, ttl);
}
/**
* Set to false if you would like to disable the last known lang for audio (or camera angle for video) from being stored during playback and used
* to set the initial settings for subsequent playback within the expiration window.
*
* The default expiration is one hour, defined in milliseconds. If expired, the default settings will be used
* for that session and a new settings will be stored during that session.
*
* @param {boolean} enable - Will toggle if feature is enabled. True to enable, False to disable.
* @param {number=} [ttl] - (Optional) A value defined in milliseconds representing how long to cache the settings for. Time to live.
* @default enable = True, ttl = 360000 (1 hour)
* @memberof module:MediaPlayer
* @instance
*
*/
function enableLastMediaSettingsCaching(enable, ttl) {
mediaPlayerModel.setLastMediaSettingsCachingInfo(enable, ttl);
}
/**
* Set to true if you would like dash.js to keep downloading fragments in the background
* when the video element is paused.
*
* @default true
* @param {boolean} value
* @memberof module:MediaPlayer
* @instance
*/
function setScheduleWhilePaused(value) {
mediaPlayerModel.setScheduleWhilePaused(value);
}
/**
* Returns a boolean of the current state of ScheduleWhilePaused.
* @returns {boolean}
* @see {@link module:MediaPlayer#setScheduleWhilePaused setScheduleWhilePaused()}
* @memberof module:MediaPlayer
* @instance
*/
function getScheduleWhilePaused() {
return mediaPlayerModel.getScheduleWhilePaused();
}
/**
* When enabled, after an ABR up-switch in quality, instead of requesting and appending the next fragment
* at the end of the current buffer range it is requested and appended closer to the current time
* When enabled, The maximum time to render a higher quality is current time + (1.5 * fragment duration).
*
* Note, When ABR down-switch is detected, we appended the lower quality at the end of the buffer range to preserve the
* higher quality media for as long as possible.
*
* If enabled, it should be noted there are a few cases when the client will not replace inside buffer range but rather
* just append at the end. 1. When the buffer level is less than one fragment duration 2. The client
* is in an Abandonment State due to recent fragment abandonment event.
*
* Known issues:
* 1. In IE11 with auto switching off, if a user switches to a quality they can not download in time the
* fragment may be appended in the same range as the playhead or even in the past, in IE11 it may cause a stutter
* or stall in playback.
*
*
* @param {boolean} value
* @default {boolean} false
* @memberof module:MediaPlayer
* @instance
*/
function setFastSwitchEnabled(value) { //TODO we need to look at track switches for adaptation sets. If always replace it works much like this but clears buffer. Maybe too many ways to do same thing.
mediaPlayerModel.setFastSwitchEnabled(value);
}
/**
* Enabled by default. Will return the current state of Fast Switch.
* @return {boolean} Returns true if FastSwitch ABR is enabled.
* @see {@link module:MediaPlayer#setFastSwitchEnabled setFastSwitchEnabled()}
* @memberof module:MediaPlayer
* @instance
*/
function getFastSwitchEnabled() {
return mediaPlayerModel.getFastSwitchEnabled();
}
/**
* Sets the ABR strategy. Valid strategies are "abrDynamic", "abrBola" and "abrThroughput".
* The ABR strategy can also be changed during a streaming session.
* The call has no effect if an invalid method is passed.
*
* The BOLA strategy chooses bitrate based on current buffer level, with higher bitrates for higher buffer levels.
* The Throughput strategy chooses bitrate based on the recent throughput history.
* The Dynamic strategy switches smoothly between BOLA and Throughput in real time, playing to the strengths of both.
*
* @param {string} value
* @default "abrDynamic"
* @memberof module:MediaPlayer
* @instance
*/
function setABRStrategy(value) {
if (value === Constants.ABR_STRATEGY_DYNAMIC || value === Constants.ABR_STRATEGY_BOLA || value === Constants.ABR_STRATEGY_THROUGHPUT) {
mediaPlayerModel.setABRStrategy(value);
} else {
logger.warn('Ignoring setABRStrategy(' + value + ') - unknown value.');
}
}
/**
* Returns the current ABR strategy being used.
* @return {string} "abrDynamic", "abrBola" or "abrThroughput"
* @see {@link module:MediaPlayer#setABRStrategy setABRStrategy()}
* @memberof module:MediaPlayer
* @instance
*/
function getABRStrategy() {
return mediaPlayerModel.getABRStrategy();
}
/**
* Enable/disable builtin dashjs ABR rules
* @param {boolean} value
* @default true
* @memberof module:MediaPlayer
* @instance
*/
function useDefaultABRRules(value) {
mediaPlayerModel.setUseDefaultABRRules(value);
}
/**
* Add a custom ABR Rule
* Rule will be apply on next stream if a stream is being played
*
* @param {string} type - rule type (one of ['qualitySwitchRules','abandonFragmentRules'])
* @param {string} rulename - name of rule (used to identify custom rule). If one rule of same name has been added, then existing rule will be updated
* @param {object} rule - the rule object instance
* @memberof module:MediaPlayer
* @instance
*/
function addABRCustomRule(type, rulename, rule) {
mediaPlayerModel.addABRCustomRule(type, rulename, rule);
}
/**
* Remove a custom ABR Rule
*
* @param {string} rulename - name of the rule to be removed
* @memberof module:MediaPlayer
* @instance
*/
function removeABRCustomRule(rulename) {
mediaPlayerModel.removeABRCustomRule(rulename);
}
/**
* Remove all custom rules
* @memberof module:MediaPlayer