(window["webpackjsonp"] = window["webpackjsonp"] || []).push([[67],{
/***/ 203:
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* webpack var injection */(function(global) {/* harmony import */ var global_window__webpack_imported_module_0__ = __webpack_require__(0);
/* harmony import */ var global_window__webpack_imported_module_0___default = /*#__pure__*/__webpack_require__.n(global_window__webpack_imported_module_0__);
/* harmony import */ var global_document__webpack_imported_module_1__ = __webpack_require__(3);
/* harmony import */ var global_document__webpack_imported_module_1___default = /*#__pure__*/__webpack_require__.n(global_document__webpack_imported_module_1__);
/* harmony import */ var _babel_runtime_helpers_extends__webpack_imported_module_2__ = __webpack_require__(27);
/* harmony import */ var _babel_runtime_helpers_extends__webpack_imported_module_2___default = /*#__pure__*/__webpack_require__.n(_babel_runtime_helpers_extends__webpack_imported_module_2__);
/* harmony import */ var keycode__webpack_imported_module_3__ = __webpack_require__(7);
/* harmony import */ var keycode__webpack_imported_module_3___default = /*#__pure__*/__webpack_require__.n(keycode__webpack_imported_module_3__);
/* harmony import */ var _babel_runtime_helpers_assertthisinitialized__webpack_imported_module_4__ = __webpack_require__(6);
/* harmony import */ var _babel_runtime_helpers_assertthisinitialized__webpack_imported_module_4___default = /*#__pure__*/__webpack_require__.n(_babel_runtime_helpers_assertthisinitialized__webpack_imported_module_4__);
/* harmony import */ var _babel_runtime_helpers_inheritsloose__webpack_imported_module_5__ = __webpack_require__(4);
/* harmony import */ var _babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default = /*#__pure__*/__webpack_require__.n(_babel_runtime_helpers_inheritsloose__webpack_imported_module_5__);
/* harmony import */ var safe_json_parse_tuple__webpack_imported_module_6__ = __webpack_require__(204);
/* harmony import */ var safe_json_parse_tuple__webpack_imported_module_6___default = /*#__pure__*/__webpack_require__.n(safe_json_parse_tuple__webpack_imported_module_6__);
/* harmony import */ var _videojs_xhr__webpack_imported_module_7__ = __webpack_require__(132);
/* harmony import */ var _videojs_xhr__webpack_imported_module_7___default = /*#__pure__*/__webpack_require__.n(_videojs_xhr__webpack_imported_module_7__);
/* harmony import */ var videojs_vtt_js__webpack_imported_module_8__ = __webpack_require__(133);
/* harmony import */ var videojs_vtt_js__webpack_imported_module_8___default = /*#__pure__*/__webpack_require__.n(videojs_vtt_js__webpack_imported_module_8__);
/* harmony import */ var _babel_runtime_helpers_construct__webpack_imported_module_9__ = __webpack_require__(125);
/* harmony import */ var _babel_runtime_helpers_construct__webpack_imported_module_9___default = /*#__pure__*/__webpack_require__.n(_babel_runtime_helpers_construct__webpack_imported_module_9__);
/* harmony import */ var _babel_runtime_helpers_inherits__webpack_imported_module_10__ = __webpack_require__(205);
/* harmony import */ var _babel_runtime_helpers_inherits__webpack_imported_module_10___default = /*#__pure__*/__webpack_require__.n(_babel_runtime_helpers_inherits__webpack_imported_module_10__);
/* harmony import */ var _videojs_vhs_utils_es_resolve_url_js__webpack_imported_module_11__ = __webpack_require__(57);
/* harmony import */ var m3u8_parser__webpack_imported_module_12__ = __webpack_require__(206);
/* harmony import */ var _videojs_vhs_utils_es_codecs_js__webpack_imported_module_13__ = __webpack_require__(8);
/* harmony import */ var _videojs_vhs_utils_es_media_types_js__webpack_imported_module_14__ = __webpack_require__(135);
/* harmony import */ var _videojs_vhs_utils_es_byte_helpers__webpack_imported_module_15__ = __webpack_require__(1);
/* harmony import */ var mpd_parser__webpack_imported_module_16__ = __webpack_require__(39);
/* harmony import */ var mux_js_lib_tools_parse_sidx__webpack_imported_module_17__ = __webpack_require__(209);
/* harmony import */ var mux_js_lib_tools_parse_sidx__webpack_imported_module_17___default = /*#__pure__*/__webpack_require__.n(mux_js_lib_tools_parse_sidx__webpack_imported_module_17__);
/* harmony import */ var _videojs_vhs_utils_es_id3_helpers__webpack_imported_module_18__ = __webpack_require__(44);
/* harmony import */ var _videojs_vhs_utils_es_containers__webpack_imported_module_19__ = __webpack_require__(74);
/* harmony import */ var mux_js_lib_utils_clock__webpack_imported_module_20__ = __webpack_require__(73);
/* harmony import */ var mux_js_lib_utils_clock__webpack_imported_module_20___default = /*#__pure__*/__webpack_require__.n(mux_js_lib_utils_clock__webpack_imported_module_20__);
/* harmony import */ var _babel_runtime_helpers_wrapnativesuper__webpack_imported_module_21__ = __webpack_require__(210);
/* harmony import */ var _babel_runtime_helpers_wrapnativesuper__webpack_imported_module_21___default = /*#__pure__*/__webpack_require__.n(_babel_runtime_helpers_wrapnativesuper__webpack_imported_module_21__);
/**
* @license
* video.js 7.21.6
* copyright brightcove, inc.
* available under apache license version 2.0
*
*
* includes vtt.js
* available under apache license version 2.0
*
*/
var version$5 = "7.21.6";
/**
* an object that contains lifecycle hooks as keys which point to an array
* of functions that are run when a lifecycle is triggered
*
* @private
*/
var hooks_ = {};
/**
* get a list of hooks for a specific lifecycle
*
* @param {string} type
* the lifecyle to get hooks from
*
* @param {function|function[]} [fn]
* optionally add a hook (or hooks) to the lifecycle that your are getting.
*
* @return {array}
* an array of hooks, or an empty array if there are none.
*/
var hooks = function hooks(type, fn) {
hooks_[type] = hooks_[type] || [];
if (fn) {
hooks_[type] = hooks_[type].concat(fn);
}
return hooks_[type];
};
/**
* add a function hook to a specific videojs lifecycle.
*
* @param {string} type
* the lifecycle to hook the function to.
*
* @param {function|function[]}
* the function or array of functions to attach.
*/
var hook = function hook(type, fn) {
hooks(type, fn);
};
/**
* remove a hook from a specific videojs lifecycle.
*
* @param {string} type
* the lifecycle that the function hooked to
*
* @param {function} fn
* the hooked function to remove
*
* @return {boolean}
* the function that was removed or undef
*/
var removehook = function removehook(type, fn) {
var index = hooks(type).indexof(fn);
if (index <= -1) {
return false;
}
hooks_[type] = hooks_[type].slice();
hooks_[type].splice(index, 1);
return true;
};
/**
* add a function hook that will only run once to a specific videojs lifecycle.
*
* @param {string} type
* the lifecycle to hook the function to.
*
* @param {function|function[]}
* the function or array of functions to attach.
*/
var hookonce = function hookonce(type, fn) {
hooks(type, [].concat(fn).map(function (original) {
var wrapper = function wrapper() {
removehook(type, wrapper);
return original.apply(void 0, arguments);
};
return wrapper;
}));
};
/**
* @file fullscreen-api.js
* @module fullscreen-api
* @private
*/
/**
* store the browser-specific methods for the fullscreen api.
*
* @type {object}
* @see [specification]{@link https://fullscreen.spec.whatwg.org}
* @see [map approach from screenfull.js]{@link https://github.com/sindresorhus/screenfull.js}
*/
var fullscreenapi = {
prefixed: true
}; // browser api methods
var apimap = [['requestfullscreen', 'exitfullscreen', 'fullscreenelement', 'fullscreenenabled', 'fullscreenchange', 'fullscreenerror', 'fullscreen'], // webkit
['webkitrequestfullscreen', 'webkitexitfullscreen', 'webkitfullscreenelement', 'webkitfullscreenenabled', 'webkitfullscreenchange', 'webkitfullscreenerror', '-webkit-full-screen'], // mozilla
['mozrequestfullscreen', 'mozcancelfullscreen', 'mozfullscreenelement', 'mozfullscreenenabled', 'mozfullscreenchange', 'mozfullscreenerror', '-moz-full-screen'], // microsoft
['msrequestfullscreen', 'msexitfullscreen', 'msfullscreenelement', 'msfullscreenenabled', 'msfullscreenchange', 'msfullscreenerror', '-ms-fullscreen']];
var specapi = apimap[0];
var browserapi; // determine the supported set of functions
for (var i = 0; i < apimap.length; i++) {
// check for exitfullscreen function
if (apimap[i][1] in global_document__webpack_imported_module_1___default.a) {
browserapi = apimap[i];
break;
}
} // map the browser api names to the spec api names
if (browserapi) {
for (var _i = 0; _i < browserapi.length; _i++) {
fullscreenapi[specapi[_i]] = browserapi[_i];
}
fullscreenapi.prefixed = browserapi[0] !== specapi[0];
}
/**
* @file create-logger.js
* @module create-logger
*/
var history = [];
/**
* log messages to the console and history based on the type of message
*
* @private
* @param {string} type
* the name of the console method to use.
*
* @param {array} args
* the arguments to be passed to the matching console method.
*/
var logbytypefactory = function logbytypefactory(name, log) {
return function (type, level, args) {
var lvl = log.levels[level];
var lvlregexp = new regexp("^(" + lvl + ")$");
if (type !== 'log') {
// add the type to the front of the message when it's not "log".
args.unshift(type.touppercase() + ':');
} // add console prefix after adding to history.
args.unshift(name + ':'); // add a clone of the args at this point to history.
if (history) {
history.push([].concat(args)); // only store 1000 history entries
var splice = history.length - 1000;
history.splice(0, splice > 0 ? splice : 0);
} // if there's no console then don't try to output messages, but they will
// still be stored in history.
if (!global_window__webpack_imported_module_0___default.a.console) {
return;
} // was setting these once outside of this function, but containing them
// in the function makes it easier to test cases where console doesn't exist
// when the module is executed.
var fn = global_window__webpack_imported_module_0___default.a.console[type];
if (!fn && type === 'debug') {
// certain browsers don't have support for console.debug. for those, we
// should default to the closest comparable log.
fn = global_window__webpack_imported_module_0___default.a.console.info || global_window__webpack_imported_module_0___default.a.console.log;
} // bail out if there's no console or if this type is not allowed by the
// current logging level.
if (!fn || !lvl || !lvlregexp.test(type)) {
return;
}
fn[array.isarray(args) ? 'apply' : 'call'](global_window__webpack_imported_module_0___default.a.console, args);
};
};
function createlogger$1(name) {
// this is the private tracking variable for logging level.
var level = 'info'; // the curried logbytype bound to the specific log and history
var logbytype;
/**
* logs plain debug messages. similar to `console.log`.
*
* due to [limitations](https://github.com/jsdoc3/jsdoc/issues/955#issuecomment-313829149)
* of our jsdoc template, we cannot properly document this as both a function
* and a namespace, so its function signature is documented here.
*
* #### arguments
* ##### *args
* mixed[]
*
* any combination of values that could be passed to `console.log()`.
*
* #### return value
*
* `undefined`
*
* @namespace
* @param {mixed[]} args
* one or more messages or objects that should be logged.
*/
var log = function log() {
for (var _len = arguments.length, args = new array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
logbytype('log', level, args);
}; // this is the logbytype helper that the logging methods below use
logbytype = logbytypefactory(name, log);
/**
* create a new sublogger which chains the old name to the new name.
*
* for example, doing `videojs.log.createlogger('player')` and then using that logger will log the following:
* ```js
* mylogger('foo');
* // > videojs: player: foo
* ```
*
* @param {string} name
* the name to add call the new logger
* @return {object}
*/
log.createlogger = function (subname) {
return createlogger$1(name + ': ' + subname);
};
/**
* enumeration of available logging levels, where the keys are the level names
* and the values are `|`-separated strings containing logging methods allowed
* in that logging level. these strings are used to create a regular expression
* matching the function name being called.
*
* levels provided by video.js are:
*
* - `off`: matches no calls. any value that can be cast to `false` will have
* this effect. the most restrictive.
* - `all`: matches only video.js-provided functions (`debug`, `log`,
* `log.warn`, and `log.error`).
* - `debug`: matches `log.debug`, `log`, `log.warn`, and `log.error` calls.
* - `info` (default): matches `log`, `log.warn`, and `log.error` calls.
* - `warn`: matches `log.warn` and `log.error` calls.
* - `error`: matches only `log.error` calls.
*
* @type {object}
*/
log.levels = {
all: 'debug|log|warn|error',
off: '',
debug: 'debug|log|warn|error',
info: 'log|warn|error',
warn: 'warn|error',
error: 'error',
default: level
};
/**
* get or set the current logging level.
*
* if a string matching a key from {@link module:log.levels} is provided, acts
* as a setter.
*
* @param {string} [lvl]
* pass a valid level to set a new logging level.
*
* @return {string}
* the current logging level.
*/
log.level = function (lvl) {
if (typeof lvl === 'string') {
if (!log.levels.hasownproperty(lvl)) {
throw new error("\"" + lvl + "\" in not a valid log level");
}
level = lvl;
}
return level;
};
/**
* returns an array containing everything that has been logged to the history.
*
* this array is a shallow clone of the internal history record. however, its
* contents are _not_ cloned; so, mutating objects inside this array will
* mutate them in history.
*
* @return {array}
*/
log.history = function () {
return history ? [].concat(history) : [];
};
/**
* allows you to filter the history by the given logger name
*
* @param {string} fname
* the name to filter by
*
* @return {array}
* the filtered list to return
*/
log.history.filter = function (fname) {
return (history || []).filter(function (historyitem) {
// if the first item in each historyitem includes `fname`, then it's a match
return new regexp(".*" + fname + ".*").test(historyitem[0]);
});
};
/**
* clears the internal history tracking, but does not prevent further history
* tracking.
*/
log.history.clear = function () {
if (history) {
history.length = 0;
}
};
/**
* disable history tracking if it is currently enabled.
*/
log.history.disable = function () {
if (history !== null) {
history.length = 0;
history = null;
}
};
/**
* enable history tracking if it is currently disabled.
*/
log.history.enable = function () {
if (history === null) {
history = [];
}
};
/**
* logs error messages. similar to `console.error`.
*
* @param {mixed[]} args
* one or more messages or objects that should be logged as an error
*/
log.error = function () {
for (var _len2 = arguments.length, args = new array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
return logbytype('error', level, args);
};
/**
* logs warning messages. similar to `console.warn`.
*
* @param {mixed[]} args
* one or more messages or objects that should be logged as a warning.
*/
log.warn = function () {
for (var _len3 = arguments.length, args = new array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
args[_key3] = arguments[_key3];
}
return logbytype('warn', level, args);
};
/**
* logs debug messages. similar to `console.debug`, but may also act as a comparable
* log if `console.debug` is not available
*
* @param {mixed[]} args
* one or more messages or objects that should be logged as debug.
*/
log.debug = function () {
for (var _len4 = arguments.length, args = new array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
args[_key4] = arguments[_key4];
}
return logbytype('debug', level, args);
};
return log;
}
/**
* @file log.js
* @module log
*/
var log$1 = createlogger$1('videojs');
var createlogger = log$1.createlogger;
/**
* @file obj.js
* @module obj
*/
/**
* @callback obj:eachcallback
*
* @param {mixed} value
* the current key for the object that is being iterated over.
*
* @param {string} key
* the current key-value for object that is being iterated over
*/
/**
* @callback obj:reducecallback
*
* @param {mixed} accum
* the value that is accumulating over the reduce loop.
*
* @param {mixed} value
* the current key for the object that is being iterated over.
*
* @param {string} key
* the current key-value for object that is being iterated over
*
* @return {mixed}
* the new accumulated value.
*/
var tostring = object.prototype.tostring;
/**
* get the keys of an object
*
* @param {object}
* the object to get the keys from
*
* @return {string[]}
* an array of the keys from the object. returns an empty array if the
* object passed in was invalid or had no keys.
*
* @private
*/
var keys = function keys(object) {
return isobject(object) ? object.keys(object) : [];
};
/**
* array-like iteration for objects.
*
* @param {object} object
* the object to iterate over
*
* @param {obj:eachcallback} fn
* the callback function which is called for each key in the object.
*/
function each(object, fn) {
keys(object).foreach(function (key) {
return fn(object[key], key);
});
}
/**
* array-like reduce for objects.
*
* @param {object} object
* the object that you want to reduce.
*
* @param {function} fn
* a callback function which is called for each key in the object. it
* receives the accumulated value and the per-iteration value and key
* as arguments.
*
* @param {mixed} [initial = 0]
* starting value
*
* @return {mixed}
* the final accumulated value.
*/
function reduce(object, fn, initial) {
if (initial === void 0) {
initial = 0;
}
return keys(object).reduce(function (accum, key) {
return fn(accum, object[key], key);
}, initial);
}
/**
* object.assign-style object shallow merge/extend.
*
* @param {object} target
* @param {object} ...sources
* @return {object}
*/
function assign(target) {
for (var _len = arguments.length, sources = new array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
sources[_key - 1] = arguments[_key];
}
if (object.assign) {
return _babel_runtime_helpers_extends__webpack_imported_module_2___default.a.apply(void 0, [target].concat(sources));
}
sources.foreach(function (source) {
if (!source) {
return;
}
each(source, function (value, key) {
target[key] = value;
});
});
return target;
}
/**
* returns whether a value is an object of any kind - including dom nodes,
* arrays, regular expressions, etc. not functions, though.
*
* this avoids the gotcha where using `typeof` on a `null` value
* results in `'object'`.
*
* @param {object} value
* @return {boolean}
*/
function isobject(value) {
return !!value && typeof value === 'object';
}
/**
* returns whether an object appears to be a "plain" object - that is, a
* direct instance of `object`.
*
* @param {object} value
* @return {boolean}
*/
function isplain(value) {
return isobject(value) && tostring.call(value) === '[object object]' && value.constructor === object;
}
/**
* @file computed-style.js
* @module computed-style
*/
/**
* a safe getcomputedstyle.
*
* this is needed because in firefox, if the player is loaded in an iframe with
* `display:none`, then `getcomputedstyle` returns `null`, so, we do a
* null-check to make sure that the player doesn't break in these cases.
*
* @function
* @param {element} el
* the element you want the computed style of
*
* @param {string} prop
* the property name you want
*
* @see https://bugzilla.mozilla.org/show_bug.cgi?id=548397
*/
function computedstyle(el, prop) {
if (!el || !prop) {
return '';
}
if (typeof global_window__webpack_imported_module_0___default.a.getcomputedstyle === 'function') {
var computedstylevalue;
try {
computedstylevalue = global_window__webpack_imported_module_0___default.a.getcomputedstyle(el);
} catch (e) {
return '';
}
return computedstylevalue ? computedstylevalue.getpropertyvalue(prop) || computedstylevalue[prop] : '';
}
return '';
}
/**
* @file browser.js
* @module browser
*/
var user_agent = global_window__webpack_imported_module_0___default.a.navigator && global_window__webpack_imported_module_0___default.a.navigator.useragent || '';
var webkitversionmap = /applewebkit\/([\d.]+)/i.exec(user_agent);
var applewebkitversion = webkitversionmap ? parsefloat(webkitversionmap.pop()) : null;
/**
* whether or not this device is an ipod.
*
* @static
* @const
* @type {boolean}
*/
var is_ipod = /ipod/i.test(user_agent);
/**
* the detected ios version - or `null`.
*
* @static
* @const
* @type {string|null}
*/
var ios_version = function () {
var match = user_agent.match(/os (\d+)_/i);
if (match && match[1]) {
return match[1];
}
return null;
}();
/**
* whether or not this is an android device.
*
* @static
* @const
* @type {boolean}
*/
var is_android = /android/i.test(user_agent);
/**
* the detected android version - or `null`.
*
* @static
* @const
* @type {number|string|null}
*/
var android_version = function () {
// this matches android major.minor.patch versions
// android_version is major.minor as a number, if minor isn't available, then only major is returned
var match = user_agent.match(/android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);
if (!match) {
return null;
}
var major = match[1] && parsefloat(match[1]);
var minor = match[2] && parsefloat(match[2]);
if (major && minor) {
return parsefloat(match[1] + '.' + match[2]);
} else if (major) {
return major;
}
return null;
}();
/**
* whether or not this is a native android browser.
*
* @static
* @const
* @type {boolean}
*/
var is_native_android = is_android && android_version < 5 && applewebkitversion < 537;
/**
* whether or not this is mozilla firefox.
*
* @static
* @const
* @type {boolean}
*/
var is_firefox = /firefox/i.test(user_agent);
/**
* whether or not this is microsoft edge.
*
* @static
* @const
* @type {boolean}
*/
var is_edge = /edg/i.test(user_agent);
/**
* whether or not this is google chrome.
*
* this will also be `true` for chrome on ios, which will have different support
* as it is actually safari under the hood.
*
* @static
* @const
* @type {boolean}
*/
var is_chrome = !is_edge && (/chrome/i.test(user_agent) || /crios/i.test(user_agent));
/**
* the detected google chrome version - or `null`.
*
* @static
* @const
* @type {number|null}
*/
var chrome_version = function () {
var match = user_agent.match(/(chrome|crios)\/(\d+)/);
if (match && match[2]) {
return parsefloat(match[2]);
}
return null;
}();
/**
* the detected internet explorer version - or `null`.
*
* @static
* @const
* @type {number|null}
*/
var ie_version = function () {
var result = /msie\s(\d+)\.\d/.exec(user_agent);
var version = result && parsefloat(result[1]);
if (!version && /trident\/7.0/i.test(user_agent) && /rv:11.0/.test(user_agent)) {
// ie 11 has a different user agent string than other ie versions
version = 11.0;
}
return version;
}();
/**
* whether or not this is desktop safari.
*
* @static
* @const
* @type {boolean}
*/
var is_safari = /safari/i.test(user_agent) && !is_chrome && !is_android && !is_edge;
/**
* whether or not this is a windows machine.
*
* @static
* @const
* @type {boolean}
*/
var is_windows = /windows/i.test(user_agent);
/**
* whether or not this device is touch-enabled.
*
* @static
* @const
* @type {boolean}
*/
var touch_enabled = boolean(isreal() && ('ontouchstart' in global_window__webpack_imported_module_0___default.a || global_window__webpack_imported_module_0___default.a.navigator.maxtouchpoints || global_window__webpack_imported_module_0___default.a.documenttouch && global_window__webpack_imported_module_0___default.a.document instanceof global_window__webpack_imported_module_0___default.a.documenttouch));
/**
* whether or not this device is an ipad.
*
* @static
* @const
* @type {boolean}
*/
var is_ipad = /ipad/i.test(user_agent) || is_safari && touch_enabled && !/iphone/i.test(user_agent);
/**
* whether or not this device is an iphone.
*
* @static
* @const
* @type {boolean}
*/
// the facebook app's uiwebview identifies as both an iphone and ipad, so
// to identify iphones, we need to exclude ipads.
// http://artsy.github.io/blog/2012/10/18/the-perils-of-ios-user-agent-sniffing/
var is_iphone = /iphone/i.test(user_agent) && !is_ipad;
/**
* whether or not this is an ios device.
*
* @static
* @const
* @type {boolean}
*/
var is_ios = is_iphone || is_ipad || is_ipod;
/**
* whether or not this is any flavor of safari - including ios.
*
* @static
* @const
* @type {boolean}
*/
var is_any_safari = (is_safari || is_ios) && !is_chrome;
var browser = /*#__pure__*/object.freeze({
__proto__: null,
is_ipod: is_ipod,
ios_version: ios_version,
is_android: is_android,
android_version: android_version,
is_native_android: is_native_android,
is_firefox: is_firefox,
is_edge: is_edge,
is_chrome: is_chrome,
chrome_version: chrome_version,
ie_version: ie_version,
is_safari: is_safari,
is_windows: is_windows,
touch_enabled: touch_enabled,
is_ipad: is_ipad,
is_iphone: is_iphone,
is_ios: is_ios,
is_any_safari: is_any_safari
});
/**
* @file dom.js
* @module dom
*/
/**
* detect if a value is a string with any non-whitespace characters.
*
* @private
* @param {string} str
* the string to check
*
* @return {boolean}
* will be `true` if the string is non-blank, `false` otherwise.
*
*/
function isnonblankstring(str) {
// we use str.trim as it will trim any whitespace characters
// from the front or back of non-whitespace characters. aka
// any string that contains non-whitespace characters will
// still contain them after `trim` but whitespace only strings
// will have a length of 0, failing this check.
return typeof str === 'string' && boolean(str.trim());
}
/**
* throws an error if the passed string has whitespace. this is used by
* class methods to be relatively consistent with the classlist api.
*
* @private
* @param {string} str
* the string to check for whitespace.
*
* @throws {error}
* throws an error if there is whitespace in the string.
*/
function throwifwhitespace(str) {
// str.indexof instead of regex because str.indexof is faster performance wise.
if (str.indexof(' ') >= 0) {
throw new error('class has illegal whitespace characters');
}
}
/**
* produce a regular expression for matching a classname within an elements classname.
*
* @private
* @param {string} classname
* the classname to generate the regexp for.
*
* @return {regexp}
* the regexp that will check for a specific `classname` in an elements
* classname.
*/
function classregexp(classname) {
return new regexp('(^|\\s)' + classname + '($|\\s)');
}
/**
* whether the current dom interface appears to be real (i.e. not simulated).
*
* @return {boolean}
* will be `true` if the dom appears to be real, `false` otherwise.
*/
function isreal() {
// both document and window will never be undefined thanks to `global`.
return global_document__webpack_imported_module_1___default.a === global_window__webpack_imported_module_0___default.a.document;
}
/**
* determines, via duck typing, whether or not a value is a dom element.
*
* @param {mixed} value
* the value to check.
*
* @return {boolean}
* will be `true` if the value is a dom element, `false` otherwise.
*/
function isel(value) {
return isobject(value) && value.nodetype === 1;
}
/**
* determines if the current dom is embedded in an iframe.
*
* @return {boolean}
* will be `true` if the dom is embedded in an iframe, `false`
* otherwise.
*/
function isinframe() {
// we need a try/catch here because safari will throw errors when attempting
// to get either `parent` or `self`
try {
return global_window__webpack_imported_module_0___default.a.parent !== global_window__webpack_imported_module_0___default.a.self;
} catch (x) {
return true;
}
}
/**
* creates functions to query the dom using a given method.
*
* @private
* @param {string} method
* the method to create the query with.
*
* @return {function}
* the query method
*/
function createquerier(method) {
return function (selector, context) {
if (!isnonblankstring(selector)) {
return global_document__webpack_imported_module_1___default.a[method](null);
}
if (isnonblankstring(context)) {
context = global_document__webpack_imported_module_1___default.a.queryselector(context);
}
var ctx = isel(context) ? context : global_document__webpack_imported_module_1___default.a;
return ctx[method] && ctx[method](selector);
};
}
/**
* creates an element and applies properties, attributes, and inserts content.
*
* @param {string} [tagname='div']
* name of tag to be created.
*
* @param {object} [properties={}]
* element properties to be applied.
*
* @param {object} [attributes={}]
* element attributes to be applied.
*
* @param {module:dom~contentdescriptor} content
* a content descriptor object.
*
* @return {element}
* the element that was created.
*/
function createel(tagname, properties, attributes, content) {
if (tagname === void 0) {
tagname = 'div';
}
if (properties === void 0) {
properties = {};
}
if (attributes === void 0) {
attributes = {};
}
var el = global_document__webpack_imported_module_1___default.a.createelement(tagname);
object.getownpropertynames(properties).foreach(function (propname) {
var val = properties[propname]; // see #2176
// we originally were accepting both properties and attributes in the
// same object, but that doesn't work so well.
if (propname.indexof('aria-') !== -1 || propname === 'role' || propname === 'type') {
log$1.warn('setting attributes in the second argument of createel()\n' + 'has been deprecated. use the third argument instead.\n' + ("createel(type, properties, attributes). attempting to set " + propname + " to " + val + "."));
el.setattribute(propname, val); // handle textcontent since it's not supported everywhere and we have a
// method for it.
} else if (propname === 'textcontent') {
textcontent(el, val);
} else if (el[propname] !== val || propname === 'tabindex') {
el[propname] = val;
}
});
object.getownpropertynames(attributes).foreach(function (attrname) {
el.setattribute(attrname, attributes[attrname]);
});
if (content) {
appendcontent(el, content);
}
return el;
}
/**
* injects text into an element, replacing any existing contents entirely.
*
* @param {element} el
* the element to add text content into
*
* @param {string} text
* the text content to add.
*
* @return {element}
* the element with added text content.
*/
function textcontent(el, text) {
if (typeof el.textcontent === 'undefined') {
el.innertext = text;
} else {
el.textcontent = text;
}
return el;
}
/**
* insert an element as the first child node of another
*
* @param {element} child
* element to insert
*
* @param {element} parent
* element to insert child into
*/
function prependto(child, parent) {
if (parent.firstchild) {
parent.insertbefore(child, parent.firstchild);
} else {
parent.appendchild(child);
}
}
/**
* check if an element has a class name.
*
* @param {element} element
* element to check
*
* @param {string} classtocheck
* class name to check for
*
* @return {boolean}
* will be `true` if the element has a class, `false` otherwise.
*
* @throws {error}
* throws an error if `classtocheck` has white space.
*/
function hasclass(element, classtocheck) {
throwifwhitespace(classtocheck);
if (element.classlist) {
return element.classlist.contains(classtocheck);
}
return classregexp(classtocheck).test(element.classname);
}
/**
* add a class name to an element.
*
* @param {element} element
* element to add class name to.
*
* @param {string} classtoadd
* class name to add.
*
* @return {element}
* the dom element with the added class name.
*/
function addclass(element, classtoadd) {
if (element.classlist) {
element.classlist.add(classtoadd); // don't need to `throwifwhitespace` here because `haselclass` will do it
// in the case of classlist not being supported.
} else if (!hasclass(element, classtoadd)) {
element.classname = (element.classname + ' ' + classtoadd).trim();
}
return element;
}
/**
* remove a class name from an element.
*
* @param {element} element
* element to remove a class name from.
*
* @param {string} classtoremove
* class name to remove
*
* @return {element}
* the dom element with class name removed.
*/
function removeclass(element, classtoremove) {
// protect in case the player gets disposed
if (!element) {
log$1.warn("removeclass was called with an element that doesn't exist");
return null;
}
if (element.classlist) {
element.classlist.remove(classtoremove);
} else {
throwifwhitespace(classtoremove);
element.classname = element.classname.split(/\s+/).filter(function (c) {
return c !== classtoremove;
}).join(' ');
}
return element;
}
/**
* the callback definition for toggleclass.
*
* @callback module:dom~predicatecallback
* @param {element} element
* the dom element of the component.
*
* @param {string} classtotoggle
* the `classname` that wants to be toggled
*
* @return {boolean|undefined}
* if `true` is returned, the `classtotoggle` will be added to the
* `element`. if `false`, the `classtotoggle` will be removed from
* the `element`. if `undefined`, the callback will be ignored.
*/
/**
* adds or removes a class name to/from an element depending on an optional
* condition or the presence/absence of the class name.
*
* @param {element} element
* the element to toggle a class name on.
*
* @param {string} classtotoggle
* the class that should be toggled.
*
* @param {boolean|module:dom~predicatecallback} [predicate]
* see the return value for {@link module:dom~predicatecallback}
*
* @return {element}
* the element with a class that has been toggled.
*/
function toggleclass(element, classtotoggle, predicate) {
// this cannot use `classlist` internally because ie11 does not support the
// second parameter to the `classlist.toggle()` method! which is fine because
// `classlist` will be used by the add/remove functions.
var has = hasclass(element, classtotoggle);
if (typeof predicate === 'function') {
predicate = predicate(element, classtotoggle);
}
if (typeof predicate !== 'boolean') {
predicate = !has;
} // if the necessary class operation matches the current state of the
// element, no action is required.
if (predicate === has) {
return;
}
if (predicate) {
addclass(element, classtotoggle);
} else {
removeclass(element, classtotoggle);
}
return element;
}
/**
* apply attributes to an html element.
*
* @param {element} el
* element to add attributes to.
*
* @param {object} [attributes]
* attributes to be applied.
*/
function setattributes(el, attributes) {
object.getownpropertynames(attributes).foreach(function (attrname) {
var attrvalue = attributes[attrname];
if (attrvalue === null || typeof attrvalue === 'undefined' || attrvalue === false) {
el.removeattribute(attrname);
} else {
el.setattribute(attrname, attrvalue === true ? '' : attrvalue);
}
});
}
/**
* get an element's attribute values, as defined on the html tag.
*
* attributes are not the same as properties. they're defined on the tag
* or with setattribute.
*
* @param {element} tag
* element from which to get tag attributes.
*
* @return {object}
* all attributes of the element. boolean attributes will be `true` or
* `false`, others will be strings.
*/
function getattributes(tag) {
var obj = {}; // known boolean attributes
// we can check for matching boolean properties, but not all browsers
// and not all tags know about these attributes, so, we still want to check them manually
var knownbooleans = ',' + 'autoplay,controls,playsinline,loop,muted,default,defaultmuted' + ',';
if (tag && tag.attributes && tag.attributes.length > 0) {
var attrs = tag.attributes;
for (var i = attrs.length - 1; i >= 0; i--) {
var attrname = attrs[i].name;
var attrval = attrs[i].value; // check for known booleans
// the matching element property will return a value for typeof
if (typeof tag[attrname] === 'boolean' || knownbooleans.indexof(',' + attrname + ',') !== -1) {
// the value of an included boolean attribute is typically an empty
// string ('') which would equal false if we just check for a false value.
// we also don't want support bad code like autoplay='false'
attrval = attrval !== null ? true : false;
}
obj[attrname] = attrval;
}
}
return obj;
}
/**
* get the value of an element's attribute.
*
* @param {element} el
* a dom element.
*
* @param {string} attribute
* attribute to get the value of.
*
* @return {string}
* the value of the attribute.
*/
function getattribute(el, attribute) {
return el.getattribute(attribute);
}
/**
* set the value of an element's attribute.
*
* @param {element} el
* a dom element.
*
* @param {string} attribute
* attribute to set.
*
* @param {string} value
* value to set the attribute to.
*/
function setattribute(el, attribute, value) {
el.setattribute(attribute, value);
}
/**
* remove an element's attribute.
*
* @param {element} el
* a dom element.
*
* @param {string} attribute
* attribute to remove.
*/
function removeattribute(el, attribute) {
el.removeattribute(attribute);
}
/**
* attempt to block the ability to select text.
*/
function blocktextselection() {
global_document__webpack_imported_module_1___default.a.body.focus();
global_document__webpack_imported_module_1___default.a.onselectstart = function () {
return false;
};
}
/**
* turn off text selection blocking.
*/
function unblocktextselection() {
global_document__webpack_imported_module_1___default.a.onselectstart = function () {
return true;
};
}
/**
* identical to the native `getboundingclientrect` function, but ensures that
* the method is supported at all (it is in all browsers we claim to support)
* and that the element is in the dom before continuing.
*
* this wrapper function also shims properties which are not provided by some
* older browsers (namely, ie8).
*
* additionally, some browsers do not support adding properties to a
* `clientrect`/`domrect` object; so, we shallow-copy it with the standard
* properties (except `x` and `y` which are not widely supported). this helps
* avoid implementations where keys are non-enumerable.
*
* @param {element} el
* element whose `clientrect` we want to calculate.
*
* @return {object|undefined}
* always returns a plain object - or `undefined` if it cannot.
*/
function getboundingclientrect(el) {
if (el && el.getboundingclientrect && el.parentnode) {
var rect = el.getboundingclientrect();
var result = {};
['bottom', 'height', 'left', 'right', 'top', 'width'].foreach(function (k) {
if (rect[k] !== undefined) {
result[k] = rect[k];
}
});
if (!result.height) {
result.height = parsefloat(computedstyle(el, 'height'));
}
if (!result.width) {
result.width = parsefloat(computedstyle(el, 'width'));
}
return result;
}
}
/**
* represents the position of a dom element on the page.
*
* @typedef {object} module:dom~position
*
* @property {number} left
* pixels to the left.
*
* @property {number} top
* pixels from the top.
*/
/**
* get the position of an element in the dom.
*
* uses `getboundingclientrect` technique from john resig.
*
* @see http://ejohn.org/blog/getboundingclientrect-is-awesome/
*
* @param {element} el
* element from which to get offset.
*
* @return {module:dom~position}
* the position of the element that was passed in.
*/
function findposition(el) {
if (!el || el && !el.offsetparent) {
return {
left: 0,
top: 0,
width: 0,
height: 0
};
}
var width = el.offsetwidth;
var height = el.offsetheight;
var left = 0;
var top = 0;
while (el.offsetparent && el !== global_document__webpack_imported_module_1___default.a[fullscreenapi.fullscreenelement]) {
left += el.offsetleft;
top += el.offsettop;
el = el.offsetparent;
}
return {
left: left,
top: top,
width: width,
height: height
};
}
/**
* represents x and y coordinates for a dom element or mouse pointer.
*
* @typedef {object} module:dom~coordinates
*
* @property {number} x
* x coordinate in pixels
*
* @property {number} y
* y coordinate in pixels
*/
/**
* get the pointer position within an element.
*
* the base on the coordinates are the bottom left of the element.
*
* @param {element} el
* element on which to get the pointer position on.
*
* @param {eventtarget~event} event
* event object.
*
* @return {module:dom~coordinates}
* a coordinates object corresponding to the mouse position.
*
*/
function getpointerposition(el, event) {
var translated = {
x: 0,
y: 0
};
if (is_ios) {
var item = el;
while (item && item.nodename.tolowercase() !== 'html') {
var transform = computedstyle(item, 'transform');
if (/^matrix/.test(transform)) {
var values = transform.slice(7, -1).split(/,\s/).map(number);
translated.x += values[4];
translated.y += values[5];
} else if (/^matrix3d/.test(transform)) {
var _values = transform.slice(9, -1).split(/,\s/).map(number);
translated.x += _values[12];
translated.y += _values[13];
}
item = item.parentnode;
}
}
var position = {};
var boxtarget = findposition(event.target);
var box = findposition(el);
var boxw = box.width;
var boxh = box.height;
var offsety = event.offsety - (box.top - boxtarget.top);
var offsetx = event.offsetx - (box.left - boxtarget.left);
if (event.changedtouches) {
offsetx = event.changedtouches[0].pagex - box.left;
offsety = event.changedtouches[0].pagey + box.top;
if (is_ios) {
offsetx -= translated.x;
offsety -= translated.y;
}
}
position.y = 1 - math.max(0, math.min(1, offsety / boxh));
position.x = math.max(0, math.min(1, offsetx / boxw));
return position;
}
/**
* determines, via duck typing, whether or not a value is a text node.
*
* @param {mixed} value
* check if this value is a text node.
*
* @return {boolean}
* will be `true` if the value is a text node, `false` otherwise.
*/
function istextnode(value) {
return isobject(value) && value.nodetype === 3;
}
/**
* empties the contents of an element.
*
* @param {element} el
* the element to empty children from
*
* @return {element}
* the element with no children
*/
function emptyel(el) {
while (el.firstchild) {
el.removechild(el.firstchild);
}
return el;
}
/**
* this is a mixed value that describes content to be injected into the dom
* via some method. it can be of the following types:
*
* type | description
* -----------|-------------
* `string` | the value will be normalized into a text node.
* `element` | the value will be accepted as-is.
* `textnode` | the value will be accepted as-is.
* `array` | a one-dimensional array of strings, elements, text nodes, or functions. these functions should return a string, element, or text node (any other return value, like an array, will be ignored).
* `function` | a function, which is expected to return a string, element, text node, or array - any of the other possible values described above. this means that a content descriptor could be a function that returns an array of functions, but those second-level functions must return strings, elements, or text nodes.
*
* @typedef {string|element|textnode|array|function} module:dom~contentdescriptor
*/
/**
* normalizes content for eventual insertion into the dom.
*
* this allows a wide range of content definition methods, but helps protect
* from falling into the trap of simply writing to `innerhtml`, which could
* be an xss concern.
*
* the content for an element can be passed in multiple types and
* combinations, whose behavior is as follows:
*
* @param {module:dom~contentdescriptor} content
* a content descriptor value.
*
* @return {array}
* all of the content that was passed in, normalized to an array of
* elements or text nodes.
*/
function normalizecontent(content) {
// first, invoke content if it is a function. if it produces an array,
// that needs to happen before normalization.
if (typeof content === 'function') {
content = content();
} // next up, normalize to an array, so one or many items can be normalized,
// filtered, and returned.
return (array.isarray(content) ? content : [content]).map(function (value) {
// first, invoke value if it is a function to produce a new value,
// which will be subsequently normalized to a node of some kind.
if (typeof value === 'function') {
value = value();
}
if (isel(value) || istextnode(value)) {
return value;
}
if (typeof value === 'string' && /\s/.test(value)) {
return global_document__webpack_imported_module_1___default.a.createtextnode(value);
}
}).filter(function (value) {
return value;
});
}
/**
* normalizes and appends content to an element.
*
* @param {element} el
* element to append normalized content to.
*
* @param {module:dom~contentdescriptor} content
* a content descriptor value.
*
* @return {element}
* the element with appended normalized content.
*/
function appendcontent(el, content) {
normalizecontent(content).foreach(function (node) {
return el.appendchild(node);
});
return el;
}
/**
* normalizes and inserts content into an element; this is identical to
* `appendcontent()`, except it empties the element first.
*
* @param {element} el
* element to insert normalized content into.
*
* @param {module:dom~contentdescriptor} content
* a content descriptor value.
*
* @return {element}
* the element with inserted normalized content.
*/
function insertcontent(el, content) {
return appendcontent(emptyel(el), content);
}
/**
* check if an event was a single left click.
*
* @param {eventtarget~event} event
* event object.
*
* @return {boolean}
* will be `true` if a single left click, `false` otherwise.
*/
function issingleleftclick(event) {
// note: if you create something draggable, be sure to
// call it on both `mousedown` and `mousemove` event,
// otherwise `mousedown` should be enough for a button
if (event.button === undefined && event.buttons === undefined) {
// why do we need `buttons` ?
// because, middle mouse sometimes have this:
// e.button === 0 and e.buttons === 4
// furthermore, we want to prevent combination click, something like
// hold middlemouse then left click, that would be
// e.button === 0, e.buttons === 5
// just `button` is not gonna work
// alright, then what this block does ?
// this is for chrome `simulate mobile devices`
// i want to support this as well
return true;
}
if (event.button === 0 && event.buttons === undefined) {
// touch screen, sometimes on some specific device, `buttons`
// doesn't have anything (safari on ios, blackberry...)
return true;
} // `mouseup` event on a single left click has
// `button` and `buttons` equal to 0
if (event.type === 'mouseup' && event.button === 0 && event.buttons === 0) {
return true;
}
if (event.button !== 0 || event.buttons !== 1) {
// this is the reason we have those if else block above
// if any special case we can catch and let it slide
// we do it above, when get to here, this definitely
// is-not-left-click
return false;
}
return true;
}
/**
* finds a single dom element matching `selector` within the optional
* `context` of another dom element (defaulting to `document`).
*
* @param {string} selector
* a valid css selector, which will be passed to `queryselector`.
*
* @param {element|string} [context=document]
* a dom element within which to query. can also be a selector
* string in which case the first matching element will be used
* as context. if missing (or no element matches selector), falls
* back to `document`.
*
* @return {element|null}
* the element that was found or null.
*/
var $ = createquerier('queryselector');
/**
* finds a all dom elements matching `selector` within the optional
* `context` of another dom element (defaulting to `document`).
*
* @param {string} selector
* a valid css selector, which will be passed to `queryselectorall`.
*
* @param {element|string} [context=document]
* a dom element within which to query. can also be a selector
* string in which case the first matching element will be used
* as context. if missing (or no element matches selector), falls
* back to `document`.
*
* @return {nodelist}
* a element list of elements that were found. will be empty if none
* were found.
*
*/
var $$ = createquerier('queryselectorall');
var dom = /*#__pure__*/object.freeze({
__proto__: null,
isreal: isreal,
isel: isel,
isinframe: isinframe,
createel: createel,
textcontent: textcontent,
prependto: prependto,
hasclass: hasclass,
addclass: addclass,
removeclass: removeclass,
toggleclass: toggleclass,
setattributes: setattributes,
getattributes: getattributes,
getattribute: getattribute,
setattribute: setattribute,
removeattribute: removeattribute,
blocktextselection: blocktextselection,
unblocktextselection: unblocktextselection,
getboundingclientrect: getboundingclientrect,
findposition: findposition,
getpointerposition: getpointerposition,
istextnode: istextnode,
emptyel: emptyel,
normalizecontent: normalizecontent,
appendcontent: appendcontent,
insertcontent: insertcontent,
issingleleftclick: issingleleftclick,
$: $,
$$: $$
});
/**
* @file setup.js - functions for setting up a player without
* user interaction based on the data-setup `attribute` of the video tag.
*
* @module setup
*/
var _windowloaded = false;
var videojs$1;
/**
* set up any tags that have a data-setup `attribute` when the player is started.
*/
var autosetup = function autosetup() {
if (videojs$1.options.autosetup === false) {
return;
}
var vids = array.prototype.slice.call(global_document__webpack_imported_module_1___default.a.getelementsbytagname('video'));
var audios = array.prototype.slice.call(global_document__webpack_imported_module_1___default.a.getelementsbytagname('audio'));
var divs = array.prototype.slice.call(global_document__webpack_imported_module_1___default.a.getelementsbytagname('video-js'));
var mediaels = vids.concat(audios, divs); // check if any media elements exist
if (mediaels && mediaels.length > 0) {
for (var i = 0, e = mediaels.length; i < e; i++) {
var mediael = mediaels[i]; // check if element exists, has getattribute func.
if (mediael && mediael.getattribute) {
// make sure this player hasn't already been set up.
if (mediael.player === undefined) {
var options = mediael.getattribute('data-setup'); // check if data-setup attr exists.
// we only auto-setup if they've added the data-setup attr.
if (options !== null) {
// create new video.js instance.
videojs$1(mediael);
}
} // if getattribute isn't defined, we need to wait for the dom.
} else {
autosetuptimeout(1);
break;
}
} // no videos were found, so keep looping unless page is finished loading.
} else if (!_windowloaded) {
autosetuptimeout(1);
}
};
/**
* wait until the page is loaded before running autosetup. this will be called in
* autosetup if `hasloaded` returns false.
*
* @param {number} wait
* how long to wait in ms
*
* @param {module:videojs} [vjs]
* the videojs library function
*/
function autosetuptimeout(wait, vjs) {
// protect against breakage in non-browser environments
if (!isreal()) {
return;
}
if (vjs) {
videojs$1 = vjs;
}
global_window__webpack_imported_module_0___default.a.settimeout(autosetup, wait);
}
/**
* used to set the internal tracking of window loaded state to true.
*
* @private
*/
function setwindowloaded() {
_windowloaded = true;
global_window__webpack_imported_module_0___default.a.removeeventlistener('load', setwindowloaded);
}
if (isreal()) {
if (global_document__webpack_imported_module_1___default.a.readystate === 'complete') {
setwindowloaded();
} else {
/**
* listen for the load event on window, and set _windowloaded to true.
*
* we use a standard event listener here to avoid incrementing the guid
* before any players are created.
*
* @listens load
*/
global_window__webpack_imported_module_0___default.a.addeventlistener('load', setwindowloaded);
}
}
/**
* @file stylesheet.js
* @module stylesheet
*/
/**
* create a dom syle element given a classname for it.
*
* @param {string} classname
* the classname to add to the created style element.
*
* @return {element}
* the element that was created.
*/
var createstyleelement = function createstyleelement(classname) {
var style = global_document__webpack_imported_module_1___default.a.createelement('style');
style.classname = classname;
return style;
};
/**
* add text to a dom element.
*
* @param {element} el
* the element to add text content to.
*
* @param {string} content
* the text to add to the element.
*/
var settextcontent = function settextcontent(el, content) {
if (el.stylesheet) {
el.stylesheet.csstext = content;
} else {
el.textcontent = content;
}
};
/**
* @file guid.js
* @module guid
*/
// default value for guids. this allows us to reset the guid counter in tests.
//
// the initial guid is 3 because some users have come to rely on the first
// default player id ending up as `vjs_video_3`.
//
// see: https://github.com/videojs/video.js/pull/6216
var _initialguid = 3;
/**
* unique id for an element or function
*
* @type {number}
*/
var _guid = _initialguid;
/**
* get a unique auto-incrementing id by number that has not been returned before.
*
* @return {number}
* a new unique id.
*/
function newguid() {
return _guid++;
}
/**
* @file dom-data.js
* @module dom-data
*/
var fakeweakmap;
if (!global_window__webpack_imported_module_0___default.a.weakmap) {
fakeweakmap = /*#__pure__*/function () {
function fakeweakmap() {
this.vdata = 'vdata' + math.floor(global_window__webpack_imported_module_0___default.a.performance && global_window__webpack_imported_module_0___default.a.performance.now() || date.now());
this.data = {};
}
var _proto = fakeweakmap.prototype;
_proto.set = function set(key, value) {
var access = key[this.vdata] || newguid();
if (!key[this.vdata]) {
key[this.vdata] = access;
}
this.data[access] = value;
return this;
};
_proto.get = function get(key) {
var access = key[this.vdata]; // we have data, return it
if (access) {
return this.data[access];
} // we don't have data, return nothing.
// return undefined explicitly as that's the contract for this method
log$1('we have no data for this element', key);
return undefined;
};
_proto.has = function has(key) {
var access = key[this.vdata];
return access in this.data;
};
_proto["delete"] = function _delete(key) {
var access = key[this.vdata];
if (access) {
delete this.data[access];
delete key[this.vdata];
}
};
return fakeweakmap;
}();
}
/**
* element data store.
*
* allows for binding data to an element without putting it directly on the
* element. ex. event listeners are stored here.
* (also from jsninja.com, slightly modified and updated for closure compiler)
*
* @type {object}
* @private
*/
var domdata = global_window__webpack_imported_module_0___default.a.weakmap ? new weakmap() : new fakeweakmap();
/**
* @file events.js. an event system (john resig - secrets of a js ninja http://jsninja.com/)
* (original book version wasn't completely usable, so fixed some things and made closure compiler compatible)
* this should work very similarly to jquery's events, however it's based off the book version which isn't as
* robust as jquery's, so there's probably some differences.
*
* @file events.js
* @module events
*/
/**
* clean up the listener cache and dispatchers
*
* @param {element|object} elem
* element to clean up
*
* @param {string} type
* type of event to clean up
*/
function _cleanupevents(elem, type) {
if (!domdata.has(elem)) {
return;
}
var data = domdata.get(elem); // remove the events of a particular type if there are none left
if (data.handlers[type].length === 0) {
delete data.handlers[type]; // data.handlers[type] = null;
// setting to null was causing an error with data.handlers
// remove the meta-handler from the element
if (elem.removeeventlistener) {
elem.removeeventlistener(type, data.dispatcher, false);
} else if (elem.detachevent) {
elem.detachevent('on' + type, data.dispatcher);
}
} // remove the events object if there are no types left
if (object.getownpropertynames(data.handlers).length <= 0) {
delete data.handlers;
delete data.dispatcher;
delete data.disabled;
} // finally remove the element data if there is no data left
if (object.getownpropertynames(data).length === 0) {
domdata["delete"](elem);
}
}
/**
* loops through an array of event types and calls the requested method for each type.
*
* @param {function} fn
* the event method we want to use.
*
* @param {element|object} elem
* element or object to bind listeners to
*
* @param {string} type
* type of event to bind to.
*
* @param {eventtarget~eventlistener} callback
* event listener.
*/
function _handlemultipleevents(fn, elem, types, callback) {
types.foreach(function (type) {
// call the event method for each one of the types
fn(elem, type, callback);
});
}
/**
* fix a native event to have standard property values
*
* @param {object} event
* event object to fix.
*
* @return {object}
* fixed event object.
*/
function fixevent(event) {
if (event.fixed_) {
return event;
}
function returntrue() {
return true;
}
function returnfalse() {
return false;
} // test if fixing up is needed
// used to check if !event.stoppropagation instead of ispropagationstopped
// but native events return true for stoppropagation, but don't have
// other expected methods like ispropagationstopped. seems to be a problem
// with the javascript ninja code. so we're just overriding all events now.
if (!event || !event.ispropagationstopped || !event.isimmediatepropagationstopped) {
var old = event || global_window__webpack_imported_module_0___default.a.event;
event = {}; // clone the old object so that we can modify the values event = {};
// ie8 doesn't like when you mess with native event properties
// firefox returns false for event.hasownproperty('type') and other props
// which makes copying more difficult.
// todo: probably best to create a whitelist of event props
for (var key in old) {
// safari 6.0.3 warns you if you try to copy deprecated layerx/y
// chrome warns you if you try to copy deprecated keyboardevent.keylocation
// and webkitmovementx/y
// lighthouse complains if event.path is copied
if (key !== 'layerx' && key !== 'layery' && key !== 'keylocation' && key !== 'webkitmovementx' && key !== 'webkitmovementy' && key !== 'path') {
// chrome 32+ warns if you try to copy deprecated returnvalue, but
// we still want to if preventdefault isn't supported (ie8).
if (!(key === 'returnvalue' && old.preventdefault)) {
event[key] = old[key];
}
}
} // the event occurred on this element
if (!event.target) {
event.target = event.srcelement || global_document__webpack_imported_module_1___default.a;
} // handle which other element the event is related to
if (!event.relatedtarget) {
event.relatedtarget = event.fromelement === event.target ? event.toelement : event.fromelement;
} // stop the default browser action
event.preventdefault = function () {
if (old.preventdefault) {
old.preventdefault();
}
event.returnvalue = false;
old.returnvalue = false;
event.defaultprevented = true;
};
event.defaultprevented = false; // stop the event from bubbling
event.stoppropagation = function () {
if (old.stoppropagation) {
old.stoppropagation();
}
event.cancelbubble = true;
old.cancelbubble = true;
event.ispropagationstopped = returntrue;
};
event.ispropagationstopped = returnfalse; // stop the event from bubbling and executing other handlers
event.stopimmediatepropagation = function () {
if (old.stopimmediatepropagation) {
old.stopimmediatepropagation();
}
event.isimmediatepropagationstopped = returntrue;
event.stoppropagation();
};
event.isimmediatepropagationstopped = returnfalse; // handle mouse position
if (event.clientx !== null && event.clientx !== undefined) {
var doc = global_document__webpack_imported_module_1___default.a.documentelement;
var body = global_document__webpack_imported_module_1___default.a.body;
event.pagex = event.clientx + (doc && doc.scrollleft || body && body.scrollleft || 0) - (doc && doc.clientleft || body && body.clientleft || 0);
event.pagey = event.clienty + (doc && doc.scrolltop || body && body.scrolltop || 0) - (doc && doc.clienttop || body && body.clienttop || 0);
} // handle key presses
event.which = event.charcode || event.keycode; // fix button for mouse clicks:
// 0 == left; 1 == middle; 2 == right
if (event.button !== null && event.button !== undefined) {
// the following is disabled because it does not pass videojs-standard
// and... yikes.
/* eslint-disable */
event.button = event.button & 1 ? 0 : event.button & 4 ? 1 : event.button & 2 ? 2 : 0;
/* eslint-enable */
}
}
event.fixed_ = true; // returns fixed-up instance
return event;
}
/**
* whether passive event listeners are supported
*/
var _supportspassive;
var supportspassive = function supportspassive() {
if (typeof _supportspassive !== 'boolean') {
_supportspassive = false;
try {
var opts = object.defineproperty({}, 'passive', {
get: function get() {
_supportspassive = true;
}
});
global_window__webpack_imported_module_0___default.a.addeventlistener('test', null, opts);
global_window__webpack_imported_module_0___default.a.removeeventlistener('test', null, opts);
} catch (e) {// disregard
}
}
return _supportspassive;
};
/**
* touch events chrome expects to be passive
*/
var passiveevents = ['touchstart', 'touchmove'];
/**
* add an event listener to element
* it stores the handler function in a separate cache object
* and adds a generic handler to the element's event,
* along with a unique id (guid) to the element.
*
* @param {element|object} elem
* element or object to bind listeners to
*
* @param {string|string[]} type
* type of event to bind to.
*
* @param {eventtarget~eventlistener} fn
* event listener.
*/
function on(elem, type, fn) {
if (array.isarray(type)) {
return _handlemultipleevents(on, elem, type, fn);
}
if (!domdata.has(elem)) {
domdata.set(elem, {});
}
var data = domdata.get(elem); // we need a place to store all our handler data
if (!data.handlers) {
data.handlers = {};
}
if (!data.handlers[type]) {
data.handlers[type] = [];
}
if (!fn.guid) {
fn.guid = newguid();
}
data.handlers[type].push(fn);
if (!data.dispatcher) {
data.disabled = false;
data.dispatcher = function (event, hash) {
if (data.disabled) {
return;
}
event = fixevent(event);
var handlers = data.handlers[event.type];
if (handlers) {
// copy handlers so if handlers are added/removed during the process it doesn't throw everything off.
var handlerscopy = handlers.slice(0);
for (var m = 0, n = handlerscopy.length; m < n; m++) {
if (event.isimmediatepropagationstopped()) {
break;
} else {
try {
handlerscopy[m].call(elem, event, hash);
} catch (e) {
log$1.error(e);
}
}
}
}
};
}
if (data.handlers[type].length === 1) {
if (elem.addeventlistener) {
var options = false;
if (supportspassive() && passiveevents.indexof(type) > -1) {
options = {
passive: true
};
}
elem.addeventlistener(type, data.dispatcher, options);
} else if (elem.attachevent) {
elem.attachevent('on' + type, data.dispatcher);
}
}
}
/**
* removes event listeners from an element
*
* @param {element|object} elem
* object to remove listeners from.
*
* @param {string|string[]} [type]
* type of listener to remove. don't include to remove all events from element.
*
* @param {eventtarget~eventlistener} [fn]
* specific listener to remove. don't include to remove listeners for an event
* type.
*/
function off(elem, type, fn) {
// don't want to add a cache object through geteldata if not needed
if (!domdata.has(elem)) {
return;
}
var data = domdata.get(elem); // if no events exist, nothing to unbind
if (!data.handlers) {
return;
}
if (array.isarray(type)) {
return _handlemultipleevents(off, elem, type, fn);
} // utility function
var removetype = function removetype(el, t) {
data.handlers[t] = [];
_cleanupevents(el, t);
}; // are we removing all bound events?
if (type === undefined) {
for (var t in data.handlers) {
if (object.prototype.hasownproperty.call(data.handlers || {}, t)) {
removetype(elem, t);
}
}
return;
}
var handlers = data.handlers[type]; // if no handlers exist, nothing to unbind
if (!handlers) {
return;
} // if no listener was provided, remove all listeners for type
if (!fn) {
removetype(elem, type);
return;
} // we're only removing a single handler
if (fn.guid) {
for (var n = 0; n < handlers.length; n++) {
if (handlers[n].guid === fn.guid) {
handlers.splice(n--, 1);
}
}
}
_cleanupevents(elem, type);
}
/**
* trigger an event for an element
*
* @param {element|object} elem
* element to trigger an event on
*
* @param {eventtarget~event|string} event
* a string (the type) or an event object with a type attribute
*
* @param {object} [hash]
* data hash to pass along with the event
*
* @return {boolean|undefined}
* returns the opposite of `defaultprevented` if default was
* prevented. otherwise, returns `undefined`
*/
function trigger(elem, event, hash) {
// fetches element data and a reference to the parent (for bubbling).
// don't want to add a data object to cache for every parent,
// so checking haseldata first.
var elemdata = domdata.has(elem) ? domdata.get(elem) : {};
var parent = elem.parentnode || elem.ownerdocument; // type = event.type || event,
// handler;
// if an event name was passed as a string, creates an event out of it
if (typeof event === 'string') {
event = {
type: event,
target: elem
};
} else if (!event.target) {
event.target = elem;
} // normalizes the event properties.
event = fixevent(event); // if the passed element has a dispatcher, executes the established handlers.
if (elemdata.dispatcher) {
elemdata.dispatcher.call(elem, event, hash);
} // unless explicitly stopped or the event does not bubble (e.g. media events)
// recursively calls this function to bubble the event up the dom.
if (parent && !event.ispropagationstopped() && event.bubbles === true) {
trigger.call(null, parent, event, hash); // if at the top of the dom, triggers the default action unless disabled.
} else if (!parent && !event.defaultprevented && event.target && event.target[event.type]) {
if (!domdata.has(event.target)) {
domdata.set(event.target, {});
}
var targetdata = domdata.get(event.target); // checks if the target has a default action for this event.
if (event.target[event.type]) {
// temporarily disables event dispatching on the target as we have already executed the handler.
targetdata.disabled = true; // executes the default action.
if (typeof event.target[event.type] === 'function') {
event.target[event.type]();
} // re-enables event dispatching.
targetdata.disabled = false;
}
} // inform the triggerer if the default was prevented by returning false
return !event.defaultprevented;
}
/**
* trigger a listener only once for an event.
*
* @param {element|object} elem
* element or object to bind to.
*
* @param {string|string[]} type
* name/type of event
*
* @param {event~eventlistener} fn
* event listener function
*/
function one(elem, type, fn) {
if (array.isarray(type)) {
return _handlemultipleevents(one, elem, type, fn);
}
var func = function func() {
off(elem, type, func);
fn.apply(this, arguments);
}; // copy the guid to the new function so it can removed using the original function's id
func.guid = fn.guid = fn.guid || newguid();
on(elem, type, func);
}
/**
* trigger a listener only once and then turn if off for all
* configured events
*
* @param {element|object} elem
* element or object to bind to.
*
* @param {string|string[]} type
* name/type of event
*
* @param {event~eventlistener} fn
* event listener function
*/
function any(elem, type, fn) {
var func = function func() {
off(elem, type, func);
fn.apply(this, arguments);
}; // copy the guid to the new function so it can removed using the original function's id
func.guid = fn.guid = fn.guid || newguid(); // multiple ons, but one off for everything
on(elem, type, func);
}
var events = /*#__pure__*/object.freeze({
__proto__: null,
fixevent: fixevent,
on: on,
off: off,
trigger: trigger,
one: one,
any: any
});
/**
* @file fn.js
* @module fn
*/
var update_refresh_interval = 30;
/**
* bind (a.k.a proxy or context). a simple method for changing the context of
* a function.
*
* it also stores a unique id on the function so it can be easily removed from
* events.
*
* @function
* @param {mixed} context
* the object to bind as scope.
*
* @param {function} fn
* the function to be bound to a scope.
*
* @param {number} [uid]
* an optional unique id for the function to be set
*
* @return {function}
* the new function that will be bound into the context given
*/
var bind = function bind(context, fn, uid) {
// make sure the function has a unique id
if (!fn.guid) {
fn.guid = newguid();
} // create the new function that changes the context
var bound = fn.bind(context); // allow for the ability to individualize this function
// needed in the case where multiple objects might share the same prototype
// if both items add an event listener with the same function, then you try to remove just one
// it will remove both because they both have the same guid.
// when using this, you need to use the bind method when you remove the listener as well.
// currently used in text tracks
bound.guid = uid ? uid + '_' + fn.guid : fn.guid;
return bound;
};
/**
* wraps the given function, `fn`, with a new function that only invokes `fn`
* at most once per every `wait` milliseconds.
*
* @function
* @param {function} fn
* the function to be throttled.
*
* @param {number} wait
* the number of milliseconds by which to throttle.
*
* @return {function}
*/
var throttle = function throttle(fn, wait) {
var last = global_window__webpack_imported_module_0___default.a.performance.now();
var throttled = function throttled() {
var now = global_window__webpack_imported_module_0___default.a.performance.now();
if (now - last >= wait) {
fn.apply(void 0, arguments);
last = now;
}
};
return throttled;
};
/**
* creates a debounced function that delays invoking `func` until after `wait`
* milliseconds have elapsed since the last time the debounced function was
* invoked.
*
* inspired by lodash and underscore implementations.
*
* @function
* @param {function} func
* the function to wrap with debounce behavior.
*
* @param {number} wait
* the number of milliseconds to wait after the last invocation.
*
* @param {boolean} [immediate]
* whether or not to invoke the function immediately upon creation.
*
* @param {object} [context=window]
* the "context" in which the debounced function should debounce. for
* example, if this function should be tied to a video.js player,
* the player can be passed here. alternatively, defaults to the
* global `window` object.
*
* @return {function}
* a debounced function.
*/
var debounce = function debounce(func, wait, immediate, context) {
if (context === void 0) {
context = global_window__webpack_imported_module_0___default.a;
}
var timeout;
var cancel = function cancel() {
context.cleartimeout(timeout);
timeout = null;
};
/* eslint-disable consistent-this */
var debounced = function debounced() {
var self = this;
var args = arguments;
var _later = function later() {
timeout = null;
_later = null;
if (!immediate) {
func.apply(self, args);
}
};
if (!timeout && immediate) {
func.apply(self, args);
}
context.cleartimeout(timeout);
timeout = context.settimeout(_later, wait);
};
/* eslint-enable consistent-this */
debounced.cancel = cancel;
return debounced;
};
/**
* @file src/js/event-target.js
*/
/**
* `eventtarget` is a class that can have the same api as the dom `eventtarget`. it
* adds shorthand functions that wrap around lengthy functions. for example:
* the `on` function is a wrapper around `addeventlistener`.
*
* @see [eventtarget spec]{@link https://www.w3.org/tr/dom-level-2-events/events.html#events-eventtarget}
* @class eventtarget
*/
var eventtarget$2 = function eventtarget() {};
/**
* a custom dom event.
*
* @typedef {object} eventtarget~event
* @see [properties]{@link https://developer.mozilla.org/en-us/docs/web/api/customevent}
*/
/**
* all event listeners should follow the following format.
*
* @callback eventtarget~eventlistener
* @this {eventtarget}
*
* @param {eventtarget~event} event
* the event that triggered this function
*
* @param {object} [hash]
* hash of data sent during the event
*/
/**
* an object containing event names as keys and booleans as values.
*
* > note: if an event name is set to a true value here {@link eventtarget#trigger}
* will have extra functionality. see that function for more information.
*
* @property eventtarget.prototype.allowedevents_
* @private
*/
eventtarget$2.prototype.allowedevents_ = {};
/**
* adds an `event listener` to an instance of an `eventtarget`. an `event listener` is a
* function that will get called when an event with a certain name gets triggered.
*
* @param {string|string[]} type
* an event name or an array of event names.
*
* @param {eventtarget~eventlistener} fn
* the function to call with `eventtarget`s
*/
eventtarget$2.prototype.on = function (type, fn) {
// remove the addeventlistener alias before calling events.on
// so we don't get into an infinite type loop
var ael = this.addeventlistener;
this.addeventlistener = function () {};
on(this, type, fn);
this.addeventlistener = ael;
};
/**
* an alias of {@link eventtarget#on}. allows `eventtarget` to mimic
* the standard dom api.
*
* @function
* @see {@link eventtarget#on}
*/
eventtarget$2.prototype.addeventlistener = eventtarget$2.prototype.on;
/**
* removes an `event listener` for a specific event from an instance of `eventtarget`.
* this makes it so that the `event listener` will no longer get called when the
* named event happens.
*
* @param {string|string[]} type
* an event name or an array of event names.
*
* @param {eventtarget~eventlistener} fn
* the function to remove.
*/
eventtarget$2.prototype.off = function (type, fn) {
off(this, type, fn);
};
/**
* an alias of {@link eventtarget#off}. allows `eventtarget` to mimic
* the standard dom api.
*
* @function
* @see {@link eventtarget#off}
*/
eventtarget$2.prototype.removeeventlistener = eventtarget$2.prototype.off;
/**
* this function will add an `event listener` that gets triggered only once. after the
* first trigger it will get removed. this is like adding an `event listener`
* with {@link eventtarget#on} that calls {@link eventtarget#off} on itself.
*
* @param {string|string[]} type
* an event name or an array of event names.
*
* @param {eventtarget~eventlistener} fn
* the function to be called once for each event name.
*/
eventtarget$2.prototype.one = function (type, fn) {
// remove the addeventlistener aliasing events.on
// so we don't get into an infinite type loop
var ael = this.addeventlistener;
this.addeventlistener = function () {};
one(this, type, fn);
this.addeventlistener = ael;
};
eventtarget$2.prototype.any = function (type, fn) {
// remove the addeventlistener aliasing events.on
// so we don't get into an infinite type loop
var ael = this.addeventlistener;
this.addeventlistener = function () {};
any(this, type, fn);
this.addeventlistener = ael;
};
/**
* this function causes an event to happen. this will then cause any `event listeners`
* that are waiting for that event, to get called. if there are no `event listeners`
* for an event then nothing will happen.
*
* if the name of the `event` that is being triggered is in `eventtarget.allowedevents_`.
* trigger will also call the `on` + `uppercaseeventname` function.
*
* example:
* 'click' is in `eventtarget.allowedevents_`, so, trigger will attempt to call
* `onclick` if it exists.
*
* @param {string|eventtarget~event|object} event
* the name of the event, an `event`, or an object with a key of type set to
* an event name.
*/
eventtarget$2.prototype.trigger = function (event) {
var type = event.type || event; // deprecation
// in a future version we should default target to `this`
// similar to how we default the target to `elem` in
// `events.trigger`. right now the default `target` will be
// `document` due to the `event.fixevent` call.
if (typeof event === 'string') {
event = {
type: type
};
}
event = fixevent(event);
if (this.allowedevents_[type] && this['on' + type]) {
this['on' + type](event);
}
trigger(this, event);
};
/**
* an alias of {@link eventtarget#trigger}. allows `eventtarget` to mimic
* the standard dom api.
*
* @function
* @see {@link eventtarget#trigger}
*/
eventtarget$2.prototype.dispatchevent = eventtarget$2.prototype.trigger;
var event_map;
eventtarget$2.prototype.queuetrigger = function (event) {
var _this = this;
// only set up event_map if it'll be used
if (!event_map) {
event_map = new map();
}
var type = event.type || event;
var map = event_map.get(this);
if (!map) {
map = new map();
event_map.set(this, map);
}
var oldtimeout = map.get(type);
map["delete"](type);
global_window__webpack_imported_module_0___default.a.cleartimeout(oldtimeout);
var timeout = global_window__webpack_imported_module_0___default.a.settimeout(function () {
map["delete"](type); // if we cleared out all timeouts for the current target, delete its map
if (map.size === 0) {
map = null;
event_map["delete"](_this);
}
_this.trigger(event);
}, 0);
map.set(type, timeout);
};
/**
* @file mixins/evented.js
* @module evented
*/
var objname = function objname(obj) {
if (typeof obj.name === 'function') {
return obj.name();
}
if (typeof obj.name === 'string') {
return obj.name;
}
if (obj.name_) {
return obj.name_;
}
if (obj.constructor && obj.constructor.name) {
return obj.constructor.name;
}
return typeof obj;
};
/**
* returns whether or not an object has had the evented mixin applied.
*
* @param {object} object
* an object to test.
*
* @return {boolean}
* whether or not the object appears to be evented.
*/
var isevented = function isevented(object) {
return object instanceof eventtarget$2 || !!object.eventbusel_ && ['on', 'one', 'off', 'trigger'].every(function (k) {
return typeof object[k] === 'function';
});
};
/**
* adds a callback to run after the evented mixin applied.
*
* @param {object} object
* an object to add
* @param {function} callback
* the callback to run.
*/
var addeventedcallback = function addeventedcallback(target, callback) {
if (isevented(target)) {
callback();
} else {
if (!target.eventedcallbacks) {
target.eventedcallbacks = [];
}
target.eventedcallbacks.push(callback);
}
};
/**
* whether a value is a valid event type - non-empty string or array.
*
* @private
* @param {string|array} type
* the type value to test.
*
* @return {boolean}
* whether or not the type is a valid event type.
*/
var isvalideventtype = function isvalideventtype(type) {
return (// the regex here verifies that the `type` contains at least one non-
// whitespace character.
typeof type === 'string' && /\s/.test(type) || array.isarray(type) && !!type.length
);
};
/**
* validates a value to determine if it is a valid event target. throws if not.
*
* @private
* @throws {error}
* if the target does not appear to be a valid event target.
*
* @param {object} target
* the object to test.
*
* @param {object} obj
* the evented object we are validating for
*
* @param {string} fnname
* the name of the evented mixin function that called this.
*/
var validatetarget = function validatetarget(target, obj, fnname) {
if (!target || !target.nodename && !isevented(target)) {
throw new error("invalid target for " + objname(obj) + "#" + fnname + "; must be a dom node or evented object.");
}
};
/**
* validates a value to determine if it is a valid event target. throws if not.
*
* @private
* @throws {error}
* if the type does not appear to be a valid event type.
*
* @param {string|array} type
* the type to test.
*
* @param {object} obj
* the evented object we are validating for
*
* @param {string} fnname
* the name of the evented mixin function that called this.
*/
var validateeventtype = function validateeventtype(type, obj, fnname) {
if (!isvalideventtype(type)) {
throw new error("invalid event type for " + objname(obj) + "#" + fnname + "; must be a non-empty string or array.");
}
};
/**
* validates a value to determine if it is a valid listener. throws if not.
*
* @private
* @throws {error}
* if the listener is not a function.
*
* @param {function} listener
* the listener to test.
*
* @param {object} obj
* the evented object we are validating for
*
* @param {string} fnname
* the name of the evented mixin function that called this.
*/
var validatelistener = function validatelistener(listener, obj, fnname) {
if (typeof listener !== 'function') {
throw new error("invalid listener for " + objname(obj) + "#" + fnname + "; must be a function.");
}
};
/**
* takes an array of arguments given to `on()` or `one()`, validates them, and
* normalizes them into an object.
*
* @private
* @param {object} self
* the evented object on which `on()` or `one()` was called. this
* object will be bound as the `this` value for the listener.
*
* @param {array} args
* an array of arguments passed to `on()` or `one()`.
*
* @param {string} fnname
* the name of the evented mixin function that called this.
*
* @return {object}
* an object containing useful values for `on()` or `one()` calls.
*/
var normalizelistenargs = function normalizelistenargs(self, args, fnname) {
// if the number of arguments is less than 3, the target is always the
// evented object itself.
var istargetingself = args.length < 3 || args[0] === self || args[0] === self.eventbusel_;
var target;
var type;
var listener;
if (istargetingself) {
target = self.eventbusel_; // deal with cases where we got 3 arguments, but we are still listening to
// the evented object itself.
if (args.length >= 3) {
args.shift();
}
type = args[0];
listener = args[1];
} else {
target = args[0];
type = args[1];
listener = args[2];
}
validatetarget(target, self, fnname);
validateeventtype(type, self, fnname);
validatelistener(listener, self, fnname);
listener = bind(self, listener);
return {
istargetingself: istargetingself,
target: target,
type: type,
listener: listener
};
};
/**
* adds the listener to the event type(s) on the target, normalizing for
* the type of target.
*
* @private
* @param {element|object} target
* a dom node or evented object.
*
* @param {string} method
* the event binding method to use ("on" or "one").
*
* @param {string|array} type
* one or more event type(s).
*
* @param {function} listener
* a listener function.
*/
var listen = function listen(target, method, type, listener) {
validatetarget(target, target, method);
if (target.nodename) {
events[method](target, type, listener);
} else {
target[method](type, listener);
}
};
/**
* contains methods that provide event capabilities to an object which is passed
* to {@link module:evented|evented}.
*
* @mixin eventedmixin
*/
var eventedmixin = {
/**
* add a listener to an event (or events) on this object or another evented
* object.
*
* @param {string|array|element|object} targetortype
* if this is a string or array, it represents the event type(s)
* that will trigger the listener.
*
* another evented object can be passed here instead, which will
* cause the listener to listen for events on _that_ object.
*
* in either case, the listener's `this` value will be bound to
* this object.
*
* @param {string|array|function} typeorlistener
* if the first argument was a string or array, this should be the
* listener function. otherwise, this is a string or array of event
* type(s).
*
* @param {function} [listener]
* if the first argument was another evented object, this will be
* the listener function.
*/
on: function on() {
var _this = this;
for (var _len = arguments.length, args = new array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
var _normalizelistenargs = normalizelistenargs(this, args, 'on'),
istargetingself = _normalizelistenargs.istargetingself,
target = _normalizelistenargs.target,
type = _normalizelistenargs.type,
listener = _normalizelistenargs.listener;
listen(target, 'on', type, listener); // if this object is listening to another evented object.
if (!istargetingself) {
// if this object is disposed, remove the listener.
var removelistenerondispose = function removelistenerondispose() {
return _this.off(target, type, listener);
}; // use the same function id as the listener so we can remove it later it
// using the id of the original listener.
removelistenerondispose.guid = listener.guid; // add a listener to the target's dispose event as well. this ensures
// that if the target is disposed before this object, we remove the
// removal listener that was just added. otherwise, we create a memory leak.
var removeremoverontargetdispose = function removeremoverontargetdispose() {
return _this.off('dispose', removelistenerondispose);
}; // use the same function id as the listener so we can remove it later
// it using the id of the original listener.
removeremoverontargetdispose.guid = listener.guid;
listen(this, 'on', 'dispose', removelistenerondispose);
listen(target, 'on', 'dispose', removeremoverontargetdispose);
}
},
/**
* add a listener to an event (or events) on this object or another evented
* object. the listener will be called once per event and then removed.
*
* @param {string|array|element|object} targetortype
* if this is a string or array, it represents the event type(s)
* that will trigger the listener.
*
* another evented object can be passed here instead, which will
* cause the listener to listen for events on _that_ object.
*
* in either case, the listener's `this` value will be bound to
* this object.
*
* @param {string|array|function} typeorlistener
* if the first argument was a string or array, this should be the
* listener function. otherwise, this is a string or array of event
* type(s).
*
* @param {function} [listener]
* if the first argument was another evented object, this will be
* the listener function.
*/
one: function one() {
var _this2 = this;
for (var _len2 = arguments.length, args = new array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
var _normalizelistenargs2 = normalizelistenargs(this, args, 'one'),
istargetingself = _normalizelistenargs2.istargetingself,
target = _normalizelistenargs2.target,
type = _normalizelistenargs2.type,
listener = _normalizelistenargs2.listener; // targeting this evented object.
if (istargetingself) {
listen(target, 'one', type, listener); // targeting another evented object.
} else {
// todo: this wrapper is incorrect! it should only
// remove the wrapper for the event type that called it.
// instead all listners are removed on the first trigger!
// see https://github.com/videojs/video.js/issues/5962
var wrapper = function wrapper() {
_this2.off(target, type, wrapper);
for (var _len3 = arguments.length, largs = new array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
largs[_key3] = arguments[_key3];
}
listener.apply(null, largs);
}; // use the same function id as the listener so we can remove it later
// it using the id of the original listener.
wrapper.guid = listener.guid;
listen(target, 'one', type, wrapper);
}
},
/**
* add a listener to an event (or events) on this object or another evented
* object. the listener will only be called once for the first event that is triggered
* then removed.
*
* @param {string|array|element|object} targetortype
* if this is a string or array, it represents the event type(s)
* that will trigger the listener.
*
* another evented object can be passed here instead, which will
* cause the listener to listen for events on _that_ object.
*
* in either case, the listener's `this` value will be bound to
* this object.
*
* @param {string|array|function} typeorlistener
* if the first argument was a string or array, this should be the
* listener function. otherwise, this is a string or array of event
* type(s).
*
* @param {function} [listener]
* if the first argument was another evented object, this will be
* the listener function.
*/
any: function any() {
var _this3 = this;
for (var _len4 = arguments.length, args = new array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
args[_key4] = arguments[_key4];
}
var _normalizelistenargs3 = normalizelistenargs(this, args, 'any'),
istargetingself = _normalizelistenargs3.istargetingself,
target = _normalizelistenargs3.target,
type = _normalizelistenargs3.type,
listener = _normalizelistenargs3.listener; // targeting this evented object.
if (istargetingself) {
listen(target, 'any', type, listener); // targeting another evented object.
} else {
var wrapper = function wrapper() {
_this3.off(target, type, wrapper);
for (var _len5 = arguments.length, largs = new array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
largs[_key5] = arguments[_key5];
}
listener.apply(null, largs);
}; // use the same function id as the listener so we can remove it later
// it using the id of the original listener.
wrapper.guid = listener.guid;
listen(target, 'any', type, wrapper);
}
},
/**
* removes listener(s) from event(s) on an evented object.
*
* @param {string|array|element|object} [targetortype]
* if this is a string or array, it represents the event type(s).
*
* another evented object can be passed here instead, in which case
* all 3 arguments are _required_.
*
* @param {string|array|function} [typeorlistener]
* if the first argument was a string or array, this may be the
* listener function. otherwise, this is a string or array of event
* type(s).
*
* @param {function} [listener]
* if the first argument was another evented object, this will be
* the listener function; otherwise, _all_ listeners bound to the
* event type(s) will be removed.
*/
off: function off$1(targetortype, typeorlistener, listener) {
// targeting this evented object.
if (!targetortype || isvalideventtype(targetortype)) {
off(this.eventbusel_, targetortype, typeorlistener); // targeting another evented object.
} else {
var target = targetortype;
var type = typeorlistener; // fail fast and in a meaningful way!
validatetarget(target, this, 'off');
validateeventtype(type, this, 'off');
validatelistener(listener, this, 'off'); // ensure there's at least a guid, even if the function hasn't been used
listener = bind(this, listener); // remove the dispose listener on this evented object, which was given
// the same guid as the event listener in on().
this.off('dispose', listener);
if (target.nodename) {
off(target, type, listener);
off(target, 'dispose', listener);
} else if (isevented(target)) {
target.off(type, listener);
target.off('dispose', listener);
}
}
},
/**
* fire an event on this evented object, causing its listeners to be called.
*
* @param {string|object} event
* an event type or an object with a type property.
*
* @param {object} [hash]
* an additional object to pass along to listeners.
*
* @return {boolean}
* whether or not the default behavior was prevented.
*/
trigger: function trigger$1(event, hash) {
validatetarget(this.eventbusel_, this, 'trigger');
var type = event && typeof event !== 'string' ? event.type : event;
if (!isvalideventtype(type)) {
var error = "invalid event type for " + objname(this) + "#trigger; " + 'must be a non-empty string or object with a type key that has a non-empty value.';
if (event) {
(this.log || log$1).error(error);
} else {
throw new error(error);
}
}
return trigger(this.eventbusel_, event, hash);
}
};
/**
* applies {@link module:evented~eventedmixin|eventedmixin} to a target object.
*
* @param {object} target
* the object to which to add event methods.
*
* @param {object} [options={}]
* options for customizing the mixin behavior.
*
* @param {string} [options.eventbuskey]
* by default, adds a `eventbusel_` dom element to the target object,
* which is used as an event bus. if the target object already has a
* dom element that should be used, pass its key here.
*
* @return {object}
* the target object.
*/
function evented(target, options) {
if (options === void 0) {
options = {};
}
var _options = options,
eventbuskey = _options.eventbuskey; // set or create the eventbusel_.
if (eventbuskey) {
if (!target[eventbuskey].nodename) {
throw new error("the eventbuskey \"" + eventbuskey + "\" does not refer to an element.");
}
target.eventbusel_ = target[eventbuskey];
} else {
target.eventbusel_ = createel('span', {
classname: 'vjs-event-bus'
});
}
assign(target, eventedmixin);
if (target.eventedcallbacks) {
target.eventedcallbacks.foreach(function (callback) {
callback();
});
} // when any evented object is disposed, it removes all its listeners.
target.on('dispose', function () {
target.off();
[target, target.el_, target.eventbusel_].foreach(function (val) {
if (val && domdata.has(val)) {
domdata["delete"](val);
}
});
global_window__webpack_imported_module_0___default.a.settimeout(function () {
target.eventbusel_ = null;
}, 0);
});
return target;
}
/**
* @file mixins/stateful.js
* @module stateful
*/
/**
* contains methods that provide statefulness to an object which is passed
* to {@link module:stateful}.
*
* @mixin statefulmixin
*/
var statefulmixin = {
/**
* a hash containing arbitrary keys and values representing the state of
* the object.
*
* @type {object}
*/
state: {},
/**
* set the state of an object by mutating its
* {@link module:stateful~statefulmixin.state|state} object in place.
*
* @fires module:stateful~statefulmixin#statechanged
* @param {object|function} stateupdates
* a new set of properties to shallow-merge into the plugin state.
* can be a plain object or a function returning a plain object.
*
* @return {object|undefined}
* an object containing changes that occurred. if no changes
* occurred, returns `undefined`.
*/
setstate: function setstate(stateupdates) {
var _this = this;
// support providing the `stateupdates` state as a function.
if (typeof stateupdates === 'function') {
stateupdates = stateupdates();
}
var changes;
each(stateupdates, function (value, key) {
// record the change if the value is different from what's in the
// current state.
if (_this.state[key] !== value) {
changes = changes || {};
changes[key] = {
from: _this.state[key],
to: value
};
}
_this.state[key] = value;
}); // only trigger "statechange" if there were changes and we have a trigger
// function. this allows us to not require that the target object be an
// evented object.
if (changes && isevented(this)) {
/**
* an event triggered on an object that is both
* {@link module:stateful|stateful} and {@link module:evented|evented}
* indicating that its state has changed.
*
* @event module:stateful~statefulmixin#statechanged
* @type {object}
* @property {object} changes
* a hash containing the properties that were changed and
* the values they were changed `from` and `to`.
*/
this.trigger({
changes: changes,
type: 'statechanged'
});
}
return changes;
}
};
/**
* applies {@link module:stateful~statefulmixin|statefulmixin} to a target
* object.
*
* if the target object is {@link module:evented|evented} and has a
* `handlestatechanged` method, that method will be automatically bound to the
* `statechanged` event on itself.
*
* @param {object} target
* the object to be made stateful.
*
* @param {object} [defaultstate]
* a default set of properties to populate the newly-stateful object's
* `state` property.
*
* @return {object}
* returns the `target`.
*/
function stateful(target, defaultstate) {
assign(target, statefulmixin); // this happens after the mixing-in because we need to replace the `state`
// added in that step.
target.state = assign({}, target.state, defaultstate); // auto-bind the `handlestatechanged` method of the target object if it exists.
if (typeof target.handlestatechanged === 'function' && isevented(target)) {
target.on('statechanged', target.handlestatechanged);
}
return target;
}
/**
* @file string-cases.js
* @module to-lower-case
*/
/**
* lowercase the first letter of a string.
*
* @param {string} string
* string to be lowercased
*
* @return {string}
* the string with a lowercased first letter
*/
var tolowercase = function tolowercase(string) {
if (typeof string !== 'string') {
return string;
}
return string.replace(/./, function (w) {
return w.tolowercase();
});
};
/**
* uppercase the first letter of a string.
*
* @param {string} string
* string to be uppercased
*
* @return {string}
* the string with an uppercased first letter
*/
var totitlecase$1 = function totitlecase(string) {
if (typeof string !== 'string') {
return string;
}
return string.replace(/./, function (w) {
return w.touppercase();
});
};
/**
* compares the titlecase versions of the two strings for equality.
*
* @param {string} str1
* the first string to compare
*
* @param {string} str2
* the second string to compare
*
* @return {boolean}
* whether the titlecase versions of the strings are equal
*/
var titlecaseequals = function titlecaseequals(str1, str2) {
return totitlecase$1(str1) === totitlecase$1(str2);
};
/**
* @file merge-options.js
* @module merge-options
*/
/**
* merge two objects recursively.
*
* performs a deep merge like
* {@link https://lodash.com/docs/4.17.10#merge|lodash.merge}, but only merges
* plain objects (not arrays, elements, or anything else).
*
* non-plain object values will be copied directly from the right-most
* argument.
*
* @static
* @param {object[]} sources
* one or more objects to merge into a new object.
*
* @return {object}
* a new object that is the merged result of all sources.
*/
function mergeoptions$3() {
var result = {};
for (var _len = arguments.length, sources = new array(_len), _key = 0; _key < _len; _key++) {
sources[_key] = arguments[_key];
}
sources.foreach(function (source) {
if (!source) {
return;
}
each(source, function (value, key) {
if (!isplain(value)) {
result[key] = value;
return;
}
if (!isplain(result[key])) {
result[key] = {};
}
result[key] = mergeoptions$3(result[key], value);
});
});
return result;
}
var mapsham = /*#__pure__*/function () {
function mapsham() {
this.map_ = {};
}
var _proto = mapsham.prototype;
_proto.has = function has(key) {
return key in this.map_;
};
_proto["delete"] = function _delete(key) {
var has = this.has(key);
delete this.map_[key];
return has;
};
_proto.set = function set(key, value) {
this.map_[key] = value;
return this;
};
_proto.foreach = function foreach(callback, thisarg) {
for (var key in this.map_) {
callback.call(thisarg, this.map_[key], key, this);
}
};
return mapsham;
}();
var map$1 = global_window__webpack_imported_module_0___default.a.map ? global_window__webpack_imported_module_0___default.a.map : mapsham;
var setsham = /*#__pure__*/function () {
function setsham() {
this.set_ = {};
}
var _proto = setsham.prototype;
_proto.has = function has(key) {
return key in this.set_;
};
_proto["delete"] = function _delete(key) {
var has = this.has(key);
delete this.set_[key];
return has;
};
_proto.add = function add(key) {
this.set_[key] = 1;
return this;
};
_proto.foreach = function foreach(callback, thisarg) {
for (var key in this.set_) {
callback.call(thisarg, key, key, this);
}
};
return setsham;
}();
var set$1 = global_window__webpack_imported_module_0___default.a.set ? global_window__webpack_imported_module_0___default.a.set : setsham;
/**
* player component - base class for all ui objects
*
* @file component.js
*/
/**
* base class for all ui components.
* components are ui objects which represent both a javascript object and an element
* in the dom. they can be children of other components, and can have
* children themselves.
*
* components can also use methods from {@link eventtarget}
*/
var component$1 = /*#__pure__*/function () {
/**
* a callback that is called when a component is ready. does not have any
* paramters and any callback value will be ignored.
*
* @callback component~readycallback
* @this component
*/
/**
* creates an instance of this class.
*
* @param {player} player
* the `player` that this class should be attached to.
*
* @param {object} [options]
* the key/value store of component options.
*
* @param {object[]} [options.children]
* an array of children objects to intialize this component with. children objects have
* a name property that will be used if more than one component of the same type needs to be
* added.
*
* @param {string} [options.classname]
* a class or space separated list of classes to add the component
*
* @param {component~readycallback} [ready]
* function that gets called when the `component` is ready.
*/
function component(player, options, ready) {
var _this = this;
// the component might be the player itself and we can't pass `this` to super
if (!player && this.play) {
this.player_ = player = this; // eslint-disable-line
} else {
this.player_ = player;
}
this.isdisposed_ = false; // hold the reference to the parent component via `addchild` method
this.parentcomponent_ = null; // make a copy of prototype.options_ to protect against overriding defaults
this.options_ = mergeoptions$3({}, this.options_); // updated options with supplied options
options = this.options_ = mergeoptions$3(this.options_, options); // get id from options or options element if one is supplied
this.id_ = options.id || options.el && options.el.id; // if there was no id from the options, generate one
if (!this.id_) {
// don't require the player id function in the case of mock players
var id = player && player.id && player.id() || 'no_player';
this.id_ = id + "_component_" + newguid();
}
this.name_ = options.name || null; // create element if one wasn't provided in options
if (options.el) {
this.el_ = options.el;
} else if (options.createel !== false) {
this.el_ = this.createel();
}
if (options.classname && this.el_) {
options.classname.split(' ').foreach(function (c) {
return _this.addclass(c);
});
} // if evented is anything except false, we want to mixin in evented
if (options.evented !== false) {
// make this an evented object and use `el_`, if available, as its event bus
evented(this, {
eventbuskey: this.el_ ? 'el_' : null
});
this.handlelanguagechange = this.handlelanguagechange.bind(this);
this.on(this.player_, 'languagechange', this.handlelanguagechange);
}
stateful(this, this.constructor.defaultstate);
this.children_ = [];
this.childindex_ = {};
this.childnameindex_ = {};
this.settimeoutids_ = new set$1();
this.setintervalids_ = new set$1();
this.rafids_ = new set$1();
this.namedrafs_ = new map$1();
this.clearingtimersondispose_ = false; // add any child components in options
if (options.initchildren !== false) {
this.initchildren();
} // don't want to trigger ready here or it will go before init is actually
// finished for all children that run this constructor
this.ready(ready);
if (options.reporttouchactivity !== false) {
this.enabletouchactivity();
}
}
/**
* dispose of the `component` and all child components.
*
* @fires component#dispose
*
* @param {object} options
* @param {element} options.originalel element with which to replace player element
*/
var _proto = component.prototype;
_proto.dispose = function dispose(options) {
if (options === void 0) {
options = {};
}
// bail out if the component has already been disposed.
if (this.isdisposed_) {
return;
}
if (this.readyqueue_) {
this.readyqueue_.length = 0;
}
/**
* triggered when a `component` is disposed.
*
* @event component#dispose
* @type {eventtarget~event}
*
* @property {boolean} [bubbles=false]
* set to false so that the dispose event does not
* bubble up
*/
this.trigger({
type: 'dispose',
bubbles: false
});
this.isdisposed_ = true; // dispose all children.
if (this.children_) {
for (var i = this.children_.length - 1; i >= 0; i--) {
if (this.children_[i].dispose) {
this.children_[i].dispose();
}
}
} // delete child references
this.children_ = null;
this.childindex_ = null;
this.childnameindex_ = null;
this.parentcomponent_ = null;
if (this.el_) {
// remove element from dom
if (this.el_.parentnode) {
if (options.restoreel) {
this.el_.parentnode.replacechild(options.restoreel, this.el_);
} else {
this.el_.parentnode.removechild(this.el_);
}
}
this.el_ = null;
} // remove reference to the player after disposing of the element
this.player_ = null;
}
/**
* determine whether or not this component has been disposed.
*
* @return {boolean}
* if the component has been disposed, will be `true`. otherwise, `false`.
*/
;
_proto.isdisposed = function isdisposed() {
return boolean(this.isdisposed_);
}
/**
* return the {@link player} that the `component` has attached to.
*
* @return {player}
* the player that this `component` has attached to.
*/
;
_proto.player = function player() {
return this.player_;
}
/**
* deep merge of options objects with new options.
* > note: when both `obj` and `options` contain properties whose values are objects.
* the two properties get merged using {@link module:mergeoptions}
*
* @param {object} obj
* the object that contains new options.
*
* @return {object}
* a new object of `this.options_` and `obj` merged together.
*/
;
_proto.options = function options(obj) {
if (!obj) {
return this.options_;
}
this.options_ = mergeoptions$3(this.options_, obj);
return this.options_;
}
/**
* get the `component`s dom element
*
* @return {element}
* the dom element for this `component`.
*/
;
_proto.el = function el() {
return this.el_;
}
/**
* create the `component`s dom element.
*
* @param {string} [tagname]
* element's dom node type. e.g. 'div'
*
* @param {object} [properties]
* an object of properties that should be set.
*
* @param {object} [attributes]
* an object of attributes that should be set.
*
* @return {element}
* the element that gets created.
*/
;
_proto.createel = function createel$1(tagname, properties, attributes) {
return createel(tagname, properties, attributes);
}
/**
* localize a string given the string in english.
*
* if tokens are provided, it'll try and run a simple token replacement on the provided string.
* the tokens it looks for look like `{1}` with the index being 1-indexed into the tokens array.
*
* if a `defaultvalue` is provided, it'll use that over `string`,
* if a value isn't found in provided language files.
* this is useful if you want to have a descriptive key for token replacement
* but have a succinct localized string and not require `en.json` to be included.
*
* currently, it is used for the progress bar timing.
* ```js
* {
* "progress bar timing: currenttime={1} duration={2}": "{1} of {2}"
* }
* ```
* it is then used like so:
* ```js
* this.localize('progress bar timing: currenttime={1} duration{2}',
* [this.player_.currenttime(), this.player_.duration()],
* '{1} of {2}');
* ```
*
* which outputs something like: `01:23 of 24:56`.
*
*
* @param {string} string
* the string to localize and the key to lookup in the language files.
* @param {string[]} [tokens]
* if the current item has token replacements, provide the tokens here.
* @param {string} [defaultvalue]
* defaults to `string`. can be a default value to use for token replacement
* if the lookup key is needed to be separate.
*
* @return {string}
* the localized string or if no localization exists the english string.
*/
;
_proto.localize = function localize(string, tokens, defaultvalue) {
if (defaultvalue === void 0) {
defaultvalue = string;
}
var code = this.player_.language && this.player_.language();
var languages = this.player_.languages && this.player_.languages();
var language = languages && languages[code];
var primarycode = code && code.split('-')[0];
var primarylang = languages && languages[primarycode];
var localizedstring = defaultvalue;
if (language && language[string]) {
localizedstring = language[string];
} else if (primarylang && primarylang[string]) {
localizedstring = primarylang[string];
}
if (tokens) {
localizedstring = localizedstring.replace(/\{(\d+)\}/g, function (match, index) {
var value = tokens[index - 1];
var ret = value;
if (typeof value === 'undefined') {
ret = match;
}
return ret;
});
}
return localizedstring;
}
/**
* handles language change for the player in components. should be overriden by sub-components.
*
* @abstract
*/
;
_proto.handlelanguagechange = function handlelanguagechange() {}
/**
* return the `component`s dom element. this is where children get inserted.
* this will usually be the the same as the element returned in {@link component#el}.
*
* @return {element}
* the content element for this `component`.
*/
;
_proto.contentel = function contentel() {
return this.contentel_ || this.el_;
}
/**
* get this `component`s id
*
* @return {string}
* the id of this `component`
*/
;
_proto.id = function id() {
return this.id_;
}
/**
* get the `component`s name. the name gets used to reference the `component`
* and is set during registration.
*
* @return {string}
* the name of this `component`.
*/
;
_proto.name = function name() {
return this.name_;
}
/**
* get an array of all child components
*
* @return {array}
* the children
*/
;
_proto.children = function children() {
return this.children_;
}
/**
* returns the child `component` with the given `id`.
*
* @param {string} id
* the id of the child `component` to get.
*
* @return {component|undefined}
* the child `component` with the given `id` or undefined.
*/
;
_proto.getchildbyid = function getchildbyid(id) {
return this.childindex_[id];
}
/**
* returns the child `component` with the given `name`.
*
* @param {string} name
* the name of the child `component` to get.
*
* @return {component|undefined}
* the child `component` with the given `name` or undefined.
*/
;
_proto.getchild = function getchild(name) {
if (!name) {
return;
}
return this.childnameindex_[name];
}
/**
* returns the descendant `component` following the givent
* descendant `names`. for instance ['foo', 'bar', 'baz'] would
* try to get 'foo' on the current component, 'bar' on the 'foo'
* component and 'baz' on the 'bar' component and return undefined
* if any of those don't exist.
*
* @param {...string[]|...string} names
* the name of the child `component` to get.
*
* @return {component|undefined}
* the descendant `component` following the given descendant
* `names` or undefined.
*/
;
_proto.getdescendant = function getdescendant() {
for (var _len = arguments.length, names = new array(_len), _key = 0; _key < _len; _key++) {
names[_key] = arguments[_key];
}
// flatten array argument into the main array
names = names.reduce(function (acc, n) {
return acc.concat(n);
}, []);
var currentchild = this;
for (var i = 0; i < names.length; i++) {
currentchild = currentchild.getchild(names[i]);
if (!currentchild || !currentchild.getchild) {
return;
}
}
return currentchild;
}
/**
* add a child `component` inside the current `component`.
*
*
* @param {string|component} child
* the name or instance of a child to add.
*
* @param {object} [options={}]
* the key/value store of options that will get passed to children of
* the child.
*
* @param {number} [index=this.children_.length]
* the index to attempt to add a child into.
*
* @return {component}
* the `component` that gets added as a child. when using a string the
* `component` will get created by this process.
*/
;
_proto.addchild = function addchild(child, options, index) {
if (options === void 0) {
options = {};
}
if (index === void 0) {
index = this.children_.length;
}
var component;
var componentname; // if child is a string, create component with options
if (typeof child === 'string') {
componentname = totitlecase$1(child);
var componentclassname = options.componentclass || componentname; // set name through options
options.name = componentname; // create a new object & element for this controls set
// if there's no .player_, this is a player
var componentclass = component.getcomponent(componentclassname);
if (!componentclass) {
throw new error("component " + componentclassname + " does not exist");
} // data stored directly on the videojs object may be
// misidentified as a component to retain
// backwards-compatibility with 4.x. check to make sure the
// component class can be instantiated.
if (typeof componentclass !== 'function') {
return null;
}
component = new componentclass(this.player_ || this, options); // child is a component instance
} else {
component = child;
}
if (component.parentcomponent_) {
component.parentcomponent_.removechild(component);
}
this.children_.splice(index, 0, component);
component.parentcomponent_ = this;
if (typeof component.id === 'function') {
this.childindex_[component.id()] = component;
} // if a name wasn't used to create the component, check if we can use the
// name function of the component
componentname = componentname || component.name && totitlecase$1(component.name());
if (componentname) {
this.childnameindex_[componentname] = component;
this.childnameindex_[tolowercase(componentname)] = component;
} // add the ui object's element to the container div (box)
// having an element is not required
if (typeof component.el === 'function' && component.el()) {
// if inserting before a component, insert before that component's element
var refnode = null;
if (this.children_[index + 1]) {
// most children are components, but the video tech is an html element
if (this.children_[index + 1].el_) {
refnode = this.children_[index + 1].el_;
} else if (isel(this.children_[index + 1])) {
refnode = this.children_[index + 1];
}
}
this.contentel().insertbefore(component.el(), refnode);
} // return so it can stored on parent object if desired.
return component;
}
/**
* remove a child `component` from this `component`s list of children. also removes
* the child `component`s element from this `component`s element.
*
* @param {component} component
* the child `component` to remove.
*/
;
_proto.removechild = function removechild(component) {
if (typeof component === 'string') {
component = this.getchild(component);
}
if (!component || !this.children_) {
return;
}
var childfound = false;
for (var i = this.children_.length - 1; i >= 0; i--) {
if (this.children_[i] === component) {
childfound = true;
this.children_.splice(i, 1);
break;
}
}
if (!childfound) {
return;
}
component.parentcomponent_ = null;
this.childindex_[component.id()] = null;
this.childnameindex_[totitlecase$1(component.name())] = null;
this.childnameindex_[tolowercase(component.name())] = null;
var compel = component.el();
if (compel && compel.parentnode === this.contentel()) {
this.contentel().removechild(component.el());
}
}
/**
* add and initialize default child `component`s based upon options.
*/
;
_proto.initchildren = function initchildren() {
var _this2 = this;
var children = this.options_.children;
if (children) {
// `this` is `parent`
var parentoptions = this.options_;
var handleadd = function handleadd(child) {
var name = child.name;
var opts = child.opts; // allow options for children to be set at the parent options
// e.g. videojs(id, { controlbar: false });
// instead of videojs(id, { children: { controlbar: false });
if (parentoptions[name] !== undefined) {
opts = parentoptions[name];
} // allow for disabling default components
// e.g. options['children']['posterimage'] = false
if (opts === false) {
return;
} // allow options to be passed as a simple boolean if no configuration
// is necessary.
if (opts === true) {
opts = {};
} // we also want to pass the original player options
// to each component as well so they don't need to
// reach back into the player for options later.
opts.playeroptions = _this2.options_.playeroptions; // create and add the child component.
// add a direct reference to the child by name on the parent instance.
// if two of the same component are used, different names should be supplied
// for each
var newchild = _this2.addchild(name, opts);
if (newchild) {
_this2[name] = newchild;
}
}; // allow for an array of children details to passed in the options
var workingchildren;
var tech = component.getcomponent('tech');
if (array.isarray(children)) {
workingchildren = children;
} else {
workingchildren = object.keys(children);
}
workingchildren // children that are in this.options_ but also in workingchildren would
// give us extra children we do not want. so, we want to filter them out.
.concat(object.keys(this.options_).filter(function (child) {
return !workingchildren.some(function (wchild) {
if (typeof wchild === 'string') {
return child === wchild;
}
return child === wchild.name;
});
})).map(function (child) {
var name;
var opts;
if (typeof child === 'string') {
name = child;
opts = children[name] || _this2.options_[name] || {};
} else {
name = child.name;
opts = child;
}
return {
name: name,
opts: opts
};
}).filter(function (child) {
// we have to make sure that child.name isn't in the techorder since
// techs are registerd as components but can't aren't compatible
// see https://github.com/videojs/video.js/issues/2772
var c = component.getcomponent(child.opts.componentclass || totitlecase$1(child.name));
return c && !tech.istech(c);
}).foreach(handleadd);
}
}
/**
* builds the default dom class name. should be overriden by sub-components.
*
* @return {string}
* the dom class name for this object.
*
* @abstract
*/
;
_proto.buildcssclass = function buildcssclass() {
// child classes can include a function that does:
// return 'class name' + this._super();
return '';
}
/**
* bind a listener to the component's ready state.
* different from event listeners in that if the ready event has already happened
* it will trigger the function immediately.
*
* @return {component}
* returns itself; method can be chained.
*/
;
_proto.ready = function ready(fn, sync) {
if (sync === void 0) {
sync = false;
}
if (!fn) {
return;
}
if (!this.isready_) {
this.readyqueue_ = this.readyqueue_ || [];
this.readyqueue_.push(fn);
return;
}
if (sync) {
fn.call(this);
} else {
// call the function asynchronously by default for consistency
this.settimeout(fn, 1);
}
}
/**
* trigger all the ready listeners for this `component`.
*
* @fires component#ready
*/
;
_proto.triggerready = function triggerready() {
this.isready_ = true; // ensure ready is triggered asynchronously
this.settimeout(function () {
var readyqueue = this.readyqueue_; // reset ready queue
this.readyqueue_ = [];
if (readyqueue && readyqueue.length > 0) {
readyqueue.foreach(function (fn) {
fn.call(this);
}, this);
} // allow for using event listeners also
/**
* triggered when a `component` is ready.
*
* @event component#ready
* @type {eventtarget~event}
*/
this.trigger('ready');
}, 1);
}
/**
* find a single dom element matching a `selector`. this can be within the `component`s
* `contentel()` or another custom context.
*
* @param {string} selector
* a valid css selector, which will be passed to `queryselector`.
*
* @param {element|string} [context=this.contentel()]
* a dom element within which to query. can also be a selector string in
* which case the first matching element will get used as context. if
* missing `this.contentel()` gets used. if `this.contentel()` returns
* nothing it falls back to `document`.
*
* @return {element|null}
* the dom element that was found, or null
*
* @see [information on css selectors](https://developer.mozilla.org/en-us/docs/web/guide/css/getting_started/selectors)
*/
;
_proto.$ = function $$1(selector, context) {
return $(selector, context || this.contentel());
}
/**
* finds all dom element matching a `selector`. this can be within the `component`s
* `contentel()` or another custom context.
*
* @param {string} selector
* a valid css selector, which will be passed to `queryselectorall`.
*
* @param {element|string} [context=this.contentel()]
* a dom element within which to query. can also be a selector string in
* which case the first matching element will get used as context. if
* missing `this.contentel()` gets used. if `this.contentel()` returns
* nothing it falls back to `document`.
*
* @return {nodelist}
* a list of dom elements that were found
*
* @see [information on css selectors](https://developer.mozilla.org/en-us/docs/web/guide/css/getting_started/selectors)
*/
;
_proto.$$ = function $$$1(selector, context) {
return $$(selector, context || this.contentel());
}
/**
* check if a component's element has a css class name.
*
* @param {string} classtocheck
* css class name to check.
*
* @return {boolean}
* - true if the `component` has the class.
* - false if the `component` does not have the class`
*/
;
_proto.hasclass = function hasclass$1(classtocheck) {
return hasclass(this.el_, classtocheck);
}
/**
* add a css class name to the `component`s element.
*
* @param {string} classtoadd
* css class name to add
*/
;
_proto.addclass = function addclass$1(classtoadd) {
addclass(this.el_, classtoadd);
}
/**
* remove a css class name from the `component`s element.
*
* @param {string} classtoremove
* css class name to remove
*/
;
_proto.removeclass = function removeclass$1(classtoremove) {
removeclass(this.el_, classtoremove);
}
/**
* add or remove a css class name from the component's element.
* - `classtotoggle` gets added when {@link component#hasclass} would return false.
* - `classtotoggle` gets removed when {@link component#hasclass} would return true.
*
* @param {string} classtotoggle
* the class to add or remove based on (@link component#hasclass}
*
* @param {boolean|dom~predicate} [predicate]
* an {@link dom~predicate} function or a boolean
*/
;
_proto.toggleclass = function toggleclass$1(classtotoggle, predicate) {
toggleclass(this.el_, classtotoggle, predicate);
}
/**
* show the `component`s element if it is hidden by removing the
* 'vjs-hidden' class name from it.
*/
;
_proto.show = function show() {
this.removeclass('vjs-hidden');
}
/**
* hide the `component`s element if it is currently showing by adding the
* 'vjs-hidden` class name to it.
*/
;
_proto.hide = function hide() {
this.addclass('vjs-hidden');
}
/**
* lock a `component`s element in its visible state by adding the 'vjs-lock-showing'
* class name to it. used during fadein/fadeout.
*
* @private
*/
;
_proto.lockshowing = function lockshowing() {
this.addclass('vjs-lock-showing');
}
/**
* unlock a `component`s element from its visible state by removing the 'vjs-lock-showing'
* class name from it. used during fadein/fadeout.
*
* @private
*/
;
_proto.unlockshowing = function unlockshowing() {
this.removeclass('vjs-lock-showing');
}
/**
* get the value of an attribute on the `component`s element.
*
* @param {string} attribute
* name of the attribute to get the value from.
*
* @return {string|null}
* - the value of the attribute that was asked for.
* - can be an empty string on some browsers if the attribute does not exist
* or has no value
* - most browsers will return null if the attibute does not exist or has
* no value.
*
* @see [dom api]{@link https://developer.mozilla.org/en-us/docs/web/api/element/getattribute}
*/
;
_proto.getattribute = function getattribute$1(attribute) {
return getattribute(this.el_, attribute);
}
/**
* set the value of an attribute on the `component`'s element
*
* @param {string} attribute
* name of the attribute to set.
*
* @param {string} value
* value to set the attribute to.
*
* @see [dom api]{@link https://developer.mozilla.org/en-us/docs/web/api/element/setattribute}
*/
;
_proto.setattribute = function setattribute$1(attribute, value) {
setattribute(this.el_, attribute, value);
}
/**
* remove an attribute from the `component`s element.
*
* @param {string} attribute
* name of the attribute to remove.
*
* @see [dom api]{@link https://developer.mozilla.org/en-us/docs/web/api/element/removeattribute}
*/
;
_proto.removeattribute = function removeattribute$1(attribute) {
removeattribute(this.el_, attribute);
}
/**
* get or set the width of the component based upon the css styles.
* see {@link component#dimension} for more detailed information.
*
* @param {number|string} [num]
* the width that you want to set postfixed with '%', 'px' or nothing.
*
* @param {boolean} [skiplisteners]
* skip the componentresize event trigger
*
* @return {number|string}
* the width when getting, zero if there is no width. can be a string
* postpixed with '%' or 'px'.
*/
;
_proto.width = function width(num, skiplisteners) {
return this.dimension('width', num, skiplisteners);
}
/**
* get or set the height of the component based upon the css styles.
* see {@link component#dimension} for more detailed information.
*
* @param {number|string} [num]
* the height that you want to set postfixed with '%', 'px' or nothing.
*
* @param {boolean} [skiplisteners]
* skip the componentresize event trigger
*
* @return {number|string}
* the width when getting, zero if there is no width. can be a string
* postpixed with '%' or 'px'.
*/
;
_proto.height = function height(num, skiplisteners) {
return this.dimension('height', num, skiplisteners);
}
/**
* set both the width and height of the `component` element at the same time.
*
* @param {number|string} width
* width to set the `component`s element to.
*
* @param {number|string} height
* height to set the `component`s element to.
*/
;
_proto.dimensions = function dimensions(width, height) {
// skip componentresize listeners on width for optimization
this.width(width, true);
this.height(height);
}
/**
* get or set width or height of the `component` element. this is the shared code
* for the {@link component#width} and {@link component#height}.
*
* things to know:
* - if the width or height in an number this will return the number postfixed with 'px'.
* - if the width/height is a percent this will return the percent postfixed with '%'
* - hidden elements have a width of 0 with `window.getcomputedstyle`. this function
* defaults to the `component`s `style.width` and falls back to `window.getcomputedstyle`.
* see [this]{@link http://www.foliotek.com/devblog/getting-the-width-of-a-hidden-element-with-jquery-using-width/}
* for more information
* - if you want the computed style of the component, use {@link component#currentwidth}
* and {@link {component#currentheight}
*
* @fires component#componentresize
*
* @param {string} widthorheight
8 'width' or 'height'
*
* @param {number|string} [num]
8 new dimension
*
* @param {boolean} [skiplisteners]
* skip componentresize event trigger
*
* @return {number}
* the dimension when getting or 0 if unset
*/
;
_proto.dimension = function dimension(widthorheight, num, skiplisteners) {
if (num !== undefined) {
// set to zero if null or literally nan (nan !== nan)
if (num === null || num !== num) {
num = 0;
} // check if using css width/height (% or px) and adjust
if (('' + num).indexof('%') !== -1 || ('' + num).indexof('px') !== -1) {
this.el_.style[widthorheight] = num;
} else if (num === 'auto') {
this.el_.style[widthorheight] = '';
} else {
this.el_.style[widthorheight] = num + 'px';
} // skiplisteners allows us to avoid triggering the resize event when setting both width and height
if (!skiplisteners) {
/**
* triggered when a component is resized.
*
* @event component#componentresize
* @type {eventtarget~event}
*/
this.trigger('componentresize');
}
return;
} // not setting a value, so getting it
// make sure element exists
if (!this.el_) {
return 0;
} // get dimension value from style
var val = this.el_.style[widthorheight];
var pxindex = val.indexof('px');
if (pxindex !== -1) {
// return the pixel value with no 'px'
return parseint(val.slice(0, pxindex), 10);
} // no px so using % or no style was set, so falling back to offsetwidth/height
// if component has display:none, offset will return 0
// todo: handle display:none and no dimension style using px
return parseint(this.el_['offset' + totitlecase$1(widthorheight)], 10);
}
/**
* get the computed width or the height of the component's element.
*
* uses `window.getcomputedstyle`.
*
* @param {string} widthorheight
* a string containing 'width' or 'height'. whichever one you want to get.
*
* @return {number}
* the dimension that gets asked for or 0 if nothing was set
* for that dimension.
*/
;
_proto.currentdimension = function currentdimension(widthorheight) {
var computedwidthorheight = 0;
if (widthorheight !== 'width' && widthorheight !== 'height') {
throw new error('currentdimension only accepts width or height value');
}
computedwidthorheight = computedstyle(this.el_, widthorheight); // remove 'px' from variable and parse as integer
computedwidthorheight = parsefloat(computedwidthorheight); // if the computed value is still 0, it's possible that the browser is lying
// and we want to check the offset values.
// this code also runs wherever getcomputedstyle doesn't exist.
if (computedwidthorheight === 0 || isnan(computedwidthorheight)) {
var rule = "offset" + totitlecase$1(widthorheight);
computedwidthorheight = this.el_[rule];
}
return computedwidthorheight;
}
/**
* an object that contains width and height values of the `component`s
* computed style. uses `window.getcomputedstyle`.
*
* @typedef {object} component~dimensionobject
*
* @property {number} width
* the width of the `component`s computed style.
*
* @property {number} height
* the height of the `component`s computed style.
*/
/**
* get an object that contains computed width and height values of the
* component's element.
*
* uses `window.getcomputedstyle`.
*
* @return {component~dimensionobject}
* the computed dimensions of the component's element.
*/
;
_proto.currentdimensions = function currentdimensions() {
return {
width: this.currentdimension('width'),
height: this.currentdimension('height')
};
}
/**
* get the computed width of the component's element.
*
* uses `window.getcomputedstyle`.
*
* @return {number}
* the computed width of the component's element.
*/
;
_proto.currentwidth = function currentwidth() {
return this.currentdimension('width');
}
/**
* get the computed height of the component's element.
*
* uses `window.getcomputedstyle`.
*
* @return {number}
* the computed height of the component's element.
*/
;
_proto.currentheight = function currentheight() {
return this.currentdimension('height');
}
/**
* set the focus to this component
*/
;
_proto.focus = function focus() {
this.el_.focus();
}
/**
* remove the focus from this component
*/
;
_proto.blur = function blur() {
this.el_.blur();
}
/**
* when this component receives a `keydown` event which it does not process,
* it passes the event to the player for handling.
*
* @param {eventtarget~event} event
* the `keydown` event that caused this function to be called.
*/
;
_proto.handlekeydown = function handlekeydown(event) {
if (this.player_) {
// we only stop propagation here because we want unhandled events to fall
// back to the browser. exclude tab for focus trapping.
if (!keycode__webpack_imported_module_3___default.a.iseventkey(event, 'tab')) {
event.stoppropagation();
}
this.player_.handlekeydown(event);
}
}
/**
* many components used to have a `handlekeypress` method, which was poorly
* named because it listened to a `keydown` event. this method name now
* delegates to `handlekeydown`. this means anyone calling `handlekeypress`
* will not see their method calls stop working.
*
* @param {eventtarget~event} event
* the event that caused this function to be called.
*/
;
_proto.handlekeypress = function handlekeypress(event) {
this.handlekeydown(event);
}
/**
* emit a 'tap' events when touch event support gets detected. this gets used to
* support toggling the controls through a tap on the video. they get enabled
* because every sub-component would have extra overhead otherwise.
*
* @private
* @fires component#tap
* @listens component#touchstart
* @listens component#touchmove
* @listens component#touchleave
* @listens component#touchcancel
* @listens component#touchend
*/
;
_proto.emittapevents = function emittapevents() {
// track the start time so we can determine how long the touch lasted
var touchstart = 0;
var firsttouch = null; // maximum movement allowed during a touch event to still be considered a tap
// other popular libs use anywhere from 2 (hammer.js) to 15,
// so 10 seems like a nice, round number.
var tapmovementthreshold = 10; // the maximum length a touch can be while still being considered a tap
var touchtimethreshold = 200;
var couldbetap;
this.on('touchstart', function (event) {
// if more than one finger, don't consider treating this as a click
if (event.touches.length === 1) {
// copy pagex/pagey from the object
firsttouch = {
pagex: event.touches[0].pagex,
pagey: event.touches[0].pagey
}; // record start time so we can detect a tap vs. "touch and hold"
touchstart = global_window__webpack_imported_module_0___default.a.performance.now(); // reset couldbetap tracking
couldbetap = true;
}
});
this.on('touchmove', function (event) {
// if more than one finger, don't consider treating this as a click
if (event.touches.length > 1) {
couldbetap = false;
} else if (firsttouch) {
// some devices will throw touchmoves for all but the slightest of taps.
// so, if we moved only a small distance, this could still be a tap
var xdiff = event.touches[0].pagex - firsttouch.pagex;
var ydiff = event.touches[0].pagey - firsttouch.pagey;
var touchdistance = math.sqrt(xdiff * xdiff + ydiff * ydiff);
if (touchdistance > tapmovementthreshold) {
couldbetap = false;
}
}
});
var notap = function notap() {
couldbetap = false;
}; // todo: listen to the original target. http://youtu.be/dujfpxokup8?t=13m8s
this.on('touchleave', notap);
this.on('touchcancel', notap); // when the touch ends, measure how long it took and trigger the appropriate
// event
this.on('touchend', function (event) {
firsttouch = null; // proceed only if the touchmove/leave/cancel event didn't happen
if (couldbetap === true) {
// measure how long the touch lasted
var touchtime = global_window__webpack_imported_module_0___default.a.performance.now() - touchstart; // make sure the touch was less than the threshold to be considered a tap
if (touchtime < touchtimethreshold) {
// don't let browser turn this into a click
event.preventdefault();
/**
* triggered when a `component` is tapped.
*
* @event component#tap
* @type {eventtarget~event}
*/
this.trigger('tap'); // it may be good to copy the touchend event object and change the
// type to tap, if the other event properties aren't exact after
// events.fixevent runs (e.g. event.target)
}
}
});
}
/**
* this function reports user activity whenever touch events happen. this can get
* turned off by any sub-components that wants touch events to act another way.
*
* report user touch activity when touch events occur. user activity gets used to
* determine when controls should show/hide. it is simple when it comes to mouse
* events, because any mouse event should show the controls. so we capture mouse
* events that bubble up to the player and report activity when that happens.
* with touch events it isn't as easy as `touchstart` and `touchend` toggle player
* controls. so touch events can't help us at the player level either.
*
* user activity gets checked asynchronously. so what could happen is a tap event
* on the video turns the controls off. then the `touchend` event bubbles up to
* the player. which, if it reported user activity, would turn the controls right
* back on. we also don't want to completely block touch events from bubbling up.
* furthermore a `touchmove` event and anything other than a tap, should not turn
* controls back on.
*
* @listens component#touchstart
* @listens component#touchmove
* @listens component#touchend
* @listens component#touchcancel
*/
;
_proto.enabletouchactivity = function enabletouchactivity() {
// don't continue if the root player doesn't support reporting user activity
if (!this.player() || !this.player().reportuseractivity) {
return;
} // listener for reporting that the user is active
var report = bind(this.player(), this.player().reportuseractivity);
var touchholding;
this.on('touchstart', function () {
report(); // for as long as the they are touching the device or have their mouse down,
// we consider them active even if they're not moving their finger or mouse.
// so we want to continue to update that they are active
this.clearinterval(touchholding); // report at the same interval as activitycheck
touchholding = this.setinterval(report, 250);
});
var touchend = function touchend(event) {
report(); // stop the interval that maintains activity if the touch is holding
this.clearinterval(touchholding);
};
this.on('touchmove', report);
this.on('touchend', touchend);
this.on('touchcancel', touchend);
}
/**
* a callback that has no parameters and is bound into `component`s context.
*
* @callback component~genericcallback
* @this component
*/
/**
* creates a function that runs after an `x` millisecond timeout. this function is a
* wrapper around `window.settimeout`. there are a few reasons to use this one
* instead though:
* 1. it gets cleared via {@link component#cleartimeout} when
* {@link component#dispose} gets called.
* 2. the function callback will gets turned into a {@link component~genericcallback}
*
* > note: you can't use `window.cleartimeout` on the id returned by this function. this
* will cause its dispose listener not to get cleaned up! please use
* {@link component#cleartimeout} or {@link component#dispose} instead.
*
* @param {component~genericcallback} fn
* the function that will be run after `timeout`.
*
* @param {number} timeout
* timeout in milliseconds to delay before executing the specified function.
*
* @return {number}
* returns a timeout id that gets used to identify the timeout. it can also
* get used in {@link component#cleartimeout} to clear the timeout that
* was set.
*
* @listens component#dispose
* @see [similar to]{@link https://developer.mozilla.org/en-us/docs/web/api/windowtimers/settimeout}
*/
;
_proto.settimeout = function settimeout(fn, timeout) {
var _this3 = this;
// declare as variables so they are properly available in timeout function
// eslint-disable-next-line
var timeoutid;
fn = bind(this, fn);
this.cleartimersondispose_();
timeoutid = global_window__webpack_imported_module_0___default.a.settimeout(function () {
if (_this3.settimeoutids_.has(timeoutid)) {
_this3.settimeoutids_["delete"](timeoutid);
}
fn();
}, timeout);
this.settimeoutids_.add(timeoutid);
return timeoutid;
}
/**
* clears a timeout that gets created via `window.settimeout` or
* {@link component#settimeout}. if you set a timeout via {@link component#settimeout}
* use this function instead of `window.cleartimout`. if you don't your dispose
* listener will not get cleaned up until {@link component#dispose}!
*
* @param {number} timeoutid
* the id of the timeout to clear. the return value of
* {@link component#settimeout} or `window.settimeout`.
*
* @return {number}
* returns the timeout id that was cleared.
*
* @see [similar to]{@link https://developer.mozilla.org/en-us/docs/web/api/windowtimers/cleartimeout}
*/
;
_proto.cleartimeout = function cleartimeout(timeoutid) {
if (this.settimeoutids_.has(timeoutid)) {
this.settimeoutids_["delete"](timeoutid);
global_window__webpack_imported_module_0___default.a.cleartimeout(timeoutid);
}
return timeoutid;
}
/**
* creates a function that gets run every `x` milliseconds. this function is a wrapper
* around `window.setinterval`. there are a few reasons to use this one instead though.
* 1. it gets cleared via {@link component#clearinterval} when
* {@link component#dispose} gets called.
* 2. the function callback will be a {@link component~genericcallback}
*
* @param {component~genericcallback} fn
* the function to run every `x` seconds.
*
* @param {number} interval
* execute the specified function every `x` milliseconds.
*
* @return {number}
* returns an id that can be used to identify the interval. it can also be be used in
* {@link component#clearinterval} to clear the interval.
*
* @listens component#dispose
* @see [similar to]{@link https://developer.mozilla.org/en-us/docs/web/api/windowtimers/setinterval}
*/
;
_proto.setinterval = function setinterval(fn, interval) {
fn = bind(this, fn);
this.cleartimersondispose_();
var intervalid = global_window__webpack_imported_module_0___default.a.setinterval(fn, interval);
this.setintervalids_.add(intervalid);
return intervalid;
}
/**
* clears an interval that gets created via `window.setinterval` or
* {@link component#setinterval}. if you set an inteval via {@link component#setinterval}
* use this function instead of `window.clearinterval`. if you don't your dispose
* listener will not get cleaned up until {@link component#dispose}!
*
* @param {number} intervalid
* the id of the interval to clear. the return value of
* {@link component#setinterval} or `window.setinterval`.
*
* @return {number}
* returns the interval id that was cleared.
*
* @see [similar to]{@link https://developer.mozilla.org/en-us/docs/web/api/windowtimers/clearinterval}
*/
;
_proto.clearinterval = function clearinterval(intervalid) {
if (this.setintervalids_.has(intervalid)) {
this.setintervalids_["delete"](intervalid);
global_window__webpack_imported_module_0___default.a.clearinterval(intervalid);
}
return intervalid;
}
/**
* queues up a callback to be passed to requestanimationframe (raf), but
* with a few extra bonuses:
*
* - supports browsers that do not support raf by falling back to
* {@link component#settimeout}.
*
* - the callback is turned into a {@link component~genericcallback} (i.e.
* bound to the component).
*
* - automatic cancellation of the raf callback is handled if the component
* is disposed before it is called.
*
* @param {component~genericcallback} fn
* a function that will be bound to this component and executed just
* before the browser's next repaint.
*
* @return {number}
* returns an raf id that gets used to identify the timeout. it can
* also be used in {@link component#cancelanimationframe} to cancel
* the animation frame callback.
*
* @listens component#dispose
* @see [similar to]{@link https://developer.mozilla.org/en-us/docs/web/api/window/requestanimationframe}
*/
;
_proto.requestanimationframe = function requestanimationframe(fn) {
var _this4 = this;
// fall back to using a timer.
if (!this.supportsraf_) {
return this.settimeout(fn, 1000 / 60);
}
this.cleartimersondispose_(); // declare as variables so they are properly available in raf function
// eslint-disable-next-line
var id;
fn = bind(this, fn);
id = global_window__webpack_imported_module_0___default.a.requestanimationframe(function () {
if (_this4.rafids_.has(id)) {
_this4.rafids_["delete"](id);
}
fn();
});
this.rafids_.add(id);
return id;
}
/**
* request an animation frame, but only one named animation
* frame will be queued. another will never be added until
* the previous one finishes.
*
* @param {string} name
* the name to give this requestanimationframe
*
* @param {component~genericcallback} fn
* a function that will be bound to this component and executed just
* before the browser's next repaint.
*/
;
_proto.requestnamedanimationframe = function requestnamedanimationframe(name, fn) {
var _this5 = this;
if (this.namedrafs_.has(name)) {
return;
}
this.cleartimersondispose_();
fn = bind(this, fn);
var id = this.requestanimationframe(function () {
fn();
if (_this5.namedrafs_.has(name)) {
_this5.namedrafs_["delete"](name);
}
});
this.namedrafs_.set(name, id);
return name;
}
/**
* cancels a current named animation frame if it exists.
*
* @param {string} name
* the name of the requestanimationframe to cancel.
*/
;
_proto.cancelnamedanimationframe = function cancelnamedanimationframe(name) {
if (!this.namedrafs_.has(name)) {
return;
}
this.cancelanimationframe(this.namedrafs_.get(name));
this.namedrafs_["delete"](name);
}
/**
* cancels a queued callback passed to {@link component#requestanimationframe}
* (raf).
*
* if you queue an raf callback via {@link component#requestanimationframe},
* use this function instead of `window.cancelanimationframe`. if you don't,
* your dispose listener will not get cleaned up until {@link component#dispose}!
*
* @param {number} id
* the raf id to clear. the return value of {@link component#requestanimationframe}.
*
* @return {number}
* returns the raf id that was cleared.
*
* @see [similar to]{@link https://developer.mozilla.org/en-us/docs/web/api/window/cancelanimationframe}
*/
;
_proto.cancelanimationframe = function cancelanimationframe(id) {
// fall back to using a timer.
if (!this.supportsraf_) {
return this.cleartimeout(id);
}
if (this.rafids_.has(id)) {
this.rafids_["delete"](id);
global_window__webpack_imported_module_0___default.a.cancelanimationframe(id);
}
return id;
}
/**
* a function to setup `requestanimationframe`, `settimeout`,
* and `setinterval`, clearing on dispose.
*
* > previously each timer added and removed dispose listeners on it's own.
* for better performance it was decided to batch them all, and use `set`s
* to track outstanding timer ids.
*
* @private
*/
;
_proto.cleartimersondispose_ = function cleartimersondispose_() {
var _this6 = this;
if (this.clearingtimersondispose_) {
return;
}
this.clearingtimersondispose_ = true;
this.one('dispose', function () {
[['namedrafs_', 'cancelnamedanimationframe'], ['rafids_', 'cancelanimationframe'], ['settimeoutids_', 'cleartimeout'], ['setintervalids_', 'clearinterval']].foreach(function (_ref) {
var idname = _ref[0],
cancelname = _ref[1];
// for a `set` key will actually be the value again
// so foreach((val, val) =>` but for maps we want to use
// the key.
_this6[idname].foreach(function (val, key) {
return _this6[cancelname](key);
});
});
_this6.clearingtimersondispose_ = false;
});
}
/**
* register a `component` with `videojs` given the name and the component.
*
* > note: {@link tech}s should not be registered as a `component`. {@link tech}s
* should be registered using {@link tech.registertech} or
* {@link videojs:videojs.registertech}.
*
* > note: this function can also be seen on videojs as
* {@link videojs:videojs.registercomponent}.
*
* @param {string} name
* the name of the `component` to register.
*
* @param {component} componenttoregister
* the `component` class to register.
*
* @return {component}
* the `component` that was registered.
*/
;
component.registercomponent = function registercomponent(name, componenttoregister) {
if (typeof name !== 'string' || !name) {
throw new error("illegal component name, \"" + name + "\"; must be a non-empty string.");
}
var tech = component.getcomponent('tech'); // we need to make sure this check is only done if tech has been registered.
var istech = tech && tech.istech(componenttoregister);
var iscomp = component === componenttoregister || component.prototype.isprototypeof(componenttoregister.prototype);
if (istech || !iscomp) {
var reason;
if (istech) {
reason = 'techs must be registered using tech.registertech()';
} else {
reason = 'must be a component subclass';
}
throw new error("illegal component, \"" + name + "\"; " + reason + ".");
}
name = totitlecase$1(name);
if (!component.components_) {
component.components_ = {};
}
var player = component.getcomponent('player');
if (name === 'player' && player && player.players) {
var players = player.players;
var playernames = object.keys(players); // if we have players that were disposed, then their name will still be
// in players.players. so, we must loop through and verify that the value
// for each item is not null. this allows registration of the player component
// after all players have been disposed or before any were created.
if (players && playernames.length > 0 && playernames.map(function (pname) {
return players[pname];
}).every(boolean)) {
throw new error('can not register player component after player has been created.');
}
}
component.components_[name] = componenttoregister;
component.components_[tolowercase(name)] = componenttoregister;
return componenttoregister;
}
/**
* get a `component` based on the name it was registered with.
*
* @param {string} name
* the name of the component to get.
*
* @return {component}
* the `component` that got registered under the given name.
*/
;
component.getcomponent = function getcomponent(name) {
if (!name || !component.components_) {
return;
}
return component.components_[name];
};
return component;
}();
/**
* whether or not this component supports `requestanimationframe`.
*
* this is exposed primarily for testing purposes.
*
* @private
* @type {boolean}
*/
component$1.prototype.supportsraf_ = typeof global_window__webpack_imported_module_0___default.a.requestanimationframe === 'function' && typeof global_window__webpack_imported_module_0___default.a.cancelanimationframe === 'function';
component$1.registercomponent('component', component$1);
/**
* @file time-ranges.js
* @module time-ranges
*/
/**
* returns the time for the specified index at the start or end
* of a timerange object.
*
* @typedef {function} timerangeindex
*
* @param {number} [index=0]
* the range number to return the time for.
*
* @return {number}
* the time offset at the specified index.
*
* @deprecated the index argument must be provided.
* in the future, leaving it out will throw an error.
*/
/**
* an object that contains ranges of time.
*
* @typedef {object} timerange
*
* @property {number} length
* the number of time ranges represented by this object.
*
* @property {module:time-ranges~timerangeindex} start
* returns the time offset at which a specified time range begins.
*
* @property {module:time-ranges~timerangeindex} end
* returns the time offset at which a specified time range ends.
*
* @see https://developer.mozilla.org/en-us/docs/web/api/timeranges
*/
/**
* check if any of the time ranges are over the maximum index.
*
* @private
* @param {string} fnname
* the function name to use for logging
*
* @param {number} index
* the index to check
*
* @param {number} maxindex
* the maximum possible index
*
* @throws {error} if the timeranges provided are over the maxindex
*/
function rangecheck(fnname, index, maxindex) {
if (typeof index !== 'number' || index < 0 || index > maxindex) {
throw new error("failed to execute '" + fnname + "' on 'timeranges': the index provided (" + index + ") is non-numeric or out of bounds (0-" + maxindex + ").");
}
}
/**
* get the time for the specified index at the start or end
* of a timerange object.
*
* @private
* @param {string} fnname
* the function name to use for logging
*
* @param {string} valueindex
* the property that should be used to get the time. should be
* 'start' or 'end'
*
* @param {array} ranges
* an array of time ranges
*
* @param {array} [rangeindex=0]
* the index to start the search at
*
* @return {number}
* the time that offset at the specified index.
*
* @deprecated rangeindex must be set to a value, in the future this will throw an error.
* @throws {error} if rangeindex is more than the length of ranges
*/
function getrange(fnname, valueindex, ranges, rangeindex) {
rangecheck(fnname, rangeindex, ranges.length - 1);
return ranges[rangeindex][valueindex];
}
/**
* create a time range object given ranges of time.
*
* @private
* @param {array} [ranges]
* an array of time ranges.
*/
function createtimerangesobj(ranges) {
var timerangesobj;
if (ranges === undefined || ranges.length === 0) {
timerangesobj = {
length: 0,
start: function start() {
throw new error('this timeranges object is empty');
},
end: function end() {
throw new error('this timeranges object is empty');
}
};
} else {
timerangesobj = {
length: ranges.length,
start: getrange.bind(null, 'start', 0, ranges),
end: getrange.bind(null, 'end', 1, ranges)
};
}
if (global_window__webpack_imported_module_0___default.a.symbol && global_window__webpack_imported_module_0___default.a.symbol.iterator) {
timerangesobj[global_window__webpack_imported_module_0___default.a.symbol.iterator] = function () {
return (ranges || []).values();
};
}
return timerangesobj;
}
/**
* create a `timerange` object which mimics an
* {@link https://developer.mozilla.org/en-us/docs/web/api/timeranges|html5 timeranges instance}.
*
* @param {number|array[]} start
* the start of a single range (a number) or an array of ranges (an
* array of arrays of two numbers each).
*
* @param {number} end
* the end of a single range. cannot be used with the array form of
* the `start` argument.
*/
function createtimeranges(start, end) {
if (array.isarray(start)) {
return createtimerangesobj(start);
} else if (start === undefined || end === undefined) {
return createtimerangesobj();
}
return createtimerangesobj([[start, end]]);
}
/**
* @file buffer.js
* @module buffer
*/
/**
* compute the percentage of the media that has been buffered.
*
* @param {timerange} buffered
* the current `timerange` object representing buffered time ranges
*
* @param {number} duration
* total duration of the media
*
* @return {number}
* percent buffered of the total duration in decimal form.
*/
function bufferedpercent(buffered, duration) {
var bufferedduration = 0;
var start;
var end;
if (!duration) {
return 0;
}
if (!buffered || !buffered.length) {
buffered = createtimeranges(0, 0);
}
for (var i = 0; i < buffered.length; i++) {
start = buffered.start(i);
end = buffered.end(i); // buffered end can be bigger than duration by a very small fraction
if (end > duration) {
end = duration;
}
bufferedduration += end - start;
}
return bufferedduration / duration;
}
/**
* @file media-error.js
*/
/**
* a custom `mediaerror` class which mimics the standard html5 `mediaerror` class.
*
* @param {number|string|object|mediaerror} value
* this can be of multiple types:
* - number: should be a standard error code
* - string: an error message (the code will be 0)
* - object: arbitrary properties
* - `mediaerror` (native): used to populate a video.js `mediaerror` object
* - `mediaerror` (video.js): will return itself if it's already a
* video.js `mediaerror` object.
*
* @see [mediaerror spec]{@link https://dev.w3.org/html5/spec-author-view/video.html#mediaerror}
* @see [encrypted mediaerror spec]{@link https://www.w3.org/tr/2013/wd-encrypted-media-20130510/#error-codes}
*
* @class mediaerror
*/
function mediaerror(value) {
// allow redundant calls to this constructor to avoid having `instanceof`
// checks peppered around the code.
if (value instanceof mediaerror) {
return value;
}
if (typeof value === 'number') {
this.code = value;
} else if (typeof value === 'string') {
// default code is zero, so this is a custom error
this.message = value;
} else if (isobject(value)) {
// we assign the `code` property manually because native `mediaerror` objects
// do not expose it as an own/enumerable property of the object.
if (typeof value.code === 'number') {
this.code = value.code;
}
assign(this, value);
}
if (!this.message) {
this.message = mediaerror.defaultmessages[this.code] || '';
}
}
/**
* the error code that refers two one of the defined `mediaerror` types
*
* @type {number}
*/
mediaerror.prototype.code = 0;
/**
* an optional message that to show with the error. message is not part of the html5
* video spec but allows for more informative custom errors.
*
* @type {string}
*/
mediaerror.prototype.message = '';
/**
* an optional status code that can be set by plugins to allow even more detail about
* the error. for example a plugin might provide a specific http status code and an
* error message for that code. then when the plugin gets that error this class will
* know how to display an error message for it. this allows a custom message to show
* up on the `player` error overlay.
*
* @type {array}
*/
mediaerror.prototype.status = null;
/**
* errors indexed by the w3c standard. the order **cannot change**! see the
* specification listed under {@link mediaerror} for more information.
*
* @enum {array}
* @readonly
* @property {string} 0 - media_err_custom
* @property {string} 1 - media_err_aborted
* @property {string} 2 - media_err_network
* @property {string} 3 - media_err_decode
* @property {string} 4 - media_err_src_not_supported
* @property {string} 5 - media_err_encrypted
*/
mediaerror.errortypes = ['media_err_custom', 'media_err_aborted', 'media_err_network', 'media_err_decode', 'media_err_src_not_supported', 'media_err_encrypted'];
/**
* the default `mediaerror` messages based on the {@link mediaerror.errortypes}.
*
* @type {array}
* @constant
*/
mediaerror.defaultmessages = {
1: 'you aborted the media playback',
2: 'a network error caused the media download to fail part-way.',
3: 'the media playback was aborted due to a corruption problem or because the media used features your browser did not support.',
4: 'the media could not be loaded, either because the server or network failed or because the format is not supported.',
5: 'the media is encrypted and we do not have the keys to decrypt it.'
}; // add types as properties on mediaerror
// e.g. mediaerror.media_err_src_not_supported = 4;
for (var errnum = 0; errnum < mediaerror.errortypes.length; errnum++) {
mediaerror[mediaerror.errortypes[errnum]] = errnum; // values should be accessible on both the class and instance
mediaerror.prototype[mediaerror.errortypes[errnum]] = errnum;
} // jsdocs for instance/static members added above
/**
* returns whether an object is `promise`-like (i.e. has a `then` method).
*
* @param {object} value
* an object that may or may not be `promise`-like.
*
* @return {boolean}
* whether or not the object is `promise`-like.
*/
function ispromise(value) {
return value !== undefined && value !== null && typeof value.then === 'function';
}
/**
* silence a promise-like object.
*
* this is useful for avoiding non-harmful, but potentially confusing "uncaught
* play promise" rejection error messages.
*
* @param {object} value
* an object that may or may not be `promise`-like.
*/
function silencepromise(value) {
if (ispromise(value)) {
value.then(null, function (e) {});
}
}
/**
* @file text-track-list-converter.js utilities for capturing text track state and
* re-creating tracks based on a capture.
*
* @module text-track-list-converter
*/
/**
* examine a single {@link texttrack} and return a json-compatible javascript object that
* represents the {@link texttrack}'s state.
*
* @param {texttrack} track
* the text track to query.
*
* @return {object}
* a serializable javascript representation of the texttrack.
* @private
*/
var tracktojson_ = function tracktojson_(track) {
var ret = ['kind', 'label', 'language', 'id', 'inbandmetadatatrackdispatchtype', 'mode', 'src'].reduce(function (acc, prop, i) {
if (track[prop]) {
acc[prop] = track[prop];
}
return acc;
}, {
cues: track.cues && array.prototype.map.call(track.cues, function (cue) {
return {
starttime: cue.starttime,
endtime: cue.endtime,
text: cue.text,
id: cue.id
};
})
});
return ret;
};
/**
* examine a {@link tech} and return a json-compatible javascript array that represents the
* state of all {@link texttrack}s currently configured. the return array is compatible with
* {@link text-track-list-converter:jsontotexttracks}.
*
* @param {tech} tech
* the tech object to query
*
* @return {array}
* a serializable javascript representation of the {@link tech}s
* {@link texttracklist}.
*/
var texttrackstojson = function texttrackstojson(tech) {
var trackels = tech.$$('track');
var trackobjs = array.prototype.map.call(trackels, function (t) {
return t.track;
});
var tracks = array.prototype.map.call(trackels, function (trackel) {
var json = tracktojson_(trackel.track);
if (trackel.src) {
json.src = trackel.src;
}
return json;
});
return tracks.concat(array.prototype.filter.call(tech.texttracks(), function (track) {
return trackobjs.indexof(track) === -1;
}).map(tracktojson_));
};
/**
* create a set of remote {@link texttrack}s on a {@link tech} based on an array of javascript
* object {@link texttrack} representations.
*
* @param {array} json
* an array of `texttrack` representation objects, like those that would be
* produced by `texttrackstojson`.
*
* @param {tech} tech
* the `tech` to create the `texttrack`s on.
*/
var jsontotexttracks = function jsontotexttracks(json, tech) {
json.foreach(function (track) {
var addedtrack = tech.addremotetexttrack(track).track;
if (!track.src && track.cues) {
track.cues.foreach(function (cue) {
return addedtrack.addcue(cue);
});
}
});
return tech.texttracks();
};
var texttrackconverter = {
texttrackstojson: texttrackstojson,
jsontotexttracks: jsontotexttracks,
tracktojson_: tracktojson_
};
var modal_class_name = 'vjs-modal-dialog';
/**
* the `modaldialog` displays over the video and its controls, which blocks
* interaction with the player until it is closed.
*
* modal dialogs include a "close" button and will close when that button
* is activated - or when esc is pressed anywhere.
*
* @extends component
*/
var modaldialog = /*#__pure__*/function (_component) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(modaldialog, _component);
/**
* create an instance of this class.
*
* @param {player} player
* the `player` that this class should be attached to.
*
* @param {object} [options]
* the key/value store of player options.
*
* @param {mixed} [options.content=undefined]
* provide customized content for this modal.
*
* @param {string} [options.description]
* a text description for the modal, primarily for accessibility.
*
* @param {boolean} [options.fillalways=false]
* normally, modals are automatically filled only the first time
* they open. this tells the modal to refresh its content
* every time it opens.
*
* @param {string} [options.label]
* a text label for the modal, primarily for accessibility.
*
* @param {boolean} [options.pauseonopen=true]
* if `true`, playback will will be paused if playing when
* the modal opens, and resumed when it closes.
*
* @param {boolean} [options.temporary=true]
* if `true`, the modal can only be opened once; it will be
* disposed as soon as it's closed.
*
* @param {boolean} [options.uncloseable=false]
* if `true`, the user will not be able to close the modal
* through the ui in the normal ways. programmatic closing is
* still possible.
*/
function modaldialog(player, options) {
var _this;
_this = _component.call(this, player, options) || this;
_this.handlekeydown_ = function (e) {
return _this.handlekeydown(e);
};
_this.close_ = function (e) {
return _this.close(e);
};
_this.opened_ = _this.hasbeenopened_ = _this.hasbeenfilled_ = false;
_this.closeable(!_this.options_.uncloseable);
_this.content(_this.options_.content); // make sure the contentel is defined after any children are initialized
// because we only want the contents of the modal in the contentel
// (not the ui elements like the close button).
_this.contentel_ = createel('div', {
classname: modal_class_name + "-content"
}, {
role: 'document'
});
_this.descel_ = createel('p', {
classname: modal_class_name + "-description vjs-control-text",
id: _this.el().getattribute('aria-describedby')
});
textcontent(_this.descel_, _this.description());
_this.el_.appendchild(_this.descel_);
_this.el_.appendchild(_this.contentel_);
return _this;
}
/**
* create the `modaldialog`'s dom element
*
* @return {element}
* the dom element that gets created.
*/
var _proto = modaldialog.prototype;
_proto.createel = function createel() {
return _component.prototype.createel.call(this, 'div', {
classname: this.buildcssclass(),
tabindex: -1
}, {
'aria-describedby': this.id() + "_description",
'aria-hidden': 'true',
'aria-label': this.label(),
'role': 'dialog'
});
};
_proto.dispose = function dispose() {
this.contentel_ = null;
this.descel_ = null;
this.previouslyactiveel_ = null;
_component.prototype.dispose.call(this);
}
/**
* builds the default dom `classname`.
*
* @return {string}
* the dom `classname` for this object.
*/
;
_proto.buildcssclass = function buildcssclass() {
return modal_class_name + " vjs-hidden " + _component.prototype.buildcssclass.call(this);
}
/**
* returns the label string for this modal. primarily used for accessibility.
*
* @return {string}
* the localized or raw label of this modal.
*/
;
_proto.label = function label() {
return this.localize(this.options_.label || 'modal window');
}
/**
* returns the description string for this modal. primarily used for
* accessibility.
*
* @return {string}
* the localized or raw description of this modal.
*/
;
_proto.description = function description() {
var desc = this.options_.description || this.localize('this is a modal window.'); // append a universal closeability message if the modal is closeable.
if (this.closeable()) {
desc += ' ' + this.localize('this modal can be closed by pressing the escape key or activating the close button.');
}
return desc;
}
/**
* opens the modal.
*
* @fires modaldialog#beforemodalopen
* @fires modaldialog#modalopen
*/
;
_proto.open = function open() {
if (!this.opened_) {
var player = this.player();
/**
* fired just before a `modaldialog` is opened.
*
* @event modaldialog#beforemodalopen
* @type {eventtarget~event}
*/
this.trigger('beforemodalopen');
this.opened_ = true; // fill content if the modal has never opened before and
// never been filled.
if (this.options_.fillalways || !this.hasbeenopened_ && !this.hasbeenfilled_) {
this.fill();
} // if the player was playing, pause it and take note of its previously
// playing state.
this.wasplaying_ = !player.paused();
if (this.options_.pauseonopen && this.wasplaying_) {
player.pause();
}
this.on('keydown', this.handlekeydown_); // hide controls and note if they were enabled.
this.hadcontrols_ = player.controls();
player.controls(false);
this.show();
this.conditionalfocus_();
this.el().setattribute('aria-hidden', 'false');
/**
* fired just after a `modaldialog` is opened.
*
* @event modaldialog#modalopen
* @type {eventtarget~event}
*/
this.trigger('modalopen');
this.hasbeenopened_ = true;
}
}
/**
* if the `modaldialog` is currently open or closed.
*
* @param {boolean} [value]
* if given, it will open (`true`) or close (`false`) the modal.
*
* @return {boolean}
* the current open state of the modaldialog
*/
;
_proto.opened = function opened(value) {
if (typeof value === 'boolean') {
this[value ? 'open' : 'close']();
}
return this.opened_;
}
/**
* closes the modal, does nothing if the `modaldialog` is
* not open.
*
* @fires modaldialog#beforemodalclose
* @fires modaldialog#modalclose
*/
;
_proto.close = function close() {
if (!this.opened_) {
return;
}
var player = this.player();
/**
* fired just before a `modaldialog` is closed.
*
* @event modaldialog#beforemodalclose
* @type {eventtarget~event}
*/
this.trigger('beforemodalclose');
this.opened_ = false;
if (this.wasplaying_ && this.options_.pauseonopen) {
player.play();
}
this.off('keydown', this.handlekeydown_);
if (this.hadcontrols_) {
player.controls(true);
}
this.hide();
this.el().setattribute('aria-hidden', 'true');
/**
* fired just after a `modaldialog` is closed.
*
* @event modaldialog#modalclose
* @type {eventtarget~event}
*/
this.trigger('modalclose');
this.conditionalblur_();
if (this.options_.temporary) {
this.dispose();
}
}
/**
* check to see if the `modaldialog` is closeable via the ui.
*
* @param {boolean} [value]
* if given as a boolean, it will set the `closeable` option.
*
* @return {boolean}
* returns the final value of the closable option.
*/
;
_proto.closeable = function closeable(value) {
if (typeof value === 'boolean') {
var closeable = this.closeable_ = !!value;
var close = this.getchild('closebutton'); // if this is being made closeable and has no close button, add one.
if (closeable && !close) {
// the close button should be a child of the modal - not its
// content element, so temporarily change the content element.
var temp = this.contentel_;
this.contentel_ = this.el_;
close = this.addchild('closebutton', {
controltext: 'close modal dialog'
});
this.contentel_ = temp;
this.on(close, 'close', this.close_);
} // if this is being made uncloseable and has a close button, remove it.
if (!closeable && close) {
this.off(close, 'close', this.close_);
this.removechild(close);
close.dispose();
}
}
return this.closeable_;
}
/**
* fill the modal's content element with the modal's "content" option.
* the content element will be emptied before this change takes place.
*/
;
_proto.fill = function fill() {
this.fillwith(this.content());
}
/**
* fill the modal's content element with arbitrary content.
* the content element will be emptied before this change takes place.
*
* @fires modaldialog#beforemodalfill
* @fires modaldialog#modalfill
*
* @param {mixed} [content]
* the same rules apply to this as apply to the `content` option.
*/
;
_proto.fillwith = function fillwith(content) {
var contentel = this.contentel();
var parentel = contentel.parentnode;
var nextsiblingel = contentel.nextsibling;
/**
* fired just before a `modaldialog` is filled with content.
*
* @event modaldialog#beforemodalfill
* @type {eventtarget~event}
*/
this.trigger('beforemodalfill');
this.hasbeenfilled_ = true; // detach the content element from the dom before performing
// manipulation to avoid modifying the live dom multiple times.
parentel.removechild(contentel);
this.empty();
insertcontent(contentel, content);
/**
* fired just after a `modaldialog` is filled with content.
*
* @event modaldialog#modalfill
* @type {eventtarget~event}
*/
this.trigger('modalfill'); // re-inject the re-filled content element.
if (nextsiblingel) {
parentel.insertbefore(contentel, nextsiblingel);
} else {
parentel.appendchild(contentel);
} // make sure that the close button is last in the dialog dom
var closebutton = this.getchild('closebutton');
if (closebutton) {
parentel.appendchild(closebutton.el_);
}
}
/**
* empties the content element. this happens anytime the modal is filled.
*
* @fires modaldialog#beforemodalempty
* @fires modaldialog#modalempty
*/
;
_proto.empty = function empty() {
/**
* fired just before a `modaldialog` is emptied.
*
* @event modaldialog#beforemodalempty
* @type {eventtarget~event}
*/
this.trigger('beforemodalempty');
emptyel(this.contentel());
/**
* fired just after a `modaldialog` is emptied.
*
* @event modaldialog#modalempty
* @type {eventtarget~event}
*/
this.trigger('modalempty');
}
/**
* gets or sets the modal content, which gets normalized before being
* rendered into the dom.
*
* this does not update the dom or fill the modal, but it is called during
* that process.
*
* @param {mixed} [value]
* if defined, sets the internal content value to be used on the
* next call(s) to `fill`. this value is normalized before being
* inserted. to "clear" the internal content value, pass `null`.
*
* @return {mixed}
* the current content of the modal dialog
*/
;
_proto.content = function content(value) {
if (typeof value !== 'undefined') {
this.content_ = value;
}
return this.content_;
}
/**
* conditionally focus the modal dialog if focus was previously on the player.
*
* @private
*/
;
_proto.conditionalfocus_ = function conditionalfocus_() {
var activeel = global_document__webpack_imported_module_1___default.a.activeelement;
var playerel = this.player_.el_;
this.previouslyactiveel_ = null;
if (playerel.contains(activeel) || playerel === activeel) {
this.previouslyactiveel_ = activeel;
this.focus();
}
}
/**
* conditionally blur the element and refocus the last focused element
*
* @private
*/
;
_proto.conditionalblur_ = function conditionalblur_() {
if (this.previouslyactiveel_) {
this.previouslyactiveel_.focus();
this.previouslyactiveel_ = null;
}
}
/**
* keydown handler. attached when modal is focused.
*
* @listens keydown
*/
;
_proto.handlekeydown = function handlekeydown(event) {
// do not allow keydowns to reach out of the modal dialog.
event.stoppropagation();
if (keycode__webpack_imported_module_3___default.a.iseventkey(event, 'escape') && this.closeable()) {
event.preventdefault();
this.close();
return;
} // exit early if it isn't a tab key
if (!keycode__webpack_imported_module_3___default.a.iseventkey(event, 'tab')) {
return;
}
var focusableels = this.focusableels_();
var activeel = this.el_.queryselector(':focus');
var focusindex;
for (var i = 0; i < focusableels.length; i++) {
if (activeel === focusableels[i]) {
focusindex = i;
break;
}
}
if (global_document__webpack_imported_module_1___default.a.activeelement === this.el_) {
focusindex = 0;
}
if (event.shiftkey && focusindex === 0) {
focusableels[focusableels.length - 1].focus();
event.preventdefault();
} else if (!event.shiftkey && focusindex === focusableels.length - 1) {
focusableels[0].focus();
event.preventdefault();
}
}
/**
* get all focusable elements
*
* @private
*/
;
_proto.focusableels_ = function focusableels_() {
var allchildren = this.el_.queryselectorall('*');
return array.prototype.filter.call(allchildren, function (child) {
return (child instanceof global_window__webpack_imported_module_0___default.a.htmlanchorelement || child instanceof global_window__webpack_imported_module_0___default.a.htmlareaelement) && child.hasattribute('href') || (child instanceof global_window__webpack_imported_module_0___default.a.htmlinputelement || child instanceof global_window__webpack_imported_module_0___default.a.htmlselectelement || child instanceof global_window__webpack_imported_module_0___default.a.htmltextareaelement || child instanceof global_window__webpack_imported_module_0___default.a.htmlbuttonelement) && !child.hasattribute('disabled') || child instanceof global_window__webpack_imported_module_0___default.a.htmliframeelement || child instanceof global_window__webpack_imported_module_0___default.a.htmlobjectelement || child instanceof global_window__webpack_imported_module_0___default.a.htmlembedelement || child.hasattribute('tabindex') && child.getattribute('tabindex') !== -1 || child.hasattribute('contenteditable');
});
};
return modaldialog;
}(component$1);
/**
* default options for `modaldialog` default options.
*
* @type {object}
* @private
*/
modaldialog.prototype.options_ = {
pauseonopen: true,
temporary: true
};
component$1.registercomponent('modaldialog', modaldialog);
/**
* common functionaliy between {@link texttracklist}, {@link audiotracklist}, and
* {@link videotracklist}
*
* @extends eventtarget
*/
var tracklist = /*#__pure__*/function (_eventtarget) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(tracklist, _eventtarget);
/**
* create an instance of this class
*
* @param {track[]} tracks
* a list of tracks to initialize the list with.
*
* @abstract
*/
function tracklist(tracks) {
var _this;
if (tracks === void 0) {
tracks = [];
}
_this = _eventtarget.call(this) || this;
_this.tracks_ = [];
/**
* @memberof tracklist
* @member {number} length
* the current number of `track`s in the this trackist.
* @instance
*/
object.defineproperty(_babel_runtime_helpers_assertthisinitialized__webpack_imported_module_4___default()(_this), 'length', {
get: function get() {
return this.tracks_.length;
}
});
for (var i = 0; i < tracks.length; i++) {
_this.addtrack(tracks[i]);
}
return _this;
}
/**
* add a {@link track} to the `tracklist`
*
* @param {track} track
* the audio, video, or text track to add to the list.
*
* @fires tracklist#addtrack
*/
var _proto = tracklist.prototype;
_proto.addtrack = function addtrack(track) {
var _this2 = this;
var index = this.tracks_.length;
if (!('' + index in this)) {
object.defineproperty(this, index, {
get: function get() {
return this.tracks_[index];
}
});
} // do not add duplicate tracks
if (this.tracks_.indexof(track) === -1) {
this.tracks_.push(track);
/**
* triggered when a track is added to a track list.
*
* @event tracklist#addtrack
* @type {eventtarget~event}
* @property {track} track
* a reference to track that was added.
*/
this.trigger({
track: track,
type: 'addtrack',
target: this
});
}
/**
* triggered when a track label is changed.
*
* @event tracklist#addtrack
* @type {eventtarget~event}
* @property {track} track
* a reference to track that was added.
*/
track.labelchange_ = function () {
_this2.trigger({
track: track,
type: 'labelchange',
target: _this2
});
};
if (isevented(track)) {
track.addeventlistener('labelchange', track.labelchange_);
}
}
/**
* remove a {@link track} from the `tracklist`
*
* @param {track} rtrack
* the audio, video, or text track to remove from the list.
*
* @fires tracklist#removetrack
*/
;
_proto.removetrack = function removetrack(rtrack) {
var track;
for (var i = 0, l = this.length; i < l; i++) {
if (this[i] === rtrack) {
track = this[i];
if (track.off) {
track.off();
}
this.tracks_.splice(i, 1);
break;
}
}
if (!track) {
return;
}
/**
* triggered when a track is removed from track list.
*
* @event tracklist#removetrack
* @type {eventtarget~event}
* @property {track} track
* a reference to track that was removed.
*/
this.trigger({
track: track,
type: 'removetrack',
target: this
});
}
/**
* get a track from the tracklist by a tracks id
*
* @param {string} id - the id of the track to get
* @method gettrackbyid
* @return {track}
* @private
*/
;
_proto.gettrackbyid = function gettrackbyid(id) {
var result = null;
for (var i = 0, l = this.length; i < l; i++) {
var track = this[i];
if (track.id === id) {
result = track;
break;
}
}
return result;
};
return tracklist;
}(eventtarget$2);
/**
* triggered when a different track is selected/enabled.
*
* @event tracklist#change
* @type {eventtarget~event}
*/
/**
* events that can be called with on + eventname. see {@link eventhandler}.
*
* @property {object} tracklist#allowedevents_
* @private
*/
tracklist.prototype.allowedevents_ = {
change: 'change',
addtrack: 'addtrack',
removetrack: 'removetrack',
labelchange: 'labelchange'
}; // emulate attribute eventhandler support to allow for feature detection
for (var event in tracklist.prototype.allowedevents_) {
tracklist.prototype['on' + event] = null;
}
/**
* anywhere we call this function we diverge from the spec
* as we only support one enabled audiotrack at a time
*
* @param {audiotracklist} list
* list to work on
*
* @param {audiotrack} track
* the track to skip
*
* @private
*/
var disableothers$1 = function disableothers(list, track) {
for (var i = 0; i < list.length; i++) {
if (!object.keys(list[i]).length || track.id === list[i].id) {
continue;
} // another audio track is enabled, disable it
list[i].enabled = false;
}
};
/**
* the current list of {@link audiotrack} for a media file.
*
* @see [spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#audiotracklist}
* @extends tracklist
*/
var audiotracklist = /*#__pure__*/function (_tracklist) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(audiotracklist, _tracklist);
/**
* create an instance of this class.
*
* @param {audiotrack[]} [tracks=[]]
* a list of `audiotrack` to instantiate the list with.
*/
function audiotracklist(tracks) {
var _this;
if (tracks === void 0) {
tracks = [];
}
// make sure only 1 track is enabled
// sorted from last index to first index
for (var i = tracks.length - 1; i >= 0; i--) {
if (tracks[i].enabled) {
disableothers$1(tracks, tracks[i]);
break;
}
}
_this = _tracklist.call(this, tracks) || this;
_this.changing_ = false;
return _this;
}
/**
* add an {@link audiotrack} to the `audiotracklist`.
*
* @param {audiotrack} track
* the audiotrack to add to the list
*
* @fires tracklist#addtrack
*/
var _proto = audiotracklist.prototype;
_proto.addtrack = function addtrack(track) {
var _this2 = this;
if (track.enabled) {
disableothers$1(this, track);
}
_tracklist.prototype.addtrack.call(this, track); // native tracks don't have this
if (!track.addeventlistener) {
return;
}
track.enabledchange_ = function () {
// when we are disabling other tracks (since we don't support
// more than one track at a time) we will set changing_
// to true so that we don't trigger additional change events
if (_this2.changing_) {
return;
}
_this2.changing_ = true;
disableothers$1(_this2, track);
_this2.changing_ = false;
_this2.trigger('change');
};
/**
* @listens audiotrack#enabledchange
* @fires tracklist#change
*/
track.addeventlistener('enabledchange', track.enabledchange_);
};
_proto.removetrack = function removetrack(rtrack) {
_tracklist.prototype.removetrack.call(this, rtrack);
if (rtrack.removeeventlistener && rtrack.enabledchange_) {
rtrack.removeeventlistener('enabledchange', rtrack.enabledchange_);
rtrack.enabledchange_ = null;
}
};
return audiotracklist;
}(tracklist);
/**
* un-select all other {@link videotrack}s that are selected.
*
* @param {videotracklist} list
* list to work on
*
* @param {videotrack} track
* the track to skip
*
* @private
*/
var disableothers = function disableothers(list, track) {
for (var i = 0; i < list.length; i++) {
if (!object.keys(list[i]).length || track.id === list[i].id) {
continue;
} // another video track is enabled, disable it
list[i].selected = false;
}
};
/**
* the current list of {@link videotrack} for a video.
*
* @see [spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#videotracklist}
* @extends tracklist
*/
var videotracklist = /*#__pure__*/function (_tracklist) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(videotracklist, _tracklist);
/**
* create an instance of this class.
*
* @param {videotrack[]} [tracks=[]]
* a list of `videotrack` to instantiate the list with.
*/
function videotracklist(tracks) {
var _this;
if (tracks === void 0) {
tracks = [];
}
// make sure only 1 track is enabled
// sorted from last index to first index
for (var i = tracks.length - 1; i >= 0; i--) {
if (tracks[i].selected) {
disableothers(tracks, tracks[i]);
break;
}
}
_this = _tracklist.call(this, tracks) || this;
_this.changing_ = false;
/**
* @member {number} videotracklist#selectedindex
* the current index of the selected {@link videotrack`}.
*/
object.defineproperty(_babel_runtime_helpers_assertthisinitialized__webpack_imported_module_4___default()(_this), 'selectedindex', {
get: function get() {
for (var _i = 0; _i < this.length; _i++) {
if (this[_i].selected) {
return _i;
}
}
return -1;
},
set: function set() {}
});
return _this;
}
/**
* add a {@link videotrack} to the `videotracklist`.
*
* @param {videotrack} track
* the videotrack to add to the list
*
* @fires tracklist#addtrack
*/
var _proto = videotracklist.prototype;
_proto.addtrack = function addtrack(track) {
var _this2 = this;
if (track.selected) {
disableothers(this, track);
}
_tracklist.prototype.addtrack.call(this, track); // native tracks don't have this
if (!track.addeventlistener) {
return;
}
track.selectedchange_ = function () {
if (_this2.changing_) {
return;
}
_this2.changing_ = true;
disableothers(_this2, track);
_this2.changing_ = false;
_this2.trigger('change');
};
/**
* @listens videotrack#selectedchange
* @fires tracklist#change
*/
track.addeventlistener('selectedchange', track.selectedchange_);
};
_proto.removetrack = function removetrack(rtrack) {
_tracklist.prototype.removetrack.call(this, rtrack);
if (rtrack.removeeventlistener && rtrack.selectedchange_) {
rtrack.removeeventlistener('selectedchange', rtrack.selectedchange_);
rtrack.selectedchange_ = null;
}
};
return videotracklist;
}(tracklist);
/**
* the current list of {@link texttrack} for a media file.
*
* @see [spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#texttracklist}
* @extends tracklist
*/
var texttracklist = /*#__pure__*/function (_tracklist) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(texttracklist, _tracklist);
function texttracklist() {
return _tracklist.apply(this, arguments) || this;
}
var _proto = texttracklist.prototype;
/**
* add a {@link texttrack} to the `texttracklist`
*
* @param {texttrack} track
* the text track to add to the list.
*
* @fires tracklist#addtrack
*/
_proto.addtrack = function addtrack(track) {
var _this = this;
_tracklist.prototype.addtrack.call(this, track);
if (!this.queuechange_) {
this.queuechange_ = function () {
return _this.queuetrigger('change');
};
}
if (!this.triggerselectedlanguagechange) {
this.triggerselectedlanguagechange_ = function () {
return _this.trigger('selectedlanguagechange');
};
}
/**
* @listens texttrack#modechange
* @fires tracklist#change
*/
track.addeventlistener('modechange', this.queuechange_);
var nonlanguagetexttrackkind = ['metadata', 'chapters'];
if (nonlanguagetexttrackkind.indexof(track.kind) === -1) {
track.addeventlistener('modechange', this.triggerselectedlanguagechange_);
}
};
_proto.removetrack = function removetrack(rtrack) {
_tracklist.prototype.removetrack.call(this, rtrack); // manually remove the event handlers we added
if (rtrack.removeeventlistener) {
if (this.queuechange_) {
rtrack.removeeventlistener('modechange', this.queuechange_);
}
if (this.selectedlanguagechange_) {
rtrack.removeeventlistener('modechange', this.triggerselectedlanguagechange_);
}
}
};
return texttracklist;
}(tracklist);
/**
* @file html-track-element-list.js
*/
/**
* the current list of {@link htmltrackelement}s.
*/
var htmltrackelementlist = /*#__pure__*/function () {
/**
* create an instance of this class.
*
* @param {htmltrackelement[]} [tracks=[]]
* a list of `htmltrackelement` to instantiate the list with.
*/
function htmltrackelementlist(trackelements) {
if (trackelements === void 0) {
trackelements = [];
}
this.trackelements_ = [];
/**
* @memberof htmltrackelementlist
* @member {number} length
* the current number of `track`s in the this trackist.
* @instance
*/
object.defineproperty(this, 'length', {
get: function get() {
return this.trackelements_.length;
}
});
for (var i = 0, length = trackelements.length; i < length; i++) {
this.addtrackelement_(trackelements[i]);
}
}
/**
* add an {@link htmltrackelement} to the `htmltrackelementlist`
*
* @param {htmltrackelement} trackelement
* the track element to add to the list.
*
* @private
*/
var _proto = htmltrackelementlist.prototype;
_proto.addtrackelement_ = function addtrackelement_(trackelement) {
var index = this.trackelements_.length;
if (!('' + index in this)) {
object.defineproperty(this, index, {
get: function get() {
return this.trackelements_[index];
}
});
} // do not add duplicate elements
if (this.trackelements_.indexof(trackelement) === -1) {
this.trackelements_.push(trackelement);
}
}
/**
* get an {@link htmltrackelement} from the `htmltrackelementlist` given an
* {@link texttrack}.
*
* @param {texttrack} track
* the track associated with a track element.
*
* @return {htmltrackelement|undefined}
* the track element that was found or undefined.
*
* @private
*/
;
_proto.gettrackelementbytrack_ = function gettrackelementbytrack_(track) {
var trackelement_;
for (var i = 0, length = this.trackelements_.length; i < length; i++) {
if (track === this.trackelements_[i].track) {
trackelement_ = this.trackelements_[i];
break;
}
}
return trackelement_;
}
/**
* remove a {@link htmltrackelement} from the `htmltrackelementlist`
*
* @param {htmltrackelement} trackelement
* the track element to remove from the list.
*
* @private
*/
;
_proto.removetrackelement_ = function removetrackelement_(trackelement) {
for (var i = 0, length = this.trackelements_.length; i < length; i++) {
if (trackelement === this.trackelements_[i]) {
if (this.trackelements_[i].track && typeof this.trackelements_[i].track.off === 'function') {
this.trackelements_[i].track.off();
}
if (typeof this.trackelements_[i].off === 'function') {
this.trackelements_[i].off();
}
this.trackelements_.splice(i, 1);
break;
}
}
};
return htmltrackelementlist;
}();
/**
* @file text-track-cue-list.js
*/
/**
* @typedef {object} texttrackcuelist~texttrackcue
*
* @property {string} id
* the unique id for this text track cue
*
* @property {number} starttime
* the start time for this text track cue
*
* @property {number} endtime
* the end time for this text track cue
*
* @property {boolean} pauseonexit
* pause when the end time is reached if true.
*
* @see [spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackcue}
*/
/**
* a list of texttrackcues.
*
* @see [spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackcuelist}
*/
var texttrackcuelist = /*#__pure__*/function () {
/**
* create an instance of this class..
*
* @param {array} cues
* a list of cues to be initialized with
*/
function texttrackcuelist(cues) {
texttrackcuelist.prototype.setcues_.call(this, cues);
/**
* @memberof texttrackcuelist
* @member {number} length
* the current number of `texttrackcue`s in the texttrackcuelist.
* @instance
*/
object.defineproperty(this, 'length', {
get: function get() {
return this.length_;
}
});
}
/**
* a setter for cues in this list. creates getters
* an an index for the cues.
*
* @param {array} cues
* an array of cues to set
*
* @private
*/
var _proto = texttrackcuelist.prototype;
_proto.setcues_ = function setcues_(cues) {
var oldlength = this.length || 0;
var i = 0;
var l = cues.length;
this.cues_ = cues;
this.length_ = cues.length;
var defineprop = function defineprop(index) {
if (!('' + index in this)) {
object.defineproperty(this, '' + index, {
get: function get() {
return this.cues_[index];
}
});
}
};
if (oldlength < l) {
i = oldlength;
for (; i < l; i++) {
defineprop.call(this, i);
}
}
}
/**
* get a `texttrackcue` that is currently in the `texttrackcuelist` by id.
*
* @param {string} id
* the id of the cue that should be searched for.
*
* @return {texttrackcuelist~texttrackcue|null}
* a single cue or null if none was found.
*/
;
_proto.getcuebyid = function getcuebyid(id) {
var result = null;
for (var i = 0, l = this.length; i < l; i++) {
var cue = this[i];
if (cue.id === id) {
result = cue;
break;
}
}
return result;
};
return texttrackcuelist;
}();
/**
* @file track-kinds.js
*/
/**
* all possible `videotrackkind`s
*
* @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-videotrack-kind
* @typedef videotrack~kind
* @enum
*/
var videotrackkind = {
alternative: 'alternative',
captions: 'captions',
main: 'main',
sign: 'sign',
subtitles: 'subtitles',
commentary: 'commentary'
};
/**
* all possible `audiotrackkind`s
*
* @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-audiotrack-kind
* @typedef audiotrack~kind
* @enum
*/
var audiotrackkind = {
'alternative': 'alternative',
'descriptions': 'descriptions',
'main': 'main',
'main-desc': 'main-desc',
'translation': 'translation',
'commentary': 'commentary'
};
/**
* all possible `texttrackkind`s
*
* @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-texttrack-kind
* @typedef texttrack~kind
* @enum
*/
var texttrackkind = {
subtitles: 'subtitles',
captions: 'captions',
descriptions: 'descriptions',
chapters: 'chapters',
metadata: 'metadata'
};
/**
* all possible `texttrackmode`s
*
* @see https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackmode
* @typedef texttrack~mode
* @enum
*/
var texttrackmode = {
disabled: 'disabled',
hidden: 'hidden',
showing: 'showing'
};
/**
* a track class that contains all of the common functionality for {@link audiotrack},
* {@link videotrack}, and {@link texttrack}.
*
* > note: this class should not be used directly
*
* @see {@link https://html.spec.whatwg.org/multipage/embedded-content.html}
* @extends eventtarget
* @abstract
*/
var track = /*#__pure__*/function (_eventtarget) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(track, _eventtarget);
/**
* create an instance of this class.
*
* @param {object} [options={}]
* object of option names and values
*
* @param {string} [options.kind='']
* a valid kind for the track type you are creating.
*
* @param {string} [options.id='vjs_track_' + guid.newguid()]
* a unique id for this audiotrack.
*
* @param {string} [options.label='']
* the menu label for this track.
*
* @param {string} [options.language='']
* a valid two character language code.
*
* @abstract
*/
function track(options) {
var _this;
if (options === void 0) {
options = {};
}
_this = _eventtarget.call(this) || this;
var trackprops = {
id: options.id || 'vjs_track_' + newguid(),
kind: options.kind || '',
language: options.language || ''
};
var label = options.label || '';
/**
* @memberof track
* @member {string} id
* the id of this track. cannot be changed after creation.
* @instance
*
* @readonly
*/
/**
* @memberof track
* @member {string} kind
* the kind of track that this is. cannot be changed after creation.
* @instance
*
* @readonly
*/
/**
* @memberof track
* @member {string} language
* the two letter language code for this track. cannot be changed after
* creation.
* @instance
*
* @readonly
*/
var _loop = function _loop(key) {
object.defineproperty(_babel_runtime_helpers_assertthisinitialized__webpack_imported_module_4___default()(_this), key, {
get: function get() {
return trackprops[key];
},
set: function set() {}
});
};
for (var key in trackprops) {
_loop(key);
}
/**
* @memberof track
* @member {string} label
* the label of this track. cannot be changed after creation.
* @instance
*
* @fires track#labelchange
*/
object.defineproperty(_babel_runtime_helpers_assertthisinitialized__webpack_imported_module_4___default()(_this), 'label', {
get: function get() {
return label;
},
set: function set(newlabel) {
if (newlabel !== label) {
label = newlabel;
/**
* an event that fires when label changes on this track.
*
* > note: this is not part of the spec!
*
* @event track#labelchange
* @type {eventtarget~event}
*/
this.trigger('labelchange');
}
}
});
return _this;
}
return track;
}(eventtarget$2);
/**
* @file url.js
* @module url
*/
/**
* @typedef {object} url:urlobject
*
* @property {string} protocol
* the protocol of the url that was parsed.
*
* @property {string} hostname
* the hostname of the url that was parsed.
*
* @property {string} port
* the port of the url that was parsed.
*
* @property {string} pathname
* the pathname of the url that was parsed.
*
* @property {string} search
* the search query of the url that was parsed.
*
* @property {string} hash
* the hash of the url that was parsed.
*
* @property {string} host
* the host of the url that was parsed.
*/
/**
* resolve and parse the elements of a url.
*
* @function
* @param {string} url
* the url to parse
*
* @return {url:urlobject}
* an object of url details
*/
var parseurl = function parseurl(url) {
// this entire method can be replace with url once we are able to drop ie11
var props = ['protocol', 'hostname', 'port', 'pathname', 'search', 'hash', 'host']; // add the url to an anchor and let the browser parse the url
var a = global_document__webpack_imported_module_1___default.a.createelement('a');
a.href = url; // copy the specific url properties to a new object
// this is also needed for ie because the anchor loses its
// properties when it's removed from the dom
var details = {};
for (var i = 0; i < props.length; i++) {
details[props[i]] = a[props[i]];
} // ie adds the port to the host property unlike everyone else. if
// a port identifier is added for standard ports, strip it.
if (details.protocol === 'http:') {
details.host = details.host.replace(/:80$/, '');
}
if (details.protocol === 'https:') {
details.host = details.host.replace(/:443$/, '');
}
if (!details.protocol) {
details.protocol = global_window__webpack_imported_module_0___default.a.location.protocol;
}
/* istanbul ignore if */
if (!details.host) {
details.host = global_window__webpack_imported_module_0___default.a.location.host;
}
return details;
};
/**
* get absolute version of relative url. used to tell flash the correct url.
*
* @function
* @param {string} url
* url to make absolute
*
* @return {string}
* absolute url
*
* @see http://stackoverflow.com/questions/470832/getting-an-absolute-url-from-a-relative-one-ie6-issue
*/
var getabsoluteurl = function getabsoluteurl(url) {
// check if absolute url
if (!url.match(/^https?:\/\//)) {
// convert to absolute url. flash hosted off-site needs an absolute url.
// add the url to an anchor and let the browser parse the url
var a = global_document__webpack_imported_module_1___default.a.createelement('a');
a.href = url;
url = a.href;
}
return url;
};
/**
* returns the extension of the passed file name. it will return an empty string
* if passed an invalid path.
*
* @function
* @param {string} path
* the filename path like '/path/to/file.mp4'
*
* @return {string}
* the extension in lower case or an empty string if no
* extension could be found.
*/
var getfileextension = function getfileextension(path) {
if (typeof path === 'string') {
var splitpathre = /^(\/?)([\s\s]*?)((?:\.{1,2}|[^\/]+?)(\.([^\.\/\?]+)))(?:[\/]*|[\?].*)$/;
var pathparts = splitpathre.exec(path);
if (pathparts) {
return pathparts.pop().tolowercase();
}
}
return '';
};
/**
* returns whether the url passed is a cross domain request or not.
*
* @function
* @param {string} url
* the url to check.
*
* @param {object} [winloc]
* the domain to check the url against, defaults to window.location
*
* @param {string} [winloc.protocol]
* the window location protocol defaults to window.location.protocol
*
* @param {string} [winloc.host]
* the window location host defaults to window.location.host
*
* @return {boolean}
* whether it is a cross domain request or not.
*/
var iscrossorigin = function iscrossorigin(url, winloc) {
if (winloc === void 0) {
winloc = global_window__webpack_imported_module_0___default.a.location;
}
var urlinfo = parseurl(url); // ie8 protocol relative urls will return ':' for protocol
var srcprotocol = urlinfo.protocol === ':' ? winloc.protocol : urlinfo.protocol; // check if url is for another domain/origin
// ie8 doesn't know location.origin, so we won't rely on it here
var crossorigin = srcprotocol + urlinfo.host !== winloc.protocol + winloc.host;
return crossorigin;
};
var url = /*#__pure__*/object.freeze({
__proto__: null,
parseurl: parseurl,
getabsoluteurl: getabsoluteurl,
getfileextension: getfileextension,
iscrossorigin: iscrossorigin
});
/**
* takes a webvtt file contents and parses it into cues
*
* @param {string} srccontent
* webvtt file contents
*
* @param {texttrack} track
* texttrack to add cues to. cues come from the srccontent.
*
* @private
*/
var parsecues = function parsecues(srccontent, track) {
var parser = new global_window__webpack_imported_module_0___default.a.webvtt.parser(global_window__webpack_imported_module_0___default.a, global_window__webpack_imported_module_0___default.a.vttjs, global_window__webpack_imported_module_0___default.a.webvtt.stringdecoder());
var errors = [];
parser.oncue = function (cue) {
track.addcue(cue);
};
parser.onparsingerror = function (error) {
errors.push(error);
};
parser.onflush = function () {
track.trigger({
type: 'loadeddata',
target: track
});
};
parser.parse(srccontent);
if (errors.length > 0) {
if (global_window__webpack_imported_module_0___default.a.console && global_window__webpack_imported_module_0___default.a.console.groupcollapsed) {
global_window__webpack_imported_module_0___default.a.console.groupcollapsed("text track parsing errors for " + track.src);
}
errors.foreach(function (error) {
return log$1.error(error);
});
if (global_window__webpack_imported_module_0___default.a.console && global_window__webpack_imported_module_0___default.a.console.groupend) {
global_window__webpack_imported_module_0___default.a.console.groupend();
}
}
parser.flush();
};
/**
* load a `texttrack` from a specified url.
*
* @param {string} src
* url to load track from.
*
* @param {texttrack} track
* track to add cues to. comes from the content at the end of `url`.
*
* @private
*/
var loadtrack = function loadtrack(src, track) {
var opts = {
uri: src
};
var crossorigin = iscrossorigin(src);
if (crossorigin) {
opts.cors = crossorigin;
}
var withcredentials = track.tech_.crossorigin() === 'use-credentials';
if (withcredentials) {
opts.withcredentials = withcredentials;
}
_videojs_xhr__webpack_imported_module_7___default()(opts, bind(this, function (err, response, responsebody) {
if (err) {
return log$1.error(err, response);
}
track.loaded_ = true; // make sure that vttjs has loaded, otherwise, wait till it finished loading
// note: this is only used for the alt/video.novtt.js build
if (typeof global_window__webpack_imported_module_0___default.a.webvtt !== 'function') {
if (track.tech_) {
// to prevent use before define eslint error, we define loadhandler
// as a let here
track.tech_.any(['vttjsloaded', 'vttjserror'], function (event) {
if (event.type === 'vttjserror') {
log$1.error("vttjs failed to load, stopping trying to process " + track.src);
return;
}
return parsecues(responsebody, track);
});
}
} else {
parsecues(responsebody, track);
}
}));
};
/**
* a representation of a single `texttrack`.
*
* @see [spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#texttrack}
* @extends track
*/
var texttrack = /*#__pure__*/function (_track) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(texttrack, _track);
/**
* create an instance of this class.
*
* @param {object} options={}
* object of option names and values
*
* @param {tech} options.tech
* a reference to the tech that owns this texttrack.
*
* @param {texttrack~kind} [options.kind='subtitles']
* a valid text track kind.
*
* @param {texttrack~mode} [options.mode='disabled']
* a valid text track mode.
*
* @param {string} [options.id='vjs_track_' + guid.newguid()]
* a unique id for this texttrack.
*
* @param {string} [options.label='']
* the menu label for this track.
*
* @param {string} [options.language='']
* a valid two character language code.
*
* @param {string} [options.srclang='']
* a valid two character language code. an alternative, but deprioritized
* version of `options.language`
*
* @param {string} [options.src]
* a url to texttrack cues.
*
* @param {boolean} [options.default]
* if this track should default to on or off.
*/
function texttrack(options) {
var _this;
if (options === void 0) {
options = {};
}
if (!options.tech) {
throw new error('a tech was not provided.');
}
var settings = mergeoptions$3(options, {
kind: texttrackkind[options.kind] || 'subtitles',
language: options.language || options.srclang || ''
});
var mode = texttrackmode[settings.mode] || 'disabled';
var default_ = settings["default"];
if (settings.kind === 'metadata' || settings.kind === 'chapters') {
mode = 'hidden';
}
_this = _track.call(this, settings) || this;
_this.tech_ = settings.tech;
_this.cues_ = [];
_this.activecues_ = [];
_this.preload_ = _this.tech_.preloadtexttracks !== false;
var cues = new texttrackcuelist(_this.cues_);
var activecues = new texttrackcuelist(_this.activecues_);
var changed = false;
_this.timeupdatehandler = bind(_babel_runtime_helpers_assertthisinitialized__webpack_imported_module_4___default()(_this), function (event) {
if (event === void 0) {
event = {};
}
if (this.tech_.isdisposed()) {
return;
}
if (!this.tech_.isready_) {
if (event.type !== 'timeupdate') {
this.rvf_ = this.tech_.requestvideoframecallback(this.timeupdatehandler);
}
return;
} // accessing this.activecues for the side-effects of updating itself
// due to its nature as a getter function. do not remove or cues will
// stop updating!
// use the setter to prevent deletion from uglify (pure_getters rule)
this.activecues = this.activecues;
if (changed) {
this.trigger('cuechange');
changed = false;
}
if (event.type !== 'timeupdate') {
this.rvf_ = this.tech_.requestvideoframecallback(this.timeupdatehandler);
}
});
var disposehandler = function disposehandler() {
_this.stoptracking();
};
_this.tech_.one('dispose', disposehandler);
if (mode !== 'disabled') {
_this.starttracking();
}
object.defineproperties(_babel_runtime_helpers_assertthisinitialized__webpack_imported_module_4___default()(_this), {
/**
* @memberof texttrack
* @member {boolean} default
* if this track was set to be on or off by default. cannot be changed after
* creation.
* @instance
*
* @readonly
*/
"default": {
get: function get() {
return default_;
},
set: function set() {}
},
/**
* @memberof texttrack
* @member {string} mode
* set the mode of this texttrack to a valid {@link texttrack~mode}. will
* not be set if setting to an invalid mode.
* @instance
*
* @fires texttrack#modechange
*/
mode: {
get: function get() {
return mode;
},
set: function set(newmode) {
if (!texttrackmode[newmode]) {
return;
}
if (mode === newmode) {
return;
}
mode = newmode;
if (!this.preload_ && mode !== 'disabled' && this.cues.length === 0) {
// on-demand load.
loadtrack(this.src, this);
}
this.stoptracking();
if (mode !== 'disabled') {
this.starttracking();
}
/**
* an event that fires when mode changes on this track. this allows
* the texttracklist that holds this track to act accordingly.
*
* > note: this is not part of the spec!
*
* @event texttrack#modechange
* @type {eventtarget~event}
*/
this.trigger('modechange');
}
},
/**
* @memberof texttrack
* @member {texttrackcuelist} cues
* the text track cue list for this texttrack.
* @instance
*/
cues: {
get: function get() {
if (!this.loaded_) {
return null;
}
return cues;
},
set: function set() {}
},
/**
* @memberof texttrack
* @member {texttrackcuelist} activecues
* the list text track cues that are currently active for this texttrack.
* @instance
*/
activecues: {
get: function get() {
if (!this.loaded_) {
return null;
} // nothing to do
if (this.cues.length === 0) {
return activecues;
}
var ct = this.tech_.currenttime();
var active = [];
for (var i = 0, l = this.cues.length; i < l; i++) {
var cue = this.cues[i];
if (cue.starttime <= ct && cue.endtime >= ct) {
active.push(cue);
} else if (cue.starttime === cue.endtime && cue.starttime <= ct && cue.starttime + 0.5 >= ct) {
active.push(cue);
}
}
changed = false;
if (active.length !== this.activecues_.length) {
changed = true;
} else {
for (var _i = 0; _i < active.length; _i++) {
if (this.activecues_.indexof(active[_i]) === -1) {
changed = true;
}
}
}
this.activecues_ = active;
activecues.setcues_(this.activecues_);
return activecues;
},
// /!\ keep this setter empty (see the timeupdate handler above)
set: function set() {}
}
});
if (settings.src) {
_this.src = settings.src;
if (!_this.preload_) {
// tracks will load on-demand.
// act like we're loaded for other purposes.
_this.loaded_ = true;
}
if (_this.preload_ || settings.kind !== 'subtitles' && settings.kind !== 'captions') {
loadtrack(_this.src, _babel_runtime_helpers_assertthisinitialized__webpack_imported_module_4___default()(_this));
}
} else {
_this.loaded_ = true;
}
return _this;
}
var _proto = texttrack.prototype;
_proto.starttracking = function starttracking() {
// more precise cues based on requestvideoframecallback with a requestanimationfram fallback
this.rvf_ = this.tech_.requestvideoframecallback(this.timeupdatehandler); // also listen to timeupdate in case rvfc/raf stops (window in background, audio in video el)
this.tech_.on('timeupdate', this.timeupdatehandler);
};
_proto.stoptracking = function stoptracking() {
if (this.rvf_) {
this.tech_.cancelvideoframecallback(this.rvf_);
this.rvf_ = undefined;
}
this.tech_.off('timeupdate', this.timeupdatehandler);
}
/**
* add a cue to the internal list of cues.
*
* @param {texttrack~cue} cue
* the cue to add to our internal list
*/
;
_proto.addcue = function addcue(originalcue) {
var cue = originalcue;
if (cue.constructor && cue.constructor.name !== 'vttcue') {
cue = new global_window__webpack_imported_module_0___default.a.vttjs.vttcue(originalcue.starttime, originalcue.endtime, originalcue.text);
for (var prop in originalcue) {
if (!(prop in cue)) {
cue[prop] = originalcue[prop];
}
} // make sure that `id` is copied over
cue.id = originalcue.id;
cue.originalcue_ = originalcue;
}
var tracks = this.tech_.texttracks();
for (var i = 0; i < tracks.length; i++) {
if (tracks[i] !== this) {
tracks[i].removecue(cue);
}
}
this.cues_.push(cue);
this.cues.setcues_(this.cues_);
}
/**
* remove a cue from our internal list
*
* @param {texttrack~cue} removecue
* the cue to remove from our internal list
*/
;
_proto.removecue = function removecue(_removecue) {
var i = this.cues_.length;
while (i--) {
var cue = this.cues_[i];
if (cue === _removecue || cue.originalcue_ && cue.originalcue_ === _removecue) {
this.cues_.splice(i, 1);
this.cues.setcues_(this.cues_);
break;
}
}
};
return texttrack;
}(track);
/**
* cuechange - one or more cues in the track have become active or stopped being active.
*/
texttrack.prototype.allowedevents_ = {
cuechange: 'cuechange'
};
/**
* a representation of a single `audiotrack`. if it is part of an {@link audiotracklist}
* only one `audiotrack` in the list will be enabled at a time.
*
* @see [spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#audiotrack}
* @extends track
*/
var audiotrack = /*#__pure__*/function (_track) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(audiotrack, _track);
/**
* create an instance of this class.
*
* @param {object} [options={}]
* object of option names and values
*
* @param {audiotrack~kind} [options.kind='']
* a valid audio track kind
*
* @param {string} [options.id='vjs_track_' + guid.newguid()]
* a unique id for this audiotrack.
*
* @param {string} [options.label='']
* the menu label for this track.
*
* @param {string} [options.language='']
* a valid two character language code.
*
* @param {boolean} [options.enabled]
* if this track is the one that is currently playing. if this track is part of
* an {@link audiotracklist}, only one {@link audiotrack} will be enabled.
*/
function audiotrack(options) {
var _this;
if (options === void 0) {
options = {};
}
var settings = mergeoptions$3(options, {
kind: audiotrackkind[options.kind] || ''
});
_this = _track.call(this, settings) || this;
var enabled = false;
/**
* @memberof audiotrack
* @member {boolean} enabled
* if this `audiotrack` is enabled or not. when setting this will
* fire {@link audiotrack#enabledchange} if the state of enabled is changed.
* @instance
*
* @fires videotrack#selectedchange
*/
object.defineproperty(_babel_runtime_helpers_assertthisinitialized__webpack_imported_module_4___default()(_this), 'enabled', {
get: function get() {
return enabled;
},
set: function set(newenabled) {
// an invalid or unchanged value
if (typeof newenabled !== 'boolean' || newenabled === enabled) {
return;
}
enabled = newenabled;
/**
* an event that fires when enabled changes on this track. this allows
* the audiotracklist that holds this track to act accordingly.
*
* > note: this is not part of the spec! native tracks will do
* this internally without an event.
*
* @event audiotrack#enabledchange
* @type {eventtarget~event}
*/
this.trigger('enabledchange');
}
}); // if the user sets this track to selected then
// set selected to that true value otherwise
// we keep it false
if (settings.enabled) {
_this.enabled = settings.enabled;
}
_this.loaded_ = true;
return _this;
}
return audiotrack;
}(track);
/**
* a representation of a single `videotrack`.
*
* @see [spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#videotrack}
* @extends track
*/
var videotrack = /*#__pure__*/function (_track) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(videotrack, _track);
/**
* create an instance of this class.
*
* @param {object} [options={}]
* object of option names and values
*
* @param {string} [options.kind='']
* a valid {@link videotrack~kind}
*
* @param {string} [options.id='vjs_track_' + guid.newguid()]
* a unique id for this audiotrack.
*
* @param {string} [options.label='']
* the menu label for this track.
*
* @param {string} [options.language='']
* a valid two character language code.
*
* @param {boolean} [options.selected]
* if this track is the one that is currently playing.
*/
function videotrack(options) {
var _this;
if (options === void 0) {
options = {};
}
var settings = mergeoptions$3(options, {
kind: videotrackkind[options.kind] || ''
});
_this = _track.call(this, settings) || this;
var selected = false;
/**
* @memberof videotrack
* @member {boolean} selected
* if this `videotrack` is selected or not. when setting this will
* fire {@link videotrack#selectedchange} if the state of selected changed.
* @instance
*
* @fires videotrack#selectedchange
*/
object.defineproperty(_babel_runtime_helpers_assertthisinitialized__webpack_imported_module_4___default()(_this), 'selected', {
get: function get() {
return selected;
},
set: function set(newselected) {
// an invalid or unchanged value
if (typeof newselected !== 'boolean' || newselected === selected) {
return;
}
selected = newselected;
/**
* an event that fires when selected changes on this track. this allows
* the videotracklist that holds this track to act accordingly.
*
* > note: this is not part of the spec! native tracks will do
* this internally without an event.
*
* @event videotrack#selectedchange
* @type {eventtarget~event}
*/
this.trigger('selectedchange');
}
}); // if the user sets this track to selected then
// set selected to that true value otherwise
// we keep it false
if (settings.selected) {
_this.selected = settings.selected;
}
return _this;
}
return videotrack;
}(track);
/**
* @memberof htmltrackelement
* @typedef {htmltrackelement~readystate}
* @enum {number}
*/
var none = 0;
var loading = 1;
var loaded = 2;
var error = 3;
/**
* a single track represented in the dom.
*
* @see [spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#htmltrackelement}
* @extends eventtarget
*/
var htmltrackelement = /*#__pure__*/function (_eventtarget) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(htmltrackelement, _eventtarget);
/**
* create an instance of this class.
*
* @param {object} options={}
* object of option names and values
*
* @param {tech} options.tech
* a reference to the tech that owns this htmltrackelement.
*
* @param {texttrack~kind} [options.kind='subtitles']
* a valid text track kind.
*
* @param {texttrack~mode} [options.mode='disabled']
* a valid text track mode.
*
* @param {string} [options.id='vjs_track_' + guid.newguid()]
* a unique id for this texttrack.
*
* @param {string} [options.label='']
* the menu label for this track.
*
* @param {string} [options.language='']
* a valid two character language code.
*
* @param {string} [options.srclang='']
* a valid two character language code. an alternative, but deprioritized
* version of `options.language`
*
* @param {string} [options.src]
* a url to texttrack cues.
*
* @param {boolean} [options.default]
* if this track should default to on or off.
*/
function htmltrackelement(options) {
var _this;
if (options === void 0) {
options = {};
}
_this = _eventtarget.call(this) || this;
var readystate;
var track = new texttrack(options);
_this.kind = track.kind;
_this.src = track.src;
_this.srclang = track.language;
_this.label = track.label;
_this["default"] = track["default"];
object.defineproperties(_babel_runtime_helpers_assertthisinitialized__webpack_imported_module_4___default()(_this), {
/**
* @memberof htmltrackelement
* @member {htmltrackelement~readystate} readystate
* the current ready state of the track element.
* @instance
*/
readystate: {
get: function get() {
return readystate;
}
},
/**
* @memberof htmltrackelement
* @member {texttrack} track
* the underlying texttrack object.
* @instance
*
*/
track: {
get: function get() {
return track;
}
}
});
readystate = none;
/**
* @listens texttrack#loadeddata
* @fires htmltrackelement#load
*/
track.addeventlistener('loadeddata', function () {
readystate = loaded;
_this.trigger({
type: 'load',
target: _babel_runtime_helpers_assertthisinitialized__webpack_imported_module_4___default()(_this)
});
});
return _this;
}
return htmltrackelement;
}(eventtarget$2);
htmltrackelement.prototype.allowedevents_ = {
load: 'load'
};
htmltrackelement.none = none;
htmltrackelement.loading = loading;
htmltrackelement.loaded = loaded;
htmltrackelement.error = error;
/*
* this file contains all track properties that are used in
* player.js, tech.js, html5.js and possibly other techs in the future.
*/
var normal = {
audio: {
listclass: audiotracklist,
trackclass: audiotrack,
capitalname: 'audio'
},
video: {
listclass: videotracklist,
trackclass: videotrack,
capitalname: 'video'
},
text: {
listclass: texttracklist,
trackclass: texttrack,
capitalname: 'text'
}
};
object.keys(normal).foreach(function (type) {
normal[type].gettername = type + "tracks";
normal[type].privatename = type + "tracks_";
});
var remote = {
remotetext: {
listclass: texttracklist,
trackclass: texttrack,
capitalname: 'remotetext',
gettername: 'remotetexttracks',
privatename: 'remotetexttracks_'
},
remotetextel: {
listclass: htmltrackelementlist,
trackclass: htmltrackelement,
capitalname: 'remotetexttrackels',
gettername: 'remotetexttrackels',
privatename: 'remotetexttrackels_'
}
};
var all = _babel_runtime_helpers_extends__webpack_imported_module_2___default()({}, normal, remote);
remote.names = object.keys(remote);
normal.names = object.keys(normal);
all.names = [].concat(remote.names).concat(normal.names);
/**
* an object containing a structure like: `{src: 'url', type: 'mimetype'}` or string
* that just contains the src url alone.
* * `var sourceobject = {src: 'http://ex.com/video.mp4', type: 'video/mp4'};`
* `var sourcestring = 'http://example.com/some-video.mp4';`
*
* @typedef {object|string} tech~sourceobject
*
* @property {string} src
* the url to the source
*
* @property {string} type
* the mime type of the source
*/
/**
* a function used by {@link tech} to create a new {@link texttrack}.
*
* @private
*
* @param {tech} self
* an instance of the tech class.
*
* @param {string} kind
* `texttrack` kind (subtitles, captions, descriptions, chapters, or metadata)
*
* @param {string} [label]
* label to identify the text track
*
* @param {string} [language]
* two letter language abbreviation
*
* @param {object} [options={}]
* an object with additional text track options
*
* @return {texttrack}
* the text track that was created.
*/
function createtrackhelper(self, kind, label, language, options) {
if (options === void 0) {
options = {};
}
var tracks = self.texttracks();
options.kind = kind;
if (label) {
options.label = label;
}
if (language) {
options.language = language;
}
options.tech = self;
var track = new all.text.trackclass(options);
tracks.addtrack(track);
return track;
}
/**
* this is the base class for media playback technology controllers, such as
* {@link html5}
*
* @extends component
*/
var tech = /*#__pure__*/function (_component) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(tech, _component);
/**
* create an instance of this tech.
*
* @param {object} [options]
* the key/value store of player options.
*
* @param {component~readycallback} ready
* callback function to call when the `html5` tech is ready.
*/
function tech(options, ready) {
var _this;
if (options === void 0) {
options = {};
}
if (ready === void 0) {
ready = function ready() {};
}
// we don't want the tech to report user activity automatically.
// this is done manually in addcontrolslisteners
options.reporttouchactivity = false;
_this = _component.call(this, null, options, ready) || this;
_this.ondurationchange_ = function (e) {
return _this.ondurationchange(e);
};
_this.trackprogress_ = function (e) {
return _this.trackprogress(e);
};
_this.trackcurrenttime_ = function (e) {
return _this.trackcurrenttime(e);
};
_this.stoptrackingcurrenttime_ = function (e) {
return _this.stoptrackingcurrenttime(e);
};
_this.disposesourcehandler_ = function (e) {
return _this.disposesourcehandler(e);
};
_this.queuedhanders_ = new set(); // keep track of whether the current source has played at all to
// implement a very limited played()
_this.hasstarted_ = false;
_this.on('playing', function () {
this.hasstarted_ = true;
});
_this.on('loadstart', function () {
this.hasstarted_ = false;
});
all.names.foreach(function (name) {
var props = all[name];
if (options && options[props.gettername]) {
_this[props.privatename] = options[props.gettername];
}
}); // manually track progress in cases where the browser/tech doesn't report it.
if (!_this.featuresprogressevents) {
_this.manualprogresson();
} // manually track timeupdates in cases where the browser/tech doesn't report it.
if (!_this.featurestimeupdateevents) {
_this.manualtimeupdateson();
}
['text', 'audio', 'video'].foreach(function (track) {
if (options["native" + track + "tracks"] === false) {
_this["featuresnative" + track + "tracks"] = false;
}
});
if (options.nativecaptions === false || options.nativetexttracks === false) {
_this.featuresnativetexttracks = false;
} else if (options.nativecaptions === true || options.nativetexttracks === true) {
_this.featuresnativetexttracks = true;
}
if (!_this.featuresnativetexttracks) {
_this.emulatetexttracks();
}
_this.preloadtexttracks = options.preloadtexttracks !== false;
_this.autoremotetexttracks_ = new all.text.listclass();
_this.inittracklisteners(); // turn on component tap events only if not using native controls
if (!options.nativecontrolsfortouch) {
_this.emittapevents();
}
if (_this.constructor) {
_this.name_ = _this.constructor.name || 'unknown tech';
}
return _this;
}
/**
* a special function to trigger source set in a way that will allow player
* to re-trigger if the player or tech are not ready yet.
*
* @fires tech#sourceset
* @param {string} src the source string at the time of the source changing.
*/
var _proto = tech.prototype;
_proto.triggersourceset = function triggersourceset(src) {
var _this2 = this;
if (!this.isready_) {
// on initial ready we have to trigger source set
// 1ms after ready so that player can watch for it.
this.one('ready', function () {
return _this2.settimeout(function () {
return _this2.triggersourceset(src);
}, 1);
});
}
/**
* fired when the source is set on the tech causing the media element
* to reload.
*
* @see {@link player#event:sourceset}
* @event tech#sourceset
* @type {eventtarget~event}
*/
this.trigger({
src: src,
type: 'sourceset'
});
}
/* fallbacks for unsupported event types
================================================================================ */
/**
* polyfill the `progress` event for browsers that don't support it natively.
*
* @see {@link tech#trackprogress}
*/
;
_proto.manualprogresson = function manualprogresson() {
this.on('durationchange', this.ondurationchange_);
this.manualprogress = true; // trigger progress watching when a source begins loading
this.one('ready', this.trackprogress_);
}
/**
* turn off the polyfill for `progress` events that was created in
* {@link tech#manualprogresson}
*/
;
_proto.manualprogressoff = function manualprogressoff() {
this.manualprogress = false;
this.stoptrackingprogress();
this.off('durationchange', this.ondurationchange_);
}
/**
* this is used to trigger a `progress` event when the buffered percent changes. it
* sets an interval function that will be called every 500 milliseconds to check if the
* buffer end percent has changed.
*
* > this function is called by {@link tech#manualprogresson}
*
* @param {eventtarget~event} event
* the `ready` event that caused this to run.
*
* @listens tech#ready
* @fires tech#progress
*/
;
_proto.trackprogress = function trackprogress(event) {
this.stoptrackingprogress();
this.progressinterval = this.setinterval(bind(this, function () {
// don't trigger unless buffered amount is greater than last time
var numbufferedpercent = this.bufferedpercent();
if (this.bufferedpercent_ !== numbufferedpercent) {
/**
* see {@link player#progress}
*
* @event tech#progress
* @type {eventtarget~event}
*/
this.trigger('progress');
}
this.bufferedpercent_ = numbufferedpercent;
if (numbufferedpercent === 1) {
this.stoptrackingprogress();
}
}), 500);
}
/**
* update our internal duration on a `durationchange` event by calling
* {@link tech#duration}.
*
* @param {eventtarget~event} event
* the `durationchange` event that caused this to run.
*
* @listens tech#durationchange
*/
;
_proto.ondurationchange = function ondurationchange(event) {
this.duration_ = this.duration();
}
/**
* get and create a `timerange` object for buffering.
*
* @return {timerange}
* the time range object that was created.
*/
;
_proto.buffered = function buffered() {
return createtimeranges(0, 0);
}
/**
* get the percentage of the current video that is currently buffered.
*
* @return {number}
* a number from 0 to 1 that represents the decimal percentage of the
* video that is buffered.
*
*/
;
_proto.bufferedpercent = function bufferedpercent$1() {
return bufferedpercent(this.buffered(), this.duration_);
}
/**
* turn off the polyfill for `progress` events that was created in
* {@link tech#manualprogresson}
* stop manually tracking progress events by clearing the interval that was set in
* {@link tech#trackprogress}.
*/
;
_proto.stoptrackingprogress = function stoptrackingprogress() {
this.clearinterval(this.progressinterval);
}
/**
* polyfill the `timeupdate` event for browsers that don't support it.
*
* @see {@link tech#trackcurrenttime}
*/
;
_proto.manualtimeupdateson = function manualtimeupdateson() {
this.manualtimeupdates = true;
this.on('play', this.trackcurrenttime_);
this.on('pause', this.stoptrackingcurrenttime_);
}
/**
* turn off the polyfill for `timeupdate` events that was created in
* {@link tech#manualtimeupdateson}
*/
;
_proto.manualtimeupdatesoff = function manualtimeupdatesoff() {
this.manualtimeupdates = false;
this.stoptrackingcurrenttime();
this.off('play', this.trackcurrenttime_);
this.off('pause', this.stoptrackingcurrenttime_);
}
/**
* sets up an interval function to track current time and trigger `timeupdate` every
* 250 milliseconds.
*
* @listens tech#play
* @triggers tech#timeupdate
*/
;
_proto.trackcurrenttime = function trackcurrenttime() {
if (this.currenttimeinterval) {
this.stoptrackingcurrenttime();
}
this.currenttimeinterval = this.setinterval(function () {
/**
* triggered at an interval of 250ms to indicated that time is passing in the video.
*
* @event tech#timeupdate
* @type {eventtarget~event}
*/
this.trigger({
type: 'timeupdate',
target: this,
manuallytriggered: true
}); // 42 = 24 fps // 250 is what webkit uses // ff uses 15
}, 250);
}
/**
* stop the interval function created in {@link tech#trackcurrenttime} so that the
* `timeupdate` event is no longer triggered.
*
* @listens {tech#pause}
*/
;
_proto.stoptrackingcurrenttime = function stoptrackingcurrenttime() {
this.clearinterval(this.currenttimeinterval); // #1002 - if the video ends right before the next timeupdate would happen,
// the progress bar won't make it all the way to the end
this.trigger({
type: 'timeupdate',
target: this,
manuallytriggered: true
});
}
/**
* turn off all event polyfills, clear the `tech`s {@link audiotracklist},
* {@link videotracklist}, and {@link texttracklist}, and dispose of this tech.
*
* @fires component#dispose
*/
;
_proto.dispose = function dispose() {
// clear out all tracks because we can't reuse them between techs
this.cleartracks(normal.names); // turn off any manual progress or timeupdate tracking
if (this.manualprogress) {
this.manualprogressoff();
}
if (this.manualtimeupdates) {
this.manualtimeupdatesoff();
}
_component.prototype.dispose.call(this);
}
/**
* clear out a single `tracklist` or an array of `tracklists` given their names.
*
* > note: techs without source handlers should call this between sources for `video`
* & `audio` tracks. you don't want to use them between tracks!
*
* @param {string[]|string} types
* tracklist names to clear, valid names are `video`, `audio`, and
* `text`.
*/
;
_proto.cleartracks = function cleartracks(types) {
var _this3 = this;
types = [].concat(types); // clear out all tracks because we can't reuse them between techs
types.foreach(function (type) {
var list = _this3[type + "tracks"]() || [];
var i = list.length;
while (i--) {
var track = list[i];
if (type === 'text') {
_this3.removeremotetexttrack(track);
}
list.removetrack(track);
}
});
}
/**
* remove any texttracks added via addremotetexttrack that are
* flagged for automatic garbage collection
*/
;
_proto.cleanupautotexttracks = function cleanupautotexttracks() {
var list = this.autoremotetexttracks_ || [];
var i = list.length;
while (i--) {
var track = list[i];
this.removeremotetexttrack(track);
}
}
/**
* reset the tech, which will removes all sources and reset the internal readystate.
*
* @abstract
*/
;
_proto.reset = function reset() {}
/**
* get the value of `crossorigin` from the tech.
*
* @abstract
*
* @see {html5#crossorigin}
*/
;
_proto.crossorigin = function crossorigin() {}
/**
* set the value of `crossorigin` on the tech.
*
* @abstract
*
* @param {string} crossorigin the crossorigin value
* @see {html5#setcrossorigin}
*/
;
_proto.setcrossorigin = function setcrossorigin() {}
/**
* get or set an error on the tech.
*
* @param {mediaerror} [err]
* error to set on the tech
*
* @return {mediaerror|null}
* the current error object on the tech, or null if there isn't one.
*/
;
_proto.error = function error(err) {
if (err !== undefined) {
this.error_ = new mediaerror(err);
this.trigger('error');
}
return this.error_;
}
/**
* returns the `timerange`s that have been played through for the current source.
*
* > note: this implementation is incomplete. it does not track the played `timerange`.
* it only checks whether the source has played at all or not.
*
* @return {timerange}
* - a single time range if this video has played
* - an empty set of ranges if not.
*/
;
_proto.played = function played() {
if (this.hasstarted_) {
return createtimeranges(0, 0);
}
return createtimeranges();
}
/**
* start playback
*
* @abstract
*
* @see {html5#play}
*/
;
_proto.play = function play() {}
/**
* set whether we are scrubbing or not
*
* @abstract
*
* @see {html5#setscrubbing}
*/
;
_proto.setscrubbing = function setscrubbing() {}
/**
* get whether we are scrubbing or not
*
* @abstract
*
* @see {html5#scrubbing}
*/
;
_proto.scrubbing = function scrubbing() {}
/**
* causes a manual time update to occur if {@link tech#manualtimeupdateson} was
* previously called.
*
* @fires tech#timeupdate
*/
;
_proto.setcurrenttime = function setcurrenttime() {
// improve the accuracy of manual timeupdates
if (this.manualtimeupdates) {
/**
* a manual `timeupdate` event.
*
* @event tech#timeupdate
* @type {eventtarget~event}
*/
this.trigger({
type: 'timeupdate',
target: this,
manuallytriggered: true
});
}
}
/**
* turn on listeners for {@link videotracklist}, {@link {audiotracklist}, and
* {@link texttracklist} events.
*
* this adds {@link eventtarget~eventlisteners} for `addtrack`, and `removetrack`.
*
* @fires tech#audiotrackchange
* @fires tech#videotrackchange
* @fires tech#texttrackchange
*/
;
_proto.inittracklisteners = function inittracklisteners() {
var _this4 = this;
/**
* triggered when tracks are added or removed on the tech {@link audiotracklist}
*
* @event tech#audiotrackchange
* @type {eventtarget~event}
*/
/**
* triggered when tracks are added or removed on the tech {@link videotracklist}
*
* @event tech#videotrackchange
* @type {eventtarget~event}
*/
/**
* triggered when tracks are added or removed on the tech {@link texttracklist}
*
* @event tech#texttrackchange
* @type {eventtarget~event}
*/
normal.names.foreach(function (name) {
var props = normal[name];
var tracklistchanges = function tracklistchanges() {
_this4.trigger(name + "trackchange");
};
var tracks = _this4[props.gettername]();
tracks.addeventlistener('removetrack', tracklistchanges);
tracks.addeventlistener('addtrack', tracklistchanges);
_this4.on('dispose', function () {
tracks.removeeventlistener('removetrack', tracklistchanges);
tracks.removeeventlistener('addtrack', tracklistchanges);
});
});
}
/**
* emulate texttracks using vtt.js if necessary
*
* @fires tech#vttjsloaded
* @fires tech#vttjserror
*/
;
_proto.addwebvttscript_ = function addwebvttscript_() {
var _this5 = this;
if (global_window__webpack_imported_module_0___default.a.webvtt) {
return;
} // initially, tech.el_ is a child of a dummy-div wait until the component system
// signals that the tech is ready at which point tech.el_ is part of the dom
// before inserting the webvtt script
if (global_document__webpack_imported_module_1___default.a.body.contains(this.el())) {
// load via require if available and vtt.js script location was not passed in
// as an option. novtt builds will turn the above require call into an empty object
// which will cause this if check to always fail.
if (!this.options_['vtt.js'] && isplain(videojs_vtt_js__webpack_imported_module_8___default.a) && object.keys(videojs_vtt_js__webpack_imported_module_8___default.a).length > 0) {
this.trigger('vttjsloaded');
return;
} // load vtt.js via the script location option or the cdn of no location was
// passed in
var script = global_document__webpack_imported_module_1___default.a.createelement('script');
script.src = this.options_['vtt.js'] || 'https://vjs.zencdn.net/vttjs/0.14.1/vtt.min.js';
script.onload = function () {
/**
* fired when vtt.js is loaded.
*
* @event tech#vttjsloaded
* @type {eventtarget~event}
*/
_this5.trigger('vttjsloaded');
};
script.onerror = function () {
/**
* fired when vtt.js was not loaded due to an error
*
* @event tech#vttjsloaded
* @type {eventtarget~event}
*/
_this5.trigger('vttjserror');
};
this.on('dispose', function () {
script.onload = null;
script.onerror = null;
}); // but have not loaded yet and we set it to true before the inject so that
// we don't overwrite the injected window.webvtt if it loads right away
global_window__webpack_imported_module_0___default.a.webvtt = true;
this.el().parentnode.appendchild(script);
} else {
this.ready(this.addwebvttscript_);
}
}
/**
* emulate texttracks
*
*/
;
_proto.emulatetexttracks = function emulatetexttracks() {
var _this6 = this;
var tracks = this.texttracks();
var remotetracks = this.remotetexttracks();
var handleaddtrack = function handleaddtrack(e) {
return tracks.addtrack(e.track);
};
var handleremovetrack = function handleremovetrack(e) {
return tracks.removetrack(e.track);
};
remotetracks.on('addtrack', handleaddtrack);
remotetracks.on('removetrack', handleremovetrack);
this.addwebvttscript_();
var updatedisplay = function updatedisplay() {
return _this6.trigger('texttrackchange');
};
var texttrackschanges = function texttrackschanges() {
updatedisplay();
for (var i = 0; i < tracks.length; i++) {
var track = tracks[i];
track.removeeventlistener('cuechange', updatedisplay);
if (track.mode === 'showing') {
track.addeventlistener('cuechange', updatedisplay);
}
}
};
texttrackschanges();
tracks.addeventlistener('change', texttrackschanges);
tracks.addeventlistener('addtrack', texttrackschanges);
tracks.addeventlistener('removetrack', texttrackschanges);
this.on('dispose', function () {
remotetracks.off('addtrack', handleaddtrack);
remotetracks.off('removetrack', handleremovetrack);
tracks.removeeventlistener('change', texttrackschanges);
tracks.removeeventlistener('addtrack', texttrackschanges);
tracks.removeeventlistener('removetrack', texttrackschanges);
for (var i = 0; i < tracks.length; i++) {
var track = tracks[i];
track.removeeventlistener('cuechange', updatedisplay);
}
});
}
/**
* create and returns a remote {@link texttrack} object.
*
* @param {string} kind
* `texttrack` kind (subtitles, captions, descriptions, chapters, or metadata)
*
* @param {string} [label]
* label to identify the text track
*
* @param {string} [language]
* two letter language abbreviation
*
* @return {texttrack}
* the texttrack that gets created.
*/
;
_proto.addtexttrack = function addtexttrack(kind, label, language) {
if (!kind) {
throw new error('texttrack kind is required but was not provided');
}
return createtrackhelper(this, kind, label, language);
}
/**
* create an emulated texttrack for use by addremotetexttrack
*
* this is intended to be overridden by classes that inherit from
* tech in order to create native or custom texttracks.
*
* @param {object} options
* the object should contain the options to initialize the texttrack with.
*
* @param {string} [options.kind]
* `texttrack` kind (subtitles, captions, descriptions, chapters, or metadata).
*
* @param {string} [options.label].
* label to identify the text track
*
* @param {string} [options.language]
* two letter language abbreviation.
*
* @return {htmltrackelement}
* the track element that gets created.
*/
;
_proto.createremotetexttrack = function createremotetexttrack(options) {
var track = mergeoptions$3(options, {
tech: this
});
return new remote.remotetextel.trackclass(track);
}
/**
* creates a remote text track object and returns an html track element.
*
* > note: this can be an emulated {@link htmltrackelement} or a native one.
*
* @param {object} options
* see {@link tech#createremotetexttrack} for more detailed properties.
*
* @param {boolean} [manualcleanup=true]
* - when false: the texttrack will be automatically removed from the video
* element whenever the source changes
* - when true: the texttrack will have to be cleaned up manually
*
* @return {htmltrackelement}
* an html track element.
*
* @deprecated the default functionality for this function will be equivalent
* to "manualcleanup=false" in the future. the manualcleanup parameter will
* also be removed.
*/
;
_proto.addremotetexttrack = function addremotetexttrack(options, manualcleanup) {
var _this7 = this;
if (options === void 0) {
options = {};
}
var htmltrackelement = this.createremotetexttrack(options);
if (manualcleanup !== true && manualcleanup !== false) {
// deprecation warning
log$1.warn('calling addremotetexttrack without explicitly setting the "manualcleanup" parameter to `true` is deprecated and default to `false` in future version of video.js');
manualcleanup = true;
} // store htmltrackelement and texttrack to remote list
this.remotetexttrackels().addtrackelement_(htmltrackelement);
this.remotetexttracks().addtrack(htmltrackelement.track);
if (manualcleanup !== true) {
// create the texttracklist if it doesn't exist
this.ready(function () {
return _this7.autoremotetexttracks_.addtrack(htmltrackelement.track);
});
}
return htmltrackelement;
}
/**
* remove a remote text track from the remote `texttracklist`.
*
* @param {texttrack} track
* `texttrack` to remove from the `texttracklist`
*/
;
_proto.removeremotetexttrack = function removeremotetexttrack(track) {
var trackelement = this.remotetexttrackels().gettrackelementbytrack_(track); // remove htmltrackelement and texttrack from remote list
this.remotetexttrackels().removetrackelement_(trackelement);
this.remotetexttracks().removetrack(track);
this.autoremotetexttracks_.removetrack(track);
}
/**
* gets available media playback quality metrics as specified by the w3c's media
* playback quality api.
*
* @see [spec]{@link https://wicg.github.io/media-playback-quality}
*
* @return {object}
* an object with supported media playback quality metrics
*
* @abstract
*/
;
_proto.getvideoplaybackquality = function getvideoplaybackquality() {
return {};
}
/**
* attempt to create a floating video window always on top of other windows
* so that users may continue consuming media while they interact with other
* content sites, or applications on their device.
*
* @see [spec]{@link https://wicg.github.io/picture-in-picture}
*
* @return {promise|undefined}
* a promise with a picture-in-picture window if the browser supports
* promises (or one was passed in as an option). it returns undefined
* otherwise.
*
* @abstract
*/
;
_proto.requestpictureinpicture = function requestpictureinpicture() {
var promiseclass = this.options_.promise || global_window__webpack_imported_module_0___default.a.promise;
if (promiseclass) {
return promiseclass.reject();
}
}
/**
* a method to check for the value of the 'disablepictureinpicture' property.
* defaults to true, as it should be considered disabled if the tech does not support pip
*
* @abstract
*/
;
_proto.disablepictureinpicture = function disablepictureinpicture() {
return true;
}
/**
* a method to set or unset the 'disablepictureinpicture' property.
*
* @abstract
*/
;
_proto.setdisablepictureinpicture = function setdisablepictureinpicture() {}
/**
* a fallback implementation of requestvideoframecallback using requestanimationframe
*
* @param {function} cb
* @return {number} request id
*/
;
_proto.requestvideoframecallback = function requestvideoframecallback(cb) {
var _this8 = this;
var id = newguid();
if (!this.isready_ || this.paused()) {
this.queuedhanders_.add(id);
this.one('playing', function () {
if (_this8.queuedhanders_.has(id)) {
_this8.queuedhanders_["delete"](id);
cb();
}
});
} else {
this.requestnamedanimationframe(id, cb);
}
return id;
}
/**
* a fallback implementation of cancelvideoframecallback
*
* @param {number} id id of callback to be cancelled
*/
;
_proto.cancelvideoframecallback = function cancelvideoframecallback(id) {
if (this.queuedhanders_.has(id)) {
this.queuedhanders_["delete"](id);
} else {
this.cancelnamedanimationframe(id);
}
}
/**
* a method to set a poster from a `tech`.
*
* @abstract
*/
;
_proto.setposter = function setposter() {}
/**
* a method to check for the presence of the 'playsinline' attribute.
*
* @abstract
*/
;
_proto.playsinline = function playsinline() {}
/**
* a method to set or unset the 'playsinline' attribute.
*
* @abstract
*/
;
_proto.setplaysinline = function setplaysinline() {}
/**
* attempt to force override of native audio tracks.
*
* @param {boolean} override - if set to true native audio will be overridden,
* otherwise native audio will potentially be used.
*
* @abstract
*/
;
_proto.overridenativeaudiotracks = function overridenativeaudiotracks() {}
/**
* attempt to force override of native video tracks.
*
* @param {boolean} override - if set to true native video will be overridden,
* otherwise native video will potentially be used.
*
* @abstract
*/
;
_proto.overridenativevideotracks = function overridenativevideotracks() {}
/*
* check if the tech can support the given mime-type.
*
* the base tech does not support any type, but source handlers might
* overwrite this.
*
* @param {string} type
* the mimetype to check for support
*
* @return {string}
* 'probably', 'maybe', or empty string
*
* @see [spec]{@link https://developer.mozilla.org/en-us/docs/web/api/htmlmediaelement/canplaytype}
*
* @abstract
*/
;
_proto.canplaytype = function canplaytype() {
return '';
}
/**
* check if the type is supported by this tech.
*
* the base tech does not support any type, but source handlers might
* overwrite this.
*
* @param {string} type
* the media type to check
* @return {string} returns the native video element's response
*/
;
tech.canplaytype = function canplaytype() {
return '';
}
/**
* check if the tech can support the given source
*
* @param {object} srcobj
* the source object
* @param {object} options
* the options passed to the tech
* @return {string} 'probably', 'maybe', or '' (empty string)
*/
;
tech.canplaysource = function canplaysource(srcobj, options) {
return tech.canplaytype(srcobj.type);
}
/*
* return whether the argument is a tech or not.
* can be passed either a class like `html5` or a instance like `player.tech_`
*
* @param {object} component
* the item to check
*
* @return {boolean}
* whether it is a tech or not
* - true if it is a tech
* - false if it is not
*/
;
tech.istech = function istech(component) {
return component.prototype instanceof tech || component instanceof tech || component === tech;
}
/**
* registers a `tech` into a shared list for videojs.
*
* @param {string} name
* name of the `tech` to register.
*
* @param {object} tech
* the `tech` class to register.
*/
;
tech.registertech = function registertech(name, tech) {
if (!tech.techs_) {
tech.techs_ = {};
}
if (!tech.istech(tech)) {
throw new error("tech " + name + " must be a tech");
}
if (!tech.canplaytype) {
throw new error('techs must have a static canplaytype method on them');
}
if (!tech.canplaysource) {
throw new error('techs must have a static canplaysource method on them');
}
name = totitlecase$1(name);
tech.techs_[name] = tech;
tech.techs_[tolowercase(name)] = tech;
if (name !== 'tech') {
// camel case the techname for use in techorder
tech.defaulttechorder_.push(name);
}
return tech;
}
/**
* get a `tech` from the shared list by name.
*
* @param {string} name
* `camelcase` or `titlecase` name of the tech to get
*
* @return {tech|undefined}
* the `tech` or undefined if there was no tech with the name requested.
*/
;
tech.gettech = function gettech(name) {
if (!name) {
return;
}
if (tech.techs_ && tech.techs_[name]) {
return tech.techs_[name];
}
name = totitlecase$1(name);
if (global_window__webpack_imported_module_0___default.a && global_window__webpack_imported_module_0___default.a.videojs && global_window__webpack_imported_module_0___default.a.videojs[name]) {
log$1.warn("the " + name + " tech was added to the videojs object when it should be registered using videojs.registertech(name, tech)");
return global_window__webpack_imported_module_0___default.a.videojs[name];
}
};
return tech;
}(component$1);
/**
* get the {@link videotracklist}
*
* @returns {videotracklist}
* @method tech.prototype.videotracks
*/
/**
* get the {@link audiotracklist}
*
* @returns {audiotracklist}
* @method tech.prototype.audiotracks
*/
/**
* get the {@link texttracklist}
*
* @returns {texttracklist}
* @method tech.prototype.texttracks
*/
/**
* get the remote element {@link texttracklist}
*
* @returns {texttracklist}
* @method tech.prototype.remotetexttracks
*/
/**
* get the remote element {@link htmltrackelementlist}
*
* @returns {htmltrackelementlist}
* @method tech.prototype.remotetexttrackels
*/
all.names.foreach(function (name) {
var props = all[name];
tech.prototype[props.gettername] = function () {
this[props.privatename] = this[props.privatename] || new props.listclass();
return this[props.privatename];
};
});
/**
* list of associated text tracks
*
* @type {texttracklist}
* @private
* @property tech#texttracks_
*/
/**
* list of associated audio tracks.
*
* @type {audiotracklist}
* @private
* @property tech#audiotracks_
*/
/**
* list of associated video tracks.
*
* @type {videotracklist}
* @private
* @property tech#videotracks_
*/
/**
* boolean indicating whether the `tech` supports volume control.
*
* @type {boolean}
* @default
*/
tech.prototype.featuresvolumecontrol = true;
/**
* boolean indicating whether the `tech` supports muting volume.
*
* @type {bolean}
* @default
*/
tech.prototype.featuresmutecontrol = true;
/**
* boolean indicating whether the `tech` supports fullscreen resize control.
* resizing plugins using request fullscreen reloads the plugin
*
* @type {boolean}
* @default
*/
tech.prototype.featuresfullscreenresize = false;
/**
* boolean indicating whether the `tech` supports changing the speed at which the video
* plays. examples:
* - set player to play 2x (twice) as fast
* - set player to play 0.5x (half) as fast
*
* @type {boolean}
* @default
*/
tech.prototype.featuresplaybackrate = false;
/**
* boolean indicating whether the `tech` supports the `progress` event. this is currently
* not triggered by video-js-swf. this will be used to determine if
* {@link tech#manualprogresson} should be called.
*
* @type {boolean}
* @default
*/
tech.prototype.featuresprogressevents = false;
/**
* boolean indicating whether the `tech` supports the `sourceset` event.
*
* a tech should set this to `true` and then use {@link tech#triggersourceset}
* to trigger a {@link tech#event:sourceset} at the earliest time after getting
* a new source.
*
* @type {boolean}
* @default
*/
tech.prototype.featuressourceset = false;
/**
* boolean indicating whether the `tech` supports the `timeupdate` event. this is currently
* not triggered by video-js-swf. this will be used to determine if
* {@link tech#manualtimeupdates} should be called.
*
* @type {boolean}
* @default
*/
tech.prototype.featurestimeupdateevents = false;
/**
* boolean indicating whether the `tech` supports the native `texttrack`s.
* this will help us integrate with native `texttrack`s if the browser supports them.
*
* @type {boolean}
* @default
*/
tech.prototype.featuresnativetexttracks = false;
/**
* boolean indicating whether the `tech` supports `requestvideoframecallback`.
*
* @type {boolean}
* @default
*/
tech.prototype.featuresvideoframecallback = false;
/**
* a functional mixin for techs that want to use the source handler pattern.
* source handlers are scripts for handling specific formats.
* the source handler pattern is used for adaptive formats (hls, dash) that
* manually load video data and feed it into a source buffer (media source extensions)
* example: `tech.withsourcehandlers.call(mytech);`
*
* @param {tech} _tech
* the tech to add source handler functions to.
*
* @mixes tech~sourcehandleradditions
*/
tech.withsourcehandlers = function (_tech) {
/**
* register a source handler
*
* @param {function} handler
* the source handler class
*
* @param {number} [index]
* register it at the following index
*/
_tech.registersourcehandler = function (handler, index) {
var handlers = _tech.sourcehandlers;
if (!handlers) {
handlers = _tech.sourcehandlers = [];
}
if (index === undefined) {
// add to the end of the list
index = handlers.length;
}
handlers.splice(index, 0, handler);
};
/**
* check if the tech can support the given type. also checks the
* techs sourcehandlers.
*
* @param {string} type
* the mimetype to check.
*
* @return {string}
* 'probably', 'maybe', or '' (empty string)
*/
_tech.canplaytype = function (type) {
var handlers = _tech.sourcehandlers || [];
var can;
for (var i = 0; i < handlers.length; i++) {
can = handlers[i].canplaytype(type);
if (can) {
return can;
}
}
return '';
};
/**
* returns the first source handler that supports the source.
*
* todo: answer question: should 'probably' be prioritized over 'maybe'
*
* @param {tech~sourceobject} source
* the source object
*
* @param {object} options
* the options passed to the tech
*
* @return {sourcehandler|null}
* the first source handler that supports the source or null if
* no sourcehandler supports the source
*/
_tech.selectsourcehandler = function (source, options) {
var handlers = _tech.sourcehandlers || [];
var can;
for (var i = 0; i < handlers.length; i++) {
can = handlers[i].canhandlesource(source, options);
if (can) {
return handlers[i];
}
}
return null;
};
/**
* check if the tech can support the given source.
*
* @param {tech~sourceobject} srcobj
* the source object
*
* @param {object} options
* the options passed to the tech
*
* @return {string}
* 'probably', 'maybe', or '' (empty string)
*/
_tech.canplaysource = function (srcobj, options) {
var sh = _tech.selectsourcehandler(srcobj, options);
if (sh) {
return sh.canhandlesource(srcobj, options);
}
return '';
};
/**
* when using a source handler, prefer its implementation of
* any function normally provided by the tech.
*/
var deferrable = ['seekable', 'seeking', 'duration'];
/**
* a wrapper around {@link tech#seekable} that will call a `sourcehandler`s seekable
* function if it exists, with a fallback to the techs seekable function.
*
* @method _tech.seekable
*/
/**
* a wrapper around {@link tech#duration} that will call a `sourcehandler`s duration
* function if it exists, otherwise it will fallback to the techs duration function.
*
* @method _tech.duration
*/
deferrable.foreach(function (fnname) {
var originalfn = this[fnname];
if (typeof originalfn !== 'function') {
return;
}
this[fnname] = function () {
if (this.sourcehandler_ && this.sourcehandler_[fnname]) {
return this.sourcehandler_[fnname].apply(this.sourcehandler_, arguments);
}
return originalfn.apply(this, arguments);
};
}, _tech.prototype);
/**
* create a function for setting the source using a source object
* and source handlers.
* should never be called unless a source handler was found.
*
* @param {tech~sourceobject} source
* a source object with src and type keys
*/
_tech.prototype.setsource = function (source) {
var sh = _tech.selectsourcehandler(source, this.options_);
if (!sh) {
// fall back to a native source hander when unsupported sources are
// deliberately set
if (_tech.nativesourcehandler) {
sh = _tech.nativesourcehandler;
} else {
log$1.error('no source handler found for the current source.');
}
} // dispose any existing source handler
this.disposesourcehandler();
this.off('dispose', this.disposesourcehandler_);
if (sh !== _tech.nativesourcehandler) {
this.currentsource_ = source;
}
this.sourcehandler_ = sh.handlesource(source, this, this.options_);
this.one('dispose', this.disposesourcehandler_);
};
/**
* clean up any existing sourcehandlers and listeners when the tech is disposed.
*
* @listens tech#dispose
*/
_tech.prototype.disposesourcehandler = function () {
// if we have a source and get another one
// then we are loading something new
// than clear all of our current tracks
if (this.currentsource_) {
this.cleartracks(['audio', 'video']);
this.currentsource_ = null;
} // always clean up auto-text tracks
this.cleanupautotexttracks();
if (this.sourcehandler_) {
if (this.sourcehandler_.dispose) {
this.sourcehandler_.dispose();
}
this.sourcehandler_ = null;
}
};
}; // the base tech class needs to be registered as a component. it is the only
// tech that can be registered as a component.
component$1.registercomponent('tech', tech);
tech.registertech('tech', tech);
/**
* a list of techs that should be added to techorder on players
*
* @private
*/
tech.defaulttechorder_ = [];
/**
* @file middleware.js
* @module middleware
*/
var middlewares = {};
var middlewareinstances = {};
var terminator = {};
/**
* a middleware object is a plain javascript object that has methods that
* match the {@link tech} methods found in the lists of allowed
* {@link module:middleware.allowedgetters|getters},
* {@link module:middleware.allowedsetters|setters}, and
* {@link module:middleware.allowedmediators|mediators}.
*
* @typedef {object} middlewareobject
*/
/**
* a middleware factory function that should return a
* {@link module:middleware~middlewareobject|middlewareobject}.
*
* this factory will be called for each player when needed, with the player
* passed in as an argument.
*
* @callback middlewarefactory
* @param {player} player
* a video.js player.
*/
/**
* define a middleware that the player should use by way of a factory function
* that returns a middleware object.
*
* @param {string} type
* the mime type to match or `"*"` for all mime types.
*
* @param {middlewarefactory} middleware
* a middleware factory function that will be executed for
* matching types.
*/
function use(type, middleware) {
middlewares[type] = middlewares[type] || [];
middlewares[type].push(middleware);
}
/**
* asynchronously sets a source using middleware by recursing through any
* matching middlewares and calling `setsource` on each, passing along the
* previous returned value each time.
*
* @param {player} player
* a {@link player} instance.
*
* @param {tech~sourceobject} src
* a source object.
*
* @param {function}
* the next middleware to run.
*/
function setsource(player, src, next) {
player.settimeout(function () {
return setsourcehelper(src, middlewares[src.type], next, player);
}, 1);
}
/**
* when the tech is set, passes the tech to each middleware's `settech` method.
*
* @param {object[]} middleware
* an array of middleware instances.
*
* @param {tech} tech
* a video.js tech.
*/
function settech(middleware, tech) {
middleware.foreach(function (mw) {
return mw.settech && mw.settech(tech);
});
}
/**
* calls a getter on the tech first, through each middleware
* from right to left to the player.
*
* @param {object[]} middleware
* an array of middleware instances.
*
* @param {tech} tech
* the current tech.
*
* @param {string} method
* a method name.
*
* @return {mixed}
* the final value from the tech after middleware has intercepted it.
*/
function get(middleware, tech, method) {
return middleware.reduceright(middlewareiterator(method), tech[method]());
}
/**
* takes the argument given to the player and calls the setter method on each
* middleware from left to right to the tech.
*
* @param {object[]} middleware
* an array of middleware instances.
*
* @param {tech} tech
* the current tech.
*
* @param {string} method
* a method name.
*
* @param {mixed} arg
* the value to set on the tech.
*
* @return {mixed}
* the return value of the `method` of the `tech`.
*/
function set(middleware, tech, method, arg) {
return tech[method](middleware.reduce(middlewareiterator(method), arg));
}
/**
* takes the argument given to the player and calls the `call` version of the
* method on each middleware from left to right.
*
* then, call the passed in method on the tech and return the result unchanged
* back to the player, through middleware, this time from right to left.
*
* @param {object[]} middleware
* an array of middleware instances.
*
* @param {tech} tech
* the current tech.
*
* @param {string} method
* a method name.
*
* @param {mixed} arg
* the value to set on the tech.
*
* @return {mixed}
* the return value of the `method` of the `tech`, regardless of the
* return values of middlewares.
*/
function mediate(middleware, tech, method, arg) {
if (arg === void 0) {
arg = null;
}
var callmethod = 'call' + totitlecase$1(method);
var middlewarevalue = middleware.reduce(middlewareiterator(callmethod), arg);
var terminated = middlewarevalue === terminator; // deprecated. the `null` return value should instead return terminator to
// prevent confusion if a techs method actually returns null.
var returnvalue = terminated ? null : tech[method](middlewarevalue);
executeright(middleware, method, returnvalue, terminated);
return returnvalue;
}
/**
* enumeration of allowed getters where the keys are method names.
*
* @type {object}
*/
var allowedgetters = {
buffered: 1,
currenttime: 1,
duration: 1,
muted: 1,
played: 1,
paused: 1,
seekable: 1,
volume: 1,
ended: 1
};
/**
* enumeration of allowed setters where the keys are method names.
*
* @type {object}
*/
var allowedsetters = {
setcurrenttime: 1,
setmuted: 1,
setvolume: 1
};
/**
* enumeration of allowed mediators where the keys are method names.
*
* @type {object}
*/
var allowedmediators = {
play: 1,
pause: 1
};
function middlewareiterator(method) {
return function (value, mw) {
// if the previous middleware terminated, pass along the termination
if (value === terminator) {
return terminator;
}
if (mw[method]) {
return mw[method](value);
}
return value;
};
}
function executeright(mws, method, value, terminated) {
for (var i = mws.length - 1; i >= 0; i--) {
var mw = mws[i];
if (mw[method]) {
mw[method](terminated, value);
}
}
}
/**
* clear the middleware cache for a player.
*
* @param {player} player
* a {@link player} instance.
*/
function clearcacheforplayer(player) {
middlewareinstances[player.id()] = null;
}
/**
* {
* [playerid]: [[mwfactory, mwinstance], ...]
* }
*
* @private
*/
function getorcreatefactory(player, mwfactory) {
var mws = middlewareinstances[player.id()];
var mw = null;
if (mws === undefined || mws === null) {
mw = mwfactory(player);
middlewareinstances[player.id()] = [[mwfactory, mw]];
return mw;
}
for (var i = 0; i < mws.length; i++) {
var _mws$i = mws[i],
mwf = _mws$i[0],
mwi = _mws$i[1];
if (mwf !== mwfactory) {
continue;
}
mw = mwi;
}
if (mw === null) {
mw = mwfactory(player);
mws.push([mwfactory, mw]);
}
return mw;
}
function setsourcehelper(src, middleware, next, player, acc, lastrun) {
if (src === void 0) {
src = {};
}
if (middleware === void 0) {
middleware = [];
}
if (acc === void 0) {
acc = [];
}
if (lastrun === void 0) {
lastrun = false;
}
var _middleware = middleware,
mwfactory = _middleware[0],
mwrest = _middleware.slice(1); // if mwfactory is a string, then we're at a fork in the road
if (typeof mwfactory === 'string') {
setsourcehelper(src, middlewares[mwfactory], next, player, acc, lastrun); // if we have an mwfactory, call it with the player to get the mw,
// then call the mw's setsource method
} else if (mwfactory) {
var mw = getorcreatefactory(player, mwfactory); // if setsource isn't present, implicitly select this middleware
if (!mw.setsource) {
acc.push(mw);
return setsourcehelper(src, mwrest, next, player, acc, lastrun);
}
mw.setsource(assign({}, src), function (err, _src) {
// something happened, try the next middleware on the current level
// make sure to use the old src
if (err) {
return setsourcehelper(src, mwrest, next, player, acc, lastrun);
} // we've succeeded, now we need to go deeper
acc.push(mw); // if it's the same type, continue down the current chain
// otherwise, we want to go down the new chain
setsourcehelper(_src, src.type === _src.type ? mwrest : middlewares[_src.type], next, player, acc, lastrun);
});
} else if (mwrest.length) {
setsourcehelper(src, mwrest, next, player, acc, lastrun);
} else if (lastrun) {
next(src, acc);
} else {
setsourcehelper(src, middlewares['*'], next, player, acc, true);
}
}
/**
* mimetypes
*
* @see https://www.iana.org/assignments/media-types/media-types.xhtml
* @typedef mimetypes~kind
* @enum
*/
var mimetypeskind = {
opus: 'video/ogg',
ogv: 'video/ogg',
mp4: 'video/mp4',
mov: 'video/mp4',
m4v: 'video/mp4',
mkv: 'video/x-matroska',
m4a: 'audio/mp4',
mp3: 'audio/mpeg',
aac: 'audio/aac',
caf: 'audio/x-caf',
flac: 'audio/flac',
oga: 'audio/ogg',
wav: 'audio/wav',
m3u8: 'application/x-mpegurl',
mpd: 'application/dash+xml',
jpg: 'image/jpeg',
jpeg: 'image/jpeg',
gif: 'image/gif',
png: 'image/png',
svg: 'image/svg+xml',
webp: 'image/webp'
};
/**
* get the mimetype of a given src url if possible
*
* @param {string} src
* the url to the src
*
* @return {string}
* return the mimetype if it was known or empty string otherwise
*/
var getmimetype = function getmimetype(src) {
if (src === void 0) {
src = '';
}
var ext = getfileextension(src);
var mimetype = mimetypeskind[ext.tolowercase()];
return mimetype || '';
};
/**
* find the mime type of a given source string if possible. uses the player
* source cache.
*
* @param {player} player
* the player object
*
* @param {string} src
* the source string
*
* @return {string}
* the type that was found
*/
var findmimetype = function findmimetype(player, src) {
if (!src) {
return '';
} // 1. check for the type in the `source` cache
if (player.cache_.source.src === src && player.cache_.source.type) {
return player.cache_.source.type;
} // 2. see if we have this source in our `currentsources` cache
var matchingsources = player.cache_.sources.filter(function (s) {
return s.src === src;
});
if (matchingsources.length) {
return matchingsources[0].type;
} // 3. look for the src url in source elements and use the type there
var sources = player.$$('source');
for (var i = 0; i < sources.length; i++) {
var s = sources[i];
if (s.type && s.src && s.src === src) {
return s.type;
}
} // 4. finally fallback to our list of mime types based on src url extension
return getmimetype(src);
};
/**
* @module filter-source
*/
/**
* filter out single bad source objects or multiple source objects in an
* array. also flattens nested source object arrays into a 1 dimensional
* array of source objects.
*
* @param {tech~sourceobject|tech~sourceobject[]} src
* the src object to filter
*
* @return {tech~sourceobject[]}
* an array of sourceobjects containing only valid sources
*
* @private
*/
var filtersource = function filtersource(src) {
// traverse array
if (array.isarray(src)) {
var newsrc = [];
src.foreach(function (srcobj) {
srcobj = filtersource(srcobj);
if (array.isarray(srcobj)) {
newsrc = newsrc.concat(srcobj);
} else if (isobject(srcobj)) {
newsrc.push(srcobj);
}
});
src = newsrc;
} else if (typeof src === 'string' && src.trim()) {
// convert string into object
src = [fixsource({
src: src
})];
} else if (isobject(src) && typeof src.src === 'string' && src.src && src.src.trim()) {
// src is already valid
src = [fixsource(src)];
} else {
// invalid source, turn it into an empty array
src = [];
}
return src;
};
/**
* checks src mimetype, adding it when possible
*
* @param {tech~sourceobject} src
* the src object to check
* @return {tech~sourceobject}
* src object with known type
*/
function fixsource(src) {
if (!src.type) {
var mimetype = getmimetype(src.src);
if (mimetype) {
src.type = mimetype;
}
}
return src;
}
/**
* the `medialoader` is the `component` that decides which playback technology to load
* when a player is initialized.
*
* @extends component
*/
var medialoader = /*#__pure__*/function (_component) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(medialoader, _component);
/**
* create an instance of this class.
*
* @param {player} player
* the `player` that this class should attach to.
*
* @param {object} [options]
* the key/value store of player options.
*
* @param {component~readycallback} [ready]
* the function that is run when this component is ready.
*/
function medialoader(player, options, ready) {
var _this;
// medialoader has no element
var options_ = mergeoptions$3({
createel: false
}, options);
_this = _component.call(this, player, options_, ready) || this; // if there are no sources when the player is initialized,
// load the first supported playback technology.
if (!options.playeroptions.sources || options.playeroptions.sources.length === 0) {
for (var i = 0, j = options.playeroptions.techorder; i < j.length; i++) {
var techname = totitlecase$1(j[i]);
var tech = tech.gettech(techname); // support old behavior of techs being registered as components.
// remove once that deprecated behavior is removed.
if (!techname) {
tech = component$1.getcomponent(techname);
} // check if the browser supports this technology
if (tech && tech.issupported()) {
player.loadtech_(techname);
break;
}
}
} else {
// loop through playback technologies (e.g. html5) and check for support.
// then load the best source.
// a few assumptions here:
// all playback technologies respect preload false.
player.src(options.playeroptions.sources);
}
return _this;
}
return medialoader;
}(component$1);
component$1.registercomponent('medialoader', medialoader);
/**
* component which is clickable or keyboard actionable, but is not a
* native html button.
*
* @extends component
*/
var clickablecomponent = /*#__pure__*/function (_component) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(clickablecomponent, _component);
/**
* creates an instance of this class.
*
* @param {player} player
* the `player` that this class should be attached to.
*
* @param {object} [options]
* the key/value store of component options.
*
* @param {function} [options.clickhandler]
* the function to call when the button is clicked / activated
*
* @param {string} [options.controltext]
* the text to set on the button
*
* @param {string} [options.classname]
* a class or space separated list of classes to add the component
*
*/
function clickablecomponent(player, options) {
var _this;
_this = _component.call(this, player, options) || this;
if (_this.options_.controltext) {
_this.controltext(_this.options_.controltext);
}
_this.handlemouseover_ = function (e) {
return _this.handlemouseover(e);
};
_this.handlemouseout_ = function (e) {
return _this.handlemouseout(e);
};
_this.handleclick_ = function (e) {
return _this.handleclick(e);
};
_this.handlekeydown_ = function (e) {
return _this.handlekeydown(e);
};
_this.emittapevents();
_this.enable();
return _this;
}
/**
* create the `clickablecomponent`s dom element.
*
* @param {string} [tag=div]
* the element's node type.
*
* @param {object} [props={}]
* an object of properties that should be set on the element.
*
* @param {object} [attributes={}]
* an object of attributes that should be set on the element.
*
* @return {element}
* the element that gets created.
*/
var _proto = clickablecomponent.prototype;
_proto.createel = function createel$1(tag, props, attributes) {
if (tag === void 0) {
tag = 'div';
}
if (props === void 0) {
props = {};
}
if (attributes === void 0) {
attributes = {};
}
props = assign({
classname: this.buildcssclass(),
tabindex: 0
}, props);
if (tag === 'button') {
log$1.error("creating a clickablecomponent with an html element of " + tag + " is not supported; use a button instead.");
} // add aria attributes for clickable element which is not a native html button
attributes = assign({
role: 'button'
}, attributes);
this.tabindex_ = props.tabindex;
var el = createel(tag, props, attributes);
el.appendchild(createel('span', {
classname: 'vjs-icon-placeholder'
}, {
'aria-hidden': true
}));
this.createcontroltextel(el);
return el;
};
_proto.dispose = function dispose() {
// remove controltextel_ on dispose
this.controltextel_ = null;
_component.prototype.dispose.call(this);
}
/**
* create a control text element on this `clickablecomponent`
*
* @param {element} [el]
* parent element for the control text.
*
* @return {element}
* the control text element that gets created.
*/
;
_proto.createcontroltextel = function createcontroltextel(el) {
this.controltextel_ = createel('span', {
classname: 'vjs-control-text'
}, {
// let the screen reader user know that the text of the element may change
'aria-live': 'polite'
});
if (el) {
el.appendchild(this.controltextel_);
}
this.controltext(this.controltext_, el);
return this.controltextel_;
}
/**
* get or set the localize text to use for the controls on the `clickablecomponent`.
*
* @param {string} [text]
* control text for element.
*
* @param {element} [el=this.el()]
* element to set the title on.
*
* @return {string}
* - the control text when getting
*/
;
_proto.controltext = function controltext(text, el) {
if (el === void 0) {
el = this.el();
}
if (text === undefined) {
return this.controltext_ || 'need text';
}
var localizedtext = this.localize(text);
this.controltext_ = text;
textcontent(this.controltextel_, localizedtext);
if (!this.noniconcontrol && !this.player_.options_.nouititleattributes) {
// set title attribute if only an icon is shown
el.setattribute('title', localizedtext);
}
}
/**
* builds the default dom `classname`.
*
* @return {string}
* the dom `classname` for this object.
*/
;
_proto.buildcssclass = function buildcssclass() {
return "vjs-control vjs-button " + _component.prototype.buildcssclass.call(this);
}
/**
* enable this `clickablecomponent`
*/
;
_proto.enable = function enable() {
if (!this.enabled_) {
this.enabled_ = true;
this.removeclass('vjs-disabled');
this.el_.setattribute('aria-disabled', 'false');
if (typeof this.tabindex_ !== 'undefined') {
this.el_.setattribute('tabindex', this.tabindex_);
}
this.on(['tap', 'click'], this.handleclick_);
this.on('keydown', this.handlekeydown_);
}
}
/**
* disable this `clickablecomponent`
*/
;
_proto.disable = function disable() {
this.enabled_ = false;
this.addclass('vjs-disabled');
this.el_.setattribute('aria-disabled', 'true');
if (typeof this.tabindex_ !== 'undefined') {
this.el_.removeattribute('tabindex');
}
this.off('mouseover', this.handlemouseover_);
this.off('mouseout', this.handlemouseout_);
this.off(['tap', 'click'], this.handleclick_);
this.off('keydown', this.handlekeydown_);
}
/**
* handles language change in clickablecomponent for the player in components
*
*
*/
;
_proto.handlelanguagechange = function handlelanguagechange() {
this.controltext(this.controltext_);
}
/**
* event handler that is called when a `clickablecomponent` receives a
* `click` or `tap` event.
*
* @param {eventtarget~event} event
* the `tap` or `click` event that caused this function to be called.
*
* @listens tap
* @listens click
* @abstract
*/
;
_proto.handleclick = function handleclick(event) {
if (this.options_.clickhandler) {
this.options_.clickhandler.call(this, arguments);
}
}
/**
* event handler that is called when a `clickablecomponent` receives a
* `keydown` event.
*
* by default, if the key is space or enter, it will trigger a `click` event.
*
* @param {eventtarget~event} event
* the `keydown` event that caused this function to be called.
*
* @listens keydown
*/
;
_proto.handlekeydown = function handlekeydown(event) {
// support space or enter key operation to fire a click event. also,
// prevent the event from propagating through the dom and triggering
// player hotkeys.
if (keycode__webpack_imported_module_3___default.a.iseventkey(event, 'space') || keycode__webpack_imported_module_3___default.a.iseventkey(event, 'enter')) {
event.preventdefault();
event.stoppropagation();
this.trigger('click');
} else {
// pass keypress handling up for unsupported keys
_component.prototype.handlekeydown.call(this, event);
}
};
return clickablecomponent;
}(component$1);
component$1.registercomponent('clickablecomponent', clickablecomponent);
/**
* a `clickablecomponent` that handles showing the poster image for the player.
*
* @extends clickablecomponent
*/
var posterimage = /*#__pure__*/function (_clickablecomponent) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(posterimage, _clickablecomponent);
/**
* create an instance of this class.
*
* @param {player} player
* the `player` that this class should attach to.
*
* @param {object} [options]
* the key/value store of player options.
*/
function posterimage(player, options) {
var _this;
_this = _clickablecomponent.call(this, player, options) || this;
_this.update();
_this.update_ = function (e) {
return _this.update(e);
};
player.on('posterchange', _this.update_);
return _this;
}
/**
* clean up and dispose of the `posterimage`.
*/
var _proto = posterimage.prototype;
_proto.dispose = function dispose() {
this.player().off('posterchange', this.update_);
_clickablecomponent.prototype.dispose.call(this);
}
/**
* create the `posterimage`s dom element.
*
* @return {element}
* the element that gets created.
*/
;
_proto.createel = function createel$1() {
var el = createel('div', {
classname: 'vjs-poster',
// don't want poster to be tabbable.
tabindex: -1
});
return el;
}
/**
* an {@link eventtarget~eventlistener} for {@link player#posterchange} events.
*
* @listens player#posterchange
*
* @param {eventtarget~event} [event]
* the `player#posterchange` event that triggered this function.
*/
;
_proto.update = function update(event) {
var url = this.player().poster();
this.setsrc(url); // if there's no poster source we should display:none on this component
// so it's not still clickable or right-clickable
if (url) {
this.show();
} else {
this.hide();
}
}
/**
* set the source of the `posterimage` depending on the display method.
*
* @param {string} url
* the url to the source for the `posterimage`.
*/
;
_proto.setsrc = function setsrc(url) {
var backgroundimage = ''; // any falsy value should stay as an empty string, otherwise
// this will throw an extra error
if (url) {
backgroundimage = "url(\"" + url + "\")";
}
this.el_.style.backgroundimage = backgroundimage;
}
/**
* an {@link eventtarget~eventlistener} for clicks on the `posterimage`. see
* {@link clickablecomponent#handleclick} for instances where this will be triggered.
*
* @listens tap
* @listens click
* @listens keydown
*
* @param {eventtarget~event} event
+ the `click`, `tap` or `keydown` event that caused this function to be called.
*/
;
_proto.handleclick = function handleclick(event) {
// we don't want a click to trigger playback when controls are disabled
if (!this.player_.controls()) {
return;
}
var sourceisencrypted = this.player_.usingplugin('eme') && this.player_.eme.sessions && this.player_.eme.sessions.length > 0;
if (this.player_.tech(true) && // we've observed a bug in ie and edge when playing back drm content where
// calling .focus() on the video element causes the video to go black,
// so we avoid it in that specific case
!((ie_version || is_edge) && sourceisencrypted)) {
this.player_.tech(true).focus();
}
if (this.player_.paused()) {
silencepromise(this.player_.play());
} else {
this.player_.pause();
}
};
return posterimage;
}(clickablecomponent);
component$1.registercomponent('posterimage', posterimage);
var darkgray = '#222';
var lightgray = '#ccc';
var fontmap = {
monospace: 'monospace',
sansserif: 'sans-serif',
serif: 'serif',
monospacesansserif: '"andale mono", "lucida console", monospace',
monospaceserif: '"courier new", monospace',
proportionalsansserif: 'sans-serif',
proportionalserif: 'serif',
casual: '"comic sans ms", impact, fantasy',
script: '"monotype corsiva", cursive',
smallcaps: '"andale mono", "lucida console", monospace, sans-serif'
};
/**
* construct an rgba color from a given hex color code.
*
* @param {number} color
* hex number for color, like #f0e or #f604e2.
*
* @param {number} opacity
* value for opacity, 0.0 - 1.0.
*
* @return {string}
* the rgba color that was created, like 'rgba(255, 0, 0, 0.3)'.
*/
function constructcolor(color, opacity) {
var hex;
if (color.length === 4) {
// color looks like "#f0e"
hex = color[1] + color[1] + color[2] + color[2] + color[3] + color[3];
} else if (color.length === 7) {
// color looks like "#f604e2"
hex = color.slice(1);
} else {
throw new error('invalid color code provided, ' + color + '; must be formatted as e.g. #f0e or #f604e2.');
}
return 'rgba(' + parseint(hex.slice(0, 2), 16) + ',' + parseint(hex.slice(2, 4), 16) + ',' + parseint(hex.slice(4, 6), 16) + ',' + opacity + ')';
}
/**
* try to update the style of a dom element. some style changes will throw an error,
* particularly in ie8. those should be noops.
*
* @param {element} el
* the dom element to be styled.
*
* @param {string} style
* the css property on the element that should be styled.
*
* @param {string} rule
* the style rule that should be applied to the property.
*
* @private
*/
function tryupdatestyle(el, style, rule) {
try {
el.style[style] = rule;
} catch (e) {
// satisfies linter.
return;
}
}
/**
* the component for displaying text track cues.
*
* @extends component
*/
var texttrackdisplay = /*#__pure__*/function (_component) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(texttrackdisplay, _component);
/**
* creates an instance of this class.
*
* @param {player} player
* the `player` that this class should be attached to.
*
* @param {object} [options]
* the key/value store of player options.
*
* @param {component~readycallback} [ready]
* the function to call when `texttrackdisplay` is ready.
*/
function texttrackdisplay(player, options, ready) {
var _this;
_this = _component.call(this, player, options, ready) || this;
var updatedisplayhandler = function updatedisplayhandler(e) {
return _this.updatedisplay(e);
};
player.on('loadstart', function (e) {
return _this.toggledisplay(e);
});
player.on('texttrackchange', updatedisplayhandler);
player.on('loadedmetadata', function (e) {
return _this.preselecttrack(e);
}); // this used to be called during player init, but was causing an error
// if a track should show by default and the display hadn't loaded yet.
// should probably be moved to an external track loader when we support
// tracks that don't need a display.
player.ready(bind(_babel_runtime_helpers_assertthisinitialized__webpack_imported_module_4___default()(_this), function () {
if (player.tech_ && player.tech_.featuresnativetexttracks) {
this.hide();
return;
}
player.on('fullscreenchange', updatedisplayhandler);
player.on('playerresize', updatedisplayhandler);
global_window__webpack_imported_module_0___default.a.addeventlistener('orientationchange', updatedisplayhandler);
player.on('dispose', function () {
return global_window__webpack_imported_module_0___default.a.removeeventlistener('orientationchange', updatedisplayhandler);
});
var tracks = this.options_.playeroptions.tracks || [];
for (var i = 0; i < tracks.length; i++) {
this.player_.addremotetexttrack(tracks[i], true);
}
this.preselecttrack();
}));
return _this;
}
/**
* preselect a track following this precedence:
* - matches the previously selected {@link texttrack}'s language and kind
* - matches the previously selected {@link texttrack}'s language only
* - is the first default captions track
* - is the first default descriptions track
*
* @listens player#loadstart
*/
var _proto = texttrackdisplay.prototype;
_proto.preselecttrack = function preselecttrack() {
var modes = {
captions: 1,
subtitles: 1
};
var tracklist = this.player_.texttracks();
var userpref = this.player_.cache_.selectedlanguage;
var firstdesc;
var firstcaptions;
var preferredtrack;
for (var i = 0; i < tracklist.length; i++) {
var track = tracklist[i];
if (userpref && userpref.enabled && userpref.language && userpref.language === track.language && track.kind in modes) {
// always choose the track that matches both language and kind
if (track.kind === userpref.kind) {
preferredtrack = track; // or choose the first track that matches language
} else if (!preferredtrack) {
preferredtrack = track;
} // clear everything if offtexttrackmenuitem was clicked
} else if (userpref && !userpref.enabled) {
preferredtrack = null;
firstdesc = null;
firstcaptions = null;
} else if (track["default"]) {
if (track.kind === 'descriptions' && !firstdesc) {
firstdesc = track;
} else if (track.kind in modes && !firstcaptions) {
firstcaptions = track;
}
}
} // the preferredtrack matches the user preference and takes
// precedence over all the other tracks.
// so, display the preferredtrack before the first default track
// and the subtitles/captions track before the descriptions track
if (preferredtrack) {
preferredtrack.mode = 'showing';
} else if (firstcaptions) {
firstcaptions.mode = 'showing';
} else if (firstdesc) {
firstdesc.mode = 'showing';
}
}
/**
* turn display of {@link texttrack}'s from the current state into the other state.
* there are only two states:
* - 'shown'
* - 'hidden'
*
* @listens player#loadstart
*/
;
_proto.toggledisplay = function toggledisplay() {
if (this.player_.tech_ && this.player_.tech_.featuresnativetexttracks) {
this.hide();
} else {
this.show();
}
}
/**
* create the {@link component}'s dom element.
*
* @return {element}
* the element that was created.
*/
;
_proto.createel = function createel() {
return _component.prototype.createel.call(this, 'div', {
classname: 'vjs-text-track-display'
}, {
'translate': 'yes',
'aria-live': 'off',
'aria-atomic': 'true'
});
}
/**
* clear all displayed {@link texttrack}s.
*/
;
_proto.cleardisplay = function cleardisplay() {
if (typeof global_window__webpack_imported_module_0___default.a.webvtt === 'function') {
global_window__webpack_imported_module_0___default.a.webvtt.processcues(global_window__webpack_imported_module_0___default.a, [], this.el_);
}
}
/**
* update the displayed texttrack when a either a {@link player#texttrackchange} or
* a {@link player#fullscreenchange} is fired.
*
* @listens player#texttrackchange
* @listens player#fullscreenchange
*/
;
_proto.updatedisplay = function updatedisplay() {
var tracks = this.player_.texttracks();
var allowmultipleshowingtracks = this.options_.allowmultipleshowingtracks;
this.cleardisplay();
if (allowmultipleshowingtracks) {
var showingtracks = [];
for (var _i = 0; _i < tracks.length; ++_i) {
var track = tracks[_i];
if (track.mode !== 'showing') {
continue;
}
showingtracks.push(track);
}
this.updatefortrack(showingtracks);
return;
} // track display prioritization model: if multiple tracks are 'showing',
// display the first 'subtitles' or 'captions' track which is 'showing',
// otherwise display the first 'descriptions' track which is 'showing'
var descriptionstrack = null;
var captionssubtitlestrack = null;
var i = tracks.length;
while (i--) {
var _track = tracks[i];
if (_track.mode === 'showing') {
if (_track.kind === 'descriptions') {
descriptionstrack = _track;
} else {
captionssubtitlestrack = _track;
}
}
}
if (captionssubtitlestrack) {
if (this.getattribute('aria-live') !== 'off') {
this.setattribute('aria-live', 'off');
}
this.updatefortrack(captionssubtitlestrack);
} else if (descriptionstrack) {
if (this.getattribute('aria-live') !== 'assertive') {
this.setattribute('aria-live', 'assertive');
}
this.updatefortrack(descriptionstrack);
}
}
/**
* style {@link texttrack} activecues according to {@link texttracksettings}.
*
* @param {texttrack} track
* text track object containing active cues to style.
*/
;
_proto.updatedisplaystate = function updatedisplaystate(track) {
var overrides = this.player_.texttracksettings.getvalues();
var cues = track.activecues;
var i = cues.length;
while (i--) {
var cue = cues[i];
if (!cue) {
continue;
}
var cuediv = cue.displaystate;
if (overrides.color) {
cuediv.firstchild.style.color = overrides.color;
}
if (overrides.textopacity) {
tryupdatestyle(cuediv.firstchild, 'color', constructcolor(overrides.color || '#fff', overrides.textopacity));
}
if (overrides.backgroundcolor) {
cuediv.firstchild.style.backgroundcolor = overrides.backgroundcolor;
}
if (overrides.backgroundopacity) {
tryupdatestyle(cuediv.firstchild, 'backgroundcolor', constructcolor(overrides.backgroundcolor || '#000', overrides.backgroundopacity));
}
if (overrides.windowcolor) {
if (overrides.windowopacity) {
tryupdatestyle(cuediv, 'backgroundcolor', constructcolor(overrides.windowcolor, overrides.windowopacity));
} else {
cuediv.style.backgroundcolor = overrides.windowcolor;
}
}
if (overrides.edgestyle) {
if (overrides.edgestyle === 'dropshadow') {
cuediv.firstchild.style.textshadow = "2px 2px 3px " + darkgray + ", 2px 2px 4px " + darkgray + ", 2px 2px 5px " + darkgray;
} else if (overrides.edgestyle === 'raised') {
cuediv.firstchild.style.textshadow = "1px 1px " + darkgray + ", 2px 2px " + darkgray + ", 3px 3px " + darkgray;
} else if (overrides.edgestyle === 'depressed') {
cuediv.firstchild.style.textshadow = "1px 1px " + lightgray + ", 0 1px " + lightgray + ", -1px -1px " + darkgray + ", 0 -1px " + darkgray;
} else if (overrides.edgestyle === 'uniform') {
cuediv.firstchild.style.textshadow = "0 0 4px " + darkgray + ", 0 0 4px " + darkgray + ", 0 0 4px " + darkgray + ", 0 0 4px " + darkgray;
}
}
if (overrides.fontpercent && overrides.fontpercent !== 1) {
var fontsize = global_window__webpack_imported_module_0___default.a.parsefloat(cuediv.style.fontsize);
cuediv.style.fontsize = fontsize * overrides.fontpercent + 'px';
cuediv.style.height = 'auto';
cuediv.style.top = 'auto';
}
if (overrides.fontfamily && overrides.fontfamily !== 'default') {
if (overrides.fontfamily === 'small-caps') {
cuediv.firstchild.style.fontvariant = 'small-caps';
} else {
cuediv.firstchild.style.fontfamily = fontmap[overrides.fontfamily];
}
}
}
}
/**
* add an {@link texttrack} to to the {@link tech}s {@link texttracklist}.
*
* @param {texttrack|texttrack[]} tracks
* text track object or text track array to be added to the list.
*/
;
_proto.updatefortrack = function updatefortrack(tracks) {
if (!array.isarray(tracks)) {
tracks = [tracks];
}
if (typeof global_window__webpack_imported_module_0___default.a.webvtt !== 'function' || tracks.every(function (track) {
return !track.activecues;
})) {
return;
}
var cues = []; // push all active track cues
for (var i = 0; i < tracks.length; ++i) {
var track = tracks[i];
for (var j = 0; j < track.activecues.length; ++j) {
cues.push(track.activecues[j]);
}
} // removes all cues before it processes new ones
global_window__webpack_imported_module_0___default.a.webvtt.processcues(global_window__webpack_imported_module_0___default.a, cues, this.el_); // add unique class to each language text track & add settings styling if necessary
for (var _i2 = 0; _i2 < tracks.length; ++_i2) {
var _track2 = tracks[_i2];
for (var _j = 0; _j < _track2.activecues.length; ++_j) {
var cueel = _track2.activecues[_j].displaystate;
addclass(cueel, 'vjs-text-track-cue');
addclass(cueel, 'vjs-text-track-cue-' + (_track2.language ? _track2.language : _i2));
if (_track2.language) {
setattribute(cueel, 'lang', _track2.language);
}
}
if (this.player_.texttracksettings) {
this.updatedisplaystate(_track2);
}
}
};
return texttrackdisplay;
}(component$1);
component$1.registercomponent('texttrackdisplay', texttrackdisplay);
/**
* a loading spinner for use during waiting/loading events.
*
* @extends component
*/
var loadingspinner = /*#__pure__*/function (_component) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(loadingspinner, _component);
function loadingspinner() {
return _component.apply(this, arguments) || this;
}
var _proto = loadingspinner.prototype;
/**
* create the `loadingspinner`s dom element.
*
* @return {element}
* the dom element that gets created.
*/
_proto.createel = function createel$1() {
var isaudio = this.player_.isaudio();
var playertype = this.localize(isaudio ? 'audio player' : 'video player');
var controltext = createel('span', {
classname: 'vjs-control-text',
textcontent: this.localize('{1} is loading.', [playertype])
});
var el = _component.prototype.createel.call(this, 'div', {
classname: 'vjs-loading-spinner',
dir: 'ltr'
});
el.appendchild(controltext);
return el;
};
return loadingspinner;
}(component$1);
component$1.registercomponent('loadingspinner', loadingspinner);
/**
* base class for all buttons.
*
* @extends clickablecomponent
*/
var button = /*#__pure__*/function (_clickablecomponent) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(button, _clickablecomponent);
function button() {
return _clickablecomponent.apply(this, arguments) || this;
}
var _proto = button.prototype;
/**
* create the `button`s dom element.
*
* @param {string} [tag="button"]
* the element's node type. this argument is ignored: no matter what
* is passed, it will always create a `button` element.
*
* @param {object} [props={}]
* an object of properties that should be set on the element.
*
* @param {object} [attributes={}]
* an object of attributes that should be set on the element.
*
* @return {element}
* the element that gets created.
*/
_proto.createel = function createel$1(tag, props, attributes) {
if (props === void 0) {
props = {};
}
if (attributes === void 0) {
attributes = {};
}
tag = 'button';
props = assign({
classname: this.buildcssclass()
}, props); // add attributes for button element
attributes = assign({
// necessary since the default button type is "submit"
type: 'button'
}, attributes);
var el = createel(tag, props, attributes);
el.appendchild(createel('span', {
classname: 'vjs-icon-placeholder'
}, {
'aria-hidden': true
}));
this.createcontroltextel(el);
return el;
}
/**
* add a child `component` inside of this `button`.
*
* @param {string|component} child
* the name or instance of a child to add.
*
* @param {object} [options={}]
* the key/value store of options that will get passed to children of
* the child.
*
* @return {component}
* the `component` that gets added as a child. when using a string the
* `component` will get created by this process.
*
* @deprecated since version 5
*/
;
_proto.addchild = function addchild(child, options) {
if (options === void 0) {
options = {};
}
var classname = this.constructor.name;
log$1.warn("adding an actionable (user controllable) child to a button (" + classname + ") is not supported; use a clickablecomponent instead."); // avoid the error message generated by clickablecomponent's addchild method
return component$1.prototype.addchild.call(this, child, options);
}
/**
* enable the `button` element so that it can be activated or clicked. use this with
* {@link button#disable}.
*/
;
_proto.enable = function enable() {
_clickablecomponent.prototype.enable.call(this);
this.el_.removeattribute('disabled');
}
/**
* disable the `button` element so that it cannot be activated or clicked. use this with
* {@link button#enable}.
*/
;
_proto.disable = function disable() {
_clickablecomponent.prototype.disable.call(this);
this.el_.setattribute('disabled', 'disabled');
}
/**
* this gets called when a `button` has focus and `keydown` is triggered via a key
* press.
*
* @param {eventtarget~event} event
* the event that caused this function to get called.
*
* @listens keydown
*/
;
_proto.handlekeydown = function handlekeydown(event) {
// ignore space or enter key operation, which is handled by the browser for
// a button - though not for its super class, clickablecomponent. also,
// prevent the event from propagating through the dom and triggering player
// hotkeys. we do not preventdefault here because we _want_ the browser to
// handle it.
if (keycode__webpack_imported_module_3___default.a.iseventkey(event, 'space') || keycode__webpack_imported_module_3___default.a.iseventkey(event, 'enter')) {
event.stoppropagation();
return;
} // pass keypress handling up for unsupported keys
_clickablecomponent.prototype.handlekeydown.call(this, event);
};
return button;
}(clickablecomponent);
component$1.registercomponent('button', button);
/**
* the initial play button that shows before the video has played. the hiding of the
* `bigplaybutton` get done via css and `player` states.
*
* @extends button
*/
var bigplaybutton = /*#__pure__*/function (_button) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(bigplaybutton, _button);
function bigplaybutton(player, options) {
var _this;
_this = _button.call(this, player, options) || this;
_this.mouseused_ = false;
_this.on('mousedown', function (e) {
return _this.handlemousedown(e);
});
return _this;
}
/**
* builds the default dom `classname`.
*
* @return {string}
* the dom `classname` for this object. always returns 'vjs-big-play-button'.
*/
var _proto = bigplaybutton.prototype;
_proto.buildcssclass = function buildcssclass() {
return 'vjs-big-play-button';
}
/**
* this gets called when a `bigplaybutton` "clicked". see {@link clickablecomponent}
* for more detailed information on what a click can be.
*
* @param {eventtarget~event} event
* the `keydown`, `tap`, or `click` event that caused this function to be
* called.
*
* @listens tap
* @listens click
*/
;
_proto.handleclick = function handleclick(event) {
var playpromise = this.player_.play(); // exit early if clicked via the mouse
if (this.mouseused_ && event.clientx && event.clienty) {
var sourceisencrypted = this.player_.usingplugin('eme') && this.player_.eme.sessions && this.player_.eme.sessions.length > 0;
silencepromise(playpromise);
if (this.player_.tech(true) && // we've observed a bug in ie and edge when playing back drm content where
// calling .focus() on the video element causes the video to go black,
// so we avoid it in that specific case
!((ie_version || is_edge) && sourceisencrypted)) {
this.player_.tech(true).focus();
}
return;
}
var cb = this.player_.getchild('controlbar');
var playtoggle = cb && cb.getchild('playtoggle');
if (!playtoggle) {
this.player_.tech(true).focus();
return;
}
var playfocus = function playfocus() {
return playtoggle.focus();
};
if (ispromise(playpromise)) {
playpromise.then(playfocus, function () {});
} else {
this.settimeout(playfocus, 1);
}
};
_proto.handlekeydown = function handlekeydown(event) {
this.mouseused_ = false;
_button.prototype.handlekeydown.call(this, event);
};
_proto.handlemousedown = function handlemousedown(event) {
this.mouseused_ = true;
};
return bigplaybutton;
}(button);
/**
* the text that should display over the `bigplaybutton`s controls. added to for localization.
*
* @type {string}
* @private
*/
bigplaybutton.prototype.controltext_ = 'play video';
component$1.registercomponent('bigplaybutton', bigplaybutton);
/**
* the `closebutton` is a `{@link button}` that fires a `close` event when
* it gets clicked.
*
* @extends button
*/
var closebutton = /*#__pure__*/function (_button) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(closebutton, _button);
/**
* creates an instance of the this class.
*
* @param {player} player
* the `player` that this class should be attached to.
*
* @param {object} [options]
* the key/value store of player options.
*/
function closebutton(player, options) {
var _this;
_this = _button.call(this, player, options) || this;
_this.controltext(options && options.controltext || _this.localize('close'));
return _this;
}
/**
* builds the default dom `classname`.
*
* @return {string}
* the dom `classname` for this object.
*/
var _proto = closebutton.prototype;
_proto.buildcssclass = function buildcssclass() {
return "vjs-close-button " + _button.prototype.buildcssclass.call(this);
}
/**
* this gets called when a `closebutton` gets clicked. see
* {@link clickablecomponent#handleclick} for more information on when
* this will be triggered
*
* @param {eventtarget~event} event
* the `keydown`, `tap`, or `click` event that caused this function to be
* called.
*
* @listens tap
* @listens click
* @fires closebutton#close
*/
;
_proto.handleclick = function handleclick(event) {
/**
* triggered when the a `closebutton` is clicked.
*
* @event closebutton#close
* @type {eventtarget~event}
*
* @property {boolean} [bubbles=false]
* set to false so that the close event does not
* bubble up to parents if there is no listener
*/
this.trigger({
type: 'close',
bubbles: false
});
}
/**
* event handler that is called when a `closebutton` receives a
* `keydown` event.
*
* by default, if the key is esc, it will trigger a `click` event.
*
* @param {eventtarget~event} event
* the `keydown` event that caused this function to be called.
*
* @listens keydown
*/
;
_proto.handlekeydown = function handlekeydown(event) {
// esc button will trigger `click` event
if (keycode__webpack_imported_module_3___default.a.iseventkey(event, 'esc')) {
event.preventdefault();
event.stoppropagation();
this.trigger('click');
} else {
// pass keypress handling up for unsupported keys
_button.prototype.handlekeydown.call(this, event);
}
};
return closebutton;
}(button);
component$1.registercomponent('closebutton', closebutton);
/**
* button to toggle between play and pause.
*
* @extends button
*/
var playtoggle = /*#__pure__*/function (_button) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(playtoggle, _button);
/**
* creates an instance of this class.
*
* @param {player} player
* the `player` that this class should be attached to.
*
* @param {object} [options={}]
* the key/value store of player options.
*/
function playtoggle(player, options) {
var _this;
if (options === void 0) {
options = {};
}
_this = _button.call(this, player, options) || this; // show or hide replay icon
options.replay = options.replay === undefined || options.replay;
_this.on(player, 'play', function (e) {
return _this.handleplay(e);
});
_this.on(player, 'pause', function (e) {
return _this.handlepause(e);
});
if (options.replay) {
_this.on(player, 'ended', function (e) {
return _this.handleended(e);
});
}
return _this;
}
/**
* builds the default dom `classname`.
*
* @return {string}
* the dom `classname` for this object.
*/
var _proto = playtoggle.prototype;
_proto.buildcssclass = function buildcssclass() {
return "vjs-play-control " + _button.prototype.buildcssclass.call(this);
}
/**
* this gets called when an `playtoggle` is "clicked". see
* {@link clickablecomponent} for more detailed information on what a click can be.
*
* @param {eventtarget~event} [event]
* the `keydown`, `tap`, or `click` event that caused this function to be
* called.
*
* @listens tap
* @listens click
*/
;
_proto.handleclick = function handleclick(event) {
if (this.player_.paused()) {
silencepromise(this.player_.play());
} else {
this.player_.pause();
}
}
/**
* this gets called once after the video has ended and the user seeks so that
* we can change the replay button back to a play button.
*
* @param {eventtarget~event} [event]
* the event that caused this function to run.
*
* @listens player#seeked
*/
;
_proto.handleseeked = function handleseeked(event) {
this.removeclass('vjs-ended');
if (this.player_.paused()) {
this.handlepause(event);
} else {
this.handleplay(event);
}
}
/**
* add the vjs-playing class to the element so it can change appearance.
*
* @param {eventtarget~event} [event]
* the event that caused this function to run.
*
* @listens player#play
*/
;
_proto.handleplay = function handleplay(event) {
this.removeclass('vjs-ended');
this.removeclass('vjs-paused');
this.addclass('vjs-playing'); // change the button text to "pause"
this.controltext('pause');
}
/**
* add the vjs-paused class to the element so it can change appearance.
*
* @param {eventtarget~event} [event]
* the event that caused this function to run.
*
* @listens player#pause
*/
;
_proto.handlepause = function handlepause(event) {
this.removeclass('vjs-playing');
this.addclass('vjs-paused'); // change the button text to "play"
this.controltext('play');
}
/**
* add the vjs-ended class to the element so it can change appearance
*
* @param {eventtarget~event} [event]
* the event that caused this function to run.
*
* @listens player#ended
*/
;
_proto.handleended = function handleended(event) {
var _this2 = this;
this.removeclass('vjs-playing');
this.addclass('vjs-ended'); // change the button text to "replay"
this.controltext('replay'); // on the next seek remove the replay button
this.one(this.player_, 'seeked', function (e) {
return _this2.handleseeked(e);
});
};
return playtoggle;
}(button);
/**
* the text that should display over the `playtoggle`s controls. added for localization.
*
* @type {string}
* @private
*/
playtoggle.prototype.controltext_ = 'play';
component$1.registercomponent('playtoggle', playtoggle);
/**
* @file format-time.js
* @module format-time
*/
/**
* format seconds as a time string, h:mm:ss or m:ss. supplying a guide (in
* seconds) will force a number of leading zeros to cover the length of the
* guide.
*
* @private
* @param {number} seconds
* number of seconds to be turned into a string
*
* @param {number} guide
* number (in seconds) to model the string after
*
* @return {string}
* time formatted as h:mm:ss or m:ss
*/
var defaultimplementation = function defaultimplementation(seconds, guide) {
seconds = seconds < 0 ? 0 : seconds;
var s = math.floor(seconds % 60);
var m = math.floor(seconds / 60 % 60);
var h = math.floor(seconds / 3600);
var gm = math.floor(guide / 60 % 60);
var gh = math.floor(guide / 3600); // handle invalid times
if (isnan(seconds) || seconds === infinity) {
// '-' is false for all relational operators (e.g. <, >=) so this setting
// will add the minimum number of fields specified by the guide
h = m = s = '-';
} // check if we need to show hours
h = h > 0 || gh > 0 ? h + ':' : ''; // if hours are showing, we may need to add a leading zero.
// always show at least one digit of minutes.
m = ((h || gm >= 10) && m < 10 ? '0' + m : m) + ':'; // check if leading zero is need for seconds
s = s < 10 ? '0' + s : s;
return h + m + s;
}; // internal pointer to the current implementation.
var implementation = defaultimplementation;
/**
* replaces the default formattime implementation with a custom implementation.
*
* @param {function} customimplementation
* a function which will be used in place of the default formattime
* implementation. will receive the current time in seconds and the
* guide (in seconds) as arguments.
*/
function setformattime(customimplementation) {
implementation = customimplementation;
}
/**
* resets formattime to the default implementation.
*/
function resetformattime() {
implementation = defaultimplementation;
}
/**
* delegates to either the default time formatting function or a custom
* function supplied via `setformattime`.
*
* formats seconds as a time string (h:mm:ss or m:ss). supplying a
* guide (in seconds) will force a number of leading zeros to cover the
* length of the guide.
*
* @static
* @example formattime(125, 600) === "02:05"
* @param {number} seconds
* number of seconds to be turned into a string
*
* @param {number} guide
* number (in seconds) to model the string after
*
* @return {string}
* time formatted as h:mm:ss or m:ss
*/
function formattime(seconds, guide) {
if (guide === void 0) {
guide = seconds;
}
return implementation(seconds, guide);
}
/**
* displays time information about the video
*
* @extends component
*/
var timedisplay = /*#__pure__*/function (_component) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(timedisplay, _component);
/**
* creates an instance of this class.
*
* @param {player} player
* the `player` that this class should be attached to.
*
* @param {object} [options]
* the key/value store of player options.
*/
function timedisplay(player, options) {
var _this;
_this = _component.call(this, player, options) || this;
_this.on(player, ['timeupdate', 'ended'], function (e) {
return _this.updatecontent(e);
});
_this.updatetextnode_();
return _this;
}
/**
* create the `component`'s dom element
*
* @return {element}
* the element that was created.
*/
var _proto = timedisplay.prototype;
_proto.createel = function createel$1() {
var classname = this.buildcssclass();
var el = _component.prototype.createel.call(this, 'div', {
classname: classname + " vjs-time-control vjs-control"
});
var span = createel('span', {
classname: 'vjs-control-text',
textcontent: this.localize(this.labeltext_) + "\xa0"
}, {
role: 'presentation'
});
el.appendchild(span);
this.contentel_ = createel('span', {
classname: classname + "-display"
}, {
// tell screen readers not to automatically read the time as it changes
'aria-live': 'off',
// span elements have no implicit role, but some screen readers (notably voiceover)
// treat them as a break between items in the dom when using arrow keys
// (or left-to-right swipes on ios) to read contents of a page. using
// role='presentation' causes voiceover to not treat this span as a break.
'role': 'presentation'
});
el.appendchild(this.contentel_);
return el;
};
_proto.dispose = function dispose() {
this.contentel_ = null;
this.textnode_ = null;
_component.prototype.dispose.call(this);
}
/**
* updates the time display text node with a new time
*
* @param {number} [time=0] the time to update to
*
* @private
*/
;
_proto.updatetextnode_ = function updatetextnode_(time) {
var _this2 = this;
if (time === void 0) {
time = 0;
}
time = formattime(time);
if (this.formattedtime_ === time) {
return;
}
this.formattedtime_ = time;
this.requestnamedanimationframe('timedisplay#updatetextnode_', function () {
if (!_this2.contentel_) {
return;
}
var oldnode = _this2.textnode_;
if (oldnode && _this2.contentel_.firstchild !== oldnode) {
oldnode = null;
log$1.warn('timedisplay#updatetextnode_: prevented replacement of text node element since it was no longer a child of this node. appending a new node instead.');
}
_this2.textnode_ = global_document__webpack_imported_module_1___default.a.createtextnode(_this2.formattedtime_);
if (!_this2.textnode_) {
return;
}
if (oldnode) {
_this2.contentel_.replacechild(_this2.textnode_, oldnode);
} else {
_this2.contentel_.appendchild(_this2.textnode_);
}
});
}
/**
* to be filled out in the child class, should update the displayed time
* in accordance with the fact that the current time has changed.
*
* @param {eventtarget~event} [event]
* the `timeupdate` event that caused this to run.
*
* @listens player#timeupdate
*/
;
_proto.updatecontent = function updatecontent(event) {};
return timedisplay;
}(component$1);
/**
* the text that is added to the `timedisplay` for screen reader users.
*
* @type {string}
* @private
*/
timedisplay.prototype.labeltext_ = 'time';
/**
* the text that should display over the `timedisplay`s controls. added to for localization.
*
* @type {string}
* @private
*
* @deprecated in v7; controltext_ is not used in non-active display components
*/
timedisplay.prototype.controltext_ = 'time';
component$1.registercomponent('timedisplay', timedisplay);
/**
* displays the current time
*
* @extends component
*/
var currenttimedisplay = /*#__pure__*/function (_timedisplay) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(currenttimedisplay, _timedisplay);
function currenttimedisplay() {
return _timedisplay.apply(this, arguments) || this;
}
var _proto = currenttimedisplay.prototype;
/**
* builds the default dom `classname`.
*
* @return {string}
* the dom `classname` for this object.
*/
_proto.buildcssclass = function buildcssclass() {
return 'vjs-current-time';
}
/**
* update current time display
*
* @param {eventtarget~event} [event]
* the `timeupdate` event that caused this function to run.
*
* @listens player#timeupdate
*/
;
_proto.updatecontent = function updatecontent(event) {
// allows for smooth scrubbing, when player can't keep up.
var time;
if (this.player_.ended()) {
time = this.player_.duration();
} else {
time = this.player_.scrubbing() ? this.player_.getcache().currenttime : this.player_.currenttime();
}
this.updatetextnode_(time);
};
return currenttimedisplay;
}(timedisplay);
/**
* the text that is added to the `currenttimedisplay` for screen reader users.
*
* @type {string}
* @private
*/
currenttimedisplay.prototype.labeltext_ = 'current time';
/**
* the text that should display over the `currenttimedisplay`s controls. added to for localization.
*
* @type {string}
* @private
*
* @deprecated in v7; controltext_ is not used in non-active display components
*/
currenttimedisplay.prototype.controltext_ = 'current time';
component$1.registercomponent('currenttimedisplay', currenttimedisplay);
/**
* displays the duration
*
* @extends component
*/
var durationdisplay = /*#__pure__*/function (_timedisplay) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(durationdisplay, _timedisplay);
/**
* creates an instance of this class.
*
* @param {player} player
* the `player` that this class should be attached to.
*
* @param {object} [options]
* the key/value store of player options.
*/
function durationdisplay(player, options) {
var _this;
_this = _timedisplay.call(this, player, options) || this;
var updatecontent = function updatecontent(e) {
return _this.updatecontent(e);
}; // we do not want to/need to throttle duration changes,
// as they should always display the changed duration as
// it has changed
_this.on(player, 'durationchange', updatecontent); // listen to loadstart because the player duration is reset when a new media element is loaded,
// but the durationchange on the user agent will not fire.
// @see [spec]{@link https://www.w3.org/tr/2011/wd-html5-20110113/video.html#media-element-load-algorithm}
_this.on(player, 'loadstart', updatecontent); // also listen for timeupdate (in the parent) and loadedmetadata because removing those
// listeners could have broken dependent applications/libraries. these
// can likely be removed for 7.0.
_this.on(player, 'loadedmetadata', updatecontent);
return _this;
}
/**
* builds the default dom `classname`.
*
* @return {string}
* the dom `classname` for this object.
*/
var _proto = durationdisplay.prototype;
_proto.buildcssclass = function buildcssclass() {
return 'vjs-duration';
}
/**
* update duration time display.
*
* @param {eventtarget~event} [event]
* the `durationchange`, `timeupdate`, or `loadedmetadata` event that caused
* this function to be called.
*
* @listens player#durationchange
* @listens player#timeupdate
* @listens player#loadedmetadata
*/
;
_proto.updatecontent = function updatecontent(event) {
var duration = this.player_.duration();
this.updatetextnode_(duration);
};
return durationdisplay;
}(timedisplay);
/**
* the text that is added to the `durationdisplay` for screen reader users.
*
* @type {string}
* @private
*/
durationdisplay.prototype.labeltext_ = 'duration';
/**
* the text that should display over the `durationdisplay`s controls. added to for localization.
*
* @type {string}
* @private
*
* @deprecated in v7; controltext_ is not used in non-active display components
*/
durationdisplay.prototype.controltext_ = 'duration';
component$1.registercomponent('durationdisplay', durationdisplay);
/**
* the separator between the current time and duration.
* can be hidden if it's not needed in the design.
*
* @extends component
*/
var timedivider = /*#__pure__*/function (_component) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(timedivider, _component);
function timedivider() {
return _component.apply(this, arguments) || this;
}
var _proto = timedivider.prototype;
/**
* create the component's dom element
*
* @return {element}
* the element that was created.
*/
_proto.createel = function createel() {
var el = _component.prototype.createel.call(this, 'div', {
classname: 'vjs-time-control vjs-time-divider'
}, {
// this element and its contents can be hidden from assistive techs since
// it is made extraneous by the announcement of the control text
// for the current time and duration displays
'aria-hidden': true
});
var div = _component.prototype.createel.call(this, 'div');
var span = _component.prototype.createel.call(this, 'span', {
textcontent: '/'
});
div.appendchild(span);
el.appendchild(div);
return el;
};
return timedivider;
}(component$1);
component$1.registercomponent('timedivider', timedivider);
/**
* displays the time left in the video
*
* @extends component
*/
var remainingtimedisplay = /*#__pure__*/function (_timedisplay) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(remainingtimedisplay, _timedisplay);
/**
* creates an instance of this class.
*
* @param {player} player
* the `player` that this class should be attached to.
*
* @param {object} [options]
* the key/value store of player options.
*/
function remainingtimedisplay(player, options) {
var _this;
_this = _timedisplay.call(this, player, options) || this;
_this.on(player, 'durationchange', function (e) {
return _this.updatecontent(e);
});
return _this;
}
/**
* builds the default dom `classname`.
*
* @return {string}
* the dom `classname` for this object.
*/
var _proto = remainingtimedisplay.prototype;
_proto.buildcssclass = function buildcssclass() {
return 'vjs-remaining-time';
}
/**
* create the `component`'s dom element with the "minus" characted prepend to the time
*
* @return {element}
* the element that was created.
*/
;
_proto.createel = function createel$1() {
var el = _timedisplay.prototype.createel.call(this);
if (this.options_.displaynegative !== false) {
el.insertbefore(createel('span', {}, {
'aria-hidden': true
}, '-'), this.contentel_);
}
return el;
}
/**
* update remaining time display.
*
* @param {eventtarget~event} [event]
* the `timeupdate` or `durationchange` event that caused this to run.
*
* @listens player#timeupdate
* @listens player#durationchange
*/
;
_proto.updatecontent = function updatecontent(event) {
if (typeof this.player_.duration() !== 'number') {
return;
}
var time; // @deprecated we should only use remainingtimedisplay
// as of video.js 7
if (this.player_.ended()) {
time = 0;
} else if (this.player_.remainingtimedisplay) {
time = this.player_.remainingtimedisplay();
} else {
time = this.player_.remainingtime();
}
this.updatetextnode_(time);
};
return remainingtimedisplay;
}(timedisplay);
/**
* the text that is added to the `remainingtimedisplay` for screen reader users.
*
* @type {string}
* @private
*/
remainingtimedisplay.prototype.labeltext_ = 'remaining time';
/**
* the text that should display over the `remainingtimedisplay`s controls. added to for localization.
*
* @type {string}
* @private
*
* @deprecated in v7; controltext_ is not used in non-active display components
*/
remainingtimedisplay.prototype.controltext_ = 'remaining time';
component$1.registercomponent('remainingtimedisplay', remainingtimedisplay);
/**
* displays the live indicator when duration is infinity.
*
* @extends component
*/
var livedisplay = /*#__pure__*/function (_component) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(livedisplay, _component);
/**
* creates an instance of this class.
*
* @param {player} player
* the `player` that this class should be attached to.
*
* @param {object} [options]
* the key/value store of player options.
*/
function livedisplay(player, options) {
var _this;
_this = _component.call(this, player, options) || this;
_this.updateshowing();
_this.on(_this.player(), 'durationchange', function (e) {
return _this.updateshowing(e);
});
return _this;
}
/**
* create the `component`'s dom element
*
* @return {element}
* the element that was created.
*/
var _proto = livedisplay.prototype;
_proto.createel = function createel$1() {
var el = _component.prototype.createel.call(this, 'div', {
classname: 'vjs-live-control vjs-control'
});
this.contentel_ = createel('div', {
classname: 'vjs-live-display'
}, {
'aria-live': 'off'
});
this.contentel_.appendchild(createel('span', {
classname: 'vjs-control-text',
textcontent: this.localize('stream type') + "\xa0"
}));
this.contentel_.appendchild(global_document__webpack_imported_module_1___default.a.createtextnode(this.localize('live')));
el.appendchild(this.contentel_);
return el;
};
_proto.dispose = function dispose() {
this.contentel_ = null;
_component.prototype.dispose.call(this);
}
/**
* check the duration to see if the livedisplay should be showing or not. then show/hide
* it accordingly
*
* @param {eventtarget~event} [event]
* the {@link player#durationchange} event that caused this function to run.
*
* @listens player#durationchange
*/
;
_proto.updateshowing = function updateshowing(event) {
if (this.player().duration() === infinity) {
this.show();
} else {
this.hide();
}
};
return livedisplay;
}(component$1);
component$1.registercomponent('livedisplay', livedisplay);
/**
* displays the live indicator when duration is infinity.
*
* @extends component
*/
var seektolive = /*#__pure__*/function (_button) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(seektolive, _button);
/**
* creates an instance of this class.
*
* @param {player} player
* the `player` that this class should be attached to.
*
* @param {object} [options]
* the key/value store of player options.
*/
function seektolive(player, options) {
var _this;
_this = _button.call(this, player, options) || this;
_this.updateliveedgestatus();
if (_this.player_.livetracker) {
_this.updateliveedgestatushandler_ = function (e) {
return _this.updateliveedgestatus(e);
};
_this.on(_this.player_.livetracker, 'liveedgechange', _this.updateliveedgestatushandler_);
}
return _this;
}
/**
* create the `component`'s dom element
*
* @return {element}
* the element that was created.
*/
var _proto = seektolive.prototype;
_proto.createel = function createel$1() {
var el = _button.prototype.createel.call(this, 'button', {
classname: 'vjs-seek-to-live-control vjs-control'
});
this.textel_ = createel('span', {
classname: 'vjs-seek-to-live-text',
textcontent: this.localize('live')
}, {
'aria-hidden': 'true'
});
el.appendchild(this.textel_);
return el;
}
/**
* update the state of this button if we are at the live edge
* or not
*/
;
_proto.updateliveedgestatus = function updateliveedgestatus() {
// default to live edge
if (!this.player_.livetracker || this.player_.livetracker.atliveedge()) {
this.setattribute('aria-disabled', true);
this.addclass('vjs-at-live-edge');
this.controltext('seek to live, currently playing live');
} else {
this.setattribute('aria-disabled', false);
this.removeclass('vjs-at-live-edge');
this.controltext('seek to live, currently behind live');
}
}
/**
* on click bring us as near to the live point as possible.
* this requires that we wait for the next `live-seekable-change`
* event which will happen every segment length seconds.
*/
;
_proto.handleclick = function handleclick() {
this.player_.livetracker.seektoliveedge();
}
/**
* dispose of the element and stop tracking
*/
;
_proto.dispose = function dispose() {
if (this.player_.livetracker) {
this.off(this.player_.livetracker, 'liveedgechange', this.updateliveedgestatushandler_);
}
this.textel_ = null;
_button.prototype.dispose.call(this);
};
return seektolive;
}(button);
seektolive.prototype.controltext_ = 'seek to live, currently playing live';
component$1.registercomponent('seektolive', seektolive);
/**
* keep a number between a min and a max value
*
* @param {number} number
* the number to clamp
*
* @param {number} min
* the minimum value
* @param {number} max
* the maximum value
*
* @return {number}
* the clamped number
*/
var clamp = function clamp(number, min, max) {
number = number(number);
return math.min(max, math.max(min, isnan(number) ? min : number));
};
/**
* the base functionality for a slider. can be vertical or horizontal.
* for instance the volume bar or the seek bar on a video is a slider.
*
* @extends component
*/
var slider = /*#__pure__*/function (_component) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(slider, _component);
/**
* create an instance of this class
*
* @param {player} player
* the `player` that this class should be attached to.
*
* @param {object} [options]
* the key/value store of player options.
*/
function slider(player, options) {
var _this;
_this = _component.call(this, player, options) || this;
_this.handlemousedown_ = function (e) {
return _this.handlemousedown(e);
};
_this.handlemouseup_ = function (e) {
return _this.handlemouseup(e);
};
_this.handlekeydown_ = function (e) {
return _this.handlekeydown(e);
};
_this.handleclick_ = function (e) {
return _this.handleclick(e);
};
_this.handlemousemove_ = function (e) {
return _this.handlemousemove(e);
};
_this.update_ = function (e) {
return _this.update(e);
}; // set property names to bar to match with the child slider class is looking for
_this.bar = _this.getchild(_this.options_.barname); // set a horizontal or vertical class on the slider depending on the slider type
_this.vertical(!!_this.options_.vertical);
_this.enable();
return _this;
}
/**
* are controls are currently enabled for this slider or not.
*
* @return {boolean}
* true if controls are enabled, false otherwise
*/
var _proto = slider.prototype;
_proto.enabled = function enabled() {
return this.enabled_;
}
/**
* enable controls for this slider if they are disabled
*/
;
_proto.enable = function enable() {
if (this.enabled()) {
return;
}
this.on('mousedown', this.handlemousedown_);
this.on('touchstart', this.handlemousedown_);
this.on('keydown', this.handlekeydown_);
this.on('click', this.handleclick_); // todo: deprecated, controlsvisible does not seem to be fired
this.on(this.player_, 'controlsvisible', this.update);
if (this.playerevent) {
this.on(this.player_, this.playerevent, this.update);
}
this.removeclass('disabled');
this.setattribute('tabindex', 0);
this.enabled_ = true;
}
/**
* disable controls for this slider if they are enabled
*/
;
_proto.disable = function disable() {
if (!this.enabled()) {
return;
}
var doc = this.bar.el_.ownerdocument;
this.off('mousedown', this.handlemousedown_);
this.off('touchstart', this.handlemousedown_);
this.off('keydown', this.handlekeydown_);
this.off('click', this.handleclick_);
this.off(this.player_, 'controlsvisible', this.update_);
this.off(doc, 'mousemove', this.handlemousemove_);
this.off(doc, 'mouseup', this.handlemouseup_);
this.off(doc, 'touchmove', this.handlemousemove_);
this.off(doc, 'touchend', this.handlemouseup_);
this.removeattribute('tabindex');
this.addclass('disabled');
if (this.playerevent) {
this.off(this.player_, this.playerevent, this.update);
}
this.enabled_ = false;
}
/**
* create the `slider`s dom element.
*
* @param {string} type
* type of element to create.
*
* @param {object} [props={}]
* list of properties in object form.
*
* @param {object} [attributes={}]
* list of attributes in object form.
*
* @return {element}
* the element that gets created.
*/
;
_proto.createel = function createel(type, props, attributes) {
if (props === void 0) {
props = {};
}
if (attributes === void 0) {
attributes = {};
}
// add the slider element class to all sub classes
props.classname = props.classname + ' vjs-slider';
props = assign({
tabindex: 0
}, props);
attributes = assign({
'role': 'slider',
'aria-valuenow': 0,
'aria-valuemin': 0,
'aria-valuemax': 100,
'tabindex': 0
}, attributes);
return _component.prototype.createel.call(this, type, props, attributes);
}
/**
* handle `mousedown` or `touchstart` events on the `slider`.
*
* @param {eventtarget~event} event
* `mousedown` or `touchstart` event that triggered this function
*
* @listens mousedown
* @listens touchstart
* @fires slider#slideractive
*/
;
_proto.handlemousedown = function handlemousedown(event) {
var doc = this.bar.el_.ownerdocument;
if (event.type === 'mousedown') {
event.preventdefault();
} // do not call preventdefault() on touchstart in chrome
// to avoid console warnings. use a 'touch-action: none' style
// instead to prevent unintented scrolling.
// https://developers.google.com/web/updates/2017/01/scrolling-intervention
if (event.type === 'touchstart' && !is_chrome) {
event.preventdefault();
}
blocktextselection();
this.addclass('vjs-sliding');
/**
* triggered when the slider is in an active state
*
* @event slider#slideractive
* @type {eventtarget~event}
*/
this.trigger('slideractive');
this.on(doc, 'mousemove', this.handlemousemove_);
this.on(doc, 'mouseup', this.handlemouseup_);
this.on(doc, 'touchmove', this.handlemousemove_);
this.on(doc, 'touchend', this.handlemouseup_);
this.handlemousemove(event, true);
}
/**
* handle the `mousemove`, `touchmove`, and `mousedown` events on this `slider`.
* the `mousemove` and `touchmove` events will only only trigger this function during
* `mousedown` and `touchstart`. this is due to {@link slider#handlemousedown} and
* {@link slider#handlemouseup}.
*
* @param {eventtarget~event} event
* `mousedown`, `mousemove`, `touchstart`, or `touchmove` event that triggered
* this function
* @param {boolean} mousedown this is a flag that should be set to true if `handlemousemove` is called directly. it allows us to skip things that should not happen if coming from mouse down but should happen on regular mouse move handler. defaults to false.
*
* @listens mousemove
* @listens touchmove
*/
;
_proto.handlemousemove = function handlemousemove(event) {}
/**
* handle `mouseup` or `touchend` events on the `slider`.
*
* @param {eventtarget~event} event
* `mouseup` or `touchend` event that triggered this function.
*
* @listens touchend
* @listens mouseup
* @fires slider#sliderinactive
*/
;
_proto.handlemouseup = function handlemouseup() {
var doc = this.bar.el_.ownerdocument;
unblocktextselection();
this.removeclass('vjs-sliding');
/**
* triggered when the slider is no longer in an active state.
*
* @event slider#sliderinactive
* @type {eventtarget~event}
*/
this.trigger('sliderinactive');
this.off(doc, 'mousemove', this.handlemousemove_);
this.off(doc, 'mouseup', this.handlemouseup_);
this.off(doc, 'touchmove', this.handlemousemove_);
this.off(doc, 'touchend', this.handlemouseup_);
this.update();
}
/**
* update the progress bar of the `slider`.
*
* @return {number}
* the percentage of progress the progress bar represents as a
* number from 0 to 1.
*/
;
_proto.update = function update() {
var _this2 = this;
// in volumebar init we have a settimeout for update that pops and update
// to the end of the execution stack. the player is destroyed before then
// update will cause an error
// if there's no bar...
if (!this.el_ || !this.bar) {
return;
} // clamp progress between 0 and 1
// and only round to four decimal places, as we round to two below
var progress = this.getprogress();
if (progress === this.progress_) {
return progress;
}
this.progress_ = progress;
this.requestnamedanimationframe('slider#update', function () {
// set the new bar width or height
var sizekey = _this2.vertical() ? 'height' : 'width'; // convert to a percentage for css value
_this2.bar.el().style[sizekey] = (progress * 100).tofixed(2) + '%';
});
return progress;
}
/**
* get the percentage of the bar that should be filled
* but clamped and rounded.
*
* @return {number}
* percentage filled that the slider is
*/
;
_proto.getprogress = function getprogress() {
return number(clamp(this.getpercent(), 0, 1).tofixed(4));
}
/**
* calculate distance for slider
*
* @param {eventtarget~event} event
* the event that caused this function to run.
*
* @return {number}
* the current position of the slider.
* - position.x for vertical `slider`s
* - position.y for horizontal `slider`s
*/
;
_proto.calculatedistance = function calculatedistance(event) {
var position = getpointerposition(this.el_, event);
if (this.vertical()) {
return position.y;
}
return position.x;
}
/**
* handle a `keydown` event on the `slider`. watches for left, rigth, up, and down
* arrow keys. this function will only be called when the slider has focus. see
* {@link slider#handlefocus} and {@link slider#handleblur}.
*
* @param {eventtarget~event} event
* the `keydown` event that caused this function to run.
*
* @listens keydown
*/
;
_proto.handlekeydown = function handlekeydown(event) {
// left and down arrows
if (keycode__webpack_imported_module_3___default.a.iseventkey(event, 'left') || keycode__webpack_imported_module_3___default.a.iseventkey(event, 'down')) {
event.preventdefault();
event.stoppropagation();
this.stepback(); // up and right arrows
} else if (keycode__webpack_imported_module_3___default.a.iseventkey(event, 'right') || keycode__webpack_imported_module_3___default.a.iseventkey(event, 'up')) {
event.preventdefault();
event.stoppropagation();
this.stepforward();
} else {
// pass keydown handling up for unsupported keys
_component.prototype.handlekeydown.call(this, event);
}
}
/**
* listener for click events on slider, used to prevent clicks
* from bubbling up to parent elements like button menus.
*
* @param {object} event
* event that caused this object to run
*/
;
_proto.handleclick = function handleclick(event) {
event.stoppropagation();
event.preventdefault();
}
/**
* get/set if slider is horizontal for vertical
*
* @param {boolean} [bool]
* - true if slider is vertical,
* - false is horizontal
*
* @return {boolean}
* - true if slider is vertical, and getting
* - false if the slider is horizontal, and getting
*/
;
_proto.vertical = function vertical(bool) {
if (bool === undefined) {
return this.vertical_ || false;
}
this.vertical_ = !!bool;
if (this.vertical_) {
this.addclass('vjs-slider-vertical');
} else {
this.addclass('vjs-slider-horizontal');
}
};
return slider;
}(component$1);
component$1.registercomponent('slider', slider);
var percentify = function percentify(time, end) {
return clamp(time / end * 100, 0, 100).tofixed(2) + '%';
};
/**
* shows loading progress
*
* @extends component
*/
var loadprogressbar = /*#__pure__*/function (_component) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(loadprogressbar, _component);
/**
* creates an instance of this class.
*
* @param {player} player
* the `player` that this class should be attached to.
*
* @param {object} [options]
* the key/value store of player options.
*/
function loadprogressbar(player, options) {
var _this;
_this = _component.call(this, player, options) || this;
_this.partels_ = [];
_this.on(player, 'progress', function (e) {
return _this.update(e);
});
return _this;
}
/**
* create the `component`'s dom element
*
* @return {element}
* the element that was created.
*/
var _proto = loadprogressbar.prototype;
_proto.createel = function createel$1() {
var el = _component.prototype.createel.call(this, 'div', {
classname: 'vjs-load-progress'
});
var wrapper = createel('span', {
classname: 'vjs-control-text'
});
var loadedtext = createel('span', {
textcontent: this.localize('loaded')
});
var separator = global_document__webpack_imported_module_1___default.a.createtextnode(': ');
this.percentageel_ = createel('span', {
classname: 'vjs-control-text-loaded-percentage',
textcontent: '0%'
});
el.appendchild(wrapper);
wrapper.appendchild(loadedtext);
wrapper.appendchild(separator);
wrapper.appendchild(this.percentageel_);
return el;
};
_proto.dispose = function dispose() {
this.partels_ = null;
this.percentageel_ = null;
_component.prototype.dispose.call(this);
}
/**
* update progress bar
*
* @param {eventtarget~event} [event]
* the `progress` event that caused this function to run.
*
* @listens player#progress
*/
;
_proto.update = function update(event) {
var _this2 = this;
this.requestnamedanimationframe('loadprogressbar#update', function () {
var livetracker = _this2.player_.livetracker;
var buffered = _this2.player_.buffered();
var duration = livetracker && livetracker.islive() ? livetracker.seekableend() : _this2.player_.duration();
var bufferedend = _this2.player_.bufferedend();
var children = _this2.partels_;
var percent = percentify(bufferedend, duration);
if (_this2.percent_ !== percent) {
// update the width of the progress bar
_this2.el_.style.width = percent; // update the control-text
textcontent(_this2.percentageel_, percent);
_this2.percent_ = percent;
} // add child elements to represent the individual buffered time ranges
for (var i = 0; i < buffered.length; i++) {
var start = buffered.start(i);
var end = buffered.end(i);
var part = children[i];
if (!part) {
part = _this2.el_.appendchild(createel());
children[i] = part;
} // only update if changed
if (part.dataset.start === start && part.dataset.end === end) {
continue;
}
part.dataset.start = start;
part.dataset.end = end; // set the percent based on the width of the progress bar (bufferedend)
part.style.left = percentify(start, bufferedend);
part.style.width = percentify(end - start, bufferedend);
} // remove unused buffered range elements
for (var _i = children.length; _i > buffered.length; _i--) {
_this2.el_.removechild(children[_i - 1]);
}
children.length = buffered.length;
});
};
return loadprogressbar;
}(component$1);
component$1.registercomponent('loadprogressbar', loadprogressbar);
/**
* time tooltips display a time above the progress bar.
*
* @extends component
*/
var timetooltip = /*#__pure__*/function (_component) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(timetooltip, _component);
/**
* creates an instance of this class.
*
* @param {player} player
* the {@link player} that this class should be attached to.
*
* @param {object} [options]
* the key/value store of player options.
*/
function timetooltip(player, options) {
var _this;
_this = _component.call(this, player, options) || this;
_this.update = throttle(bind(_babel_runtime_helpers_assertthisinitialized__webpack_imported_module_4___default()(_this), _this.update), update_refresh_interval);
return _this;
}
/**
* create the time tooltip dom element
*
* @return {element}
* the element that was created.
*/
var _proto = timetooltip.prototype;
_proto.createel = function createel() {
return _component.prototype.createel.call(this, 'div', {
classname: 'vjs-time-tooltip'
}, {
'aria-hidden': 'true'
});
}
/**
* updates the position of the time tooltip relative to the `seekbar`.
*
* @param {object} seekbarrect
* the `clientrect` for the {@link seekbar} element.
*
* @param {number} seekbarpoint
* a number from 0 to 1, representing a horizontal reference point
* from the left edge of the {@link seekbar}
*/
;
_proto.update = function update(seekbarrect, seekbarpoint, content) {
var tooltiprect = findposition(this.el_);
var playerrect = getboundingclientrect(this.player_.el());
var seekbarpointpx = seekbarrect.width * seekbarpoint; // do nothing if either rect isn't available
// for example, if the player isn't in the dom for testing
if (!playerrect || !tooltiprect) {
return;
} // this is the space left of the `seekbarpoint` available within the bounds
// of the player. we calculate any gap between the left edge of the player
// and the left edge of the `seekbar` and add the number of pixels in the
// `seekbar` before hitting the `seekbarpoint`
var spaceleftofpoint = seekbarrect.left - playerrect.left + seekbarpointpx; // this is the space right of the `seekbarpoint` available within the bounds
// of the player. we calculate the number of pixels from the `seekbarpoint`
// to the right edge of the `seekbar` and add to that any gap between the
// right edge of the `seekbar` and the player.
var spacerightofpoint = seekbarrect.width - seekbarpointpx + (playerrect.right - seekbarrect.right); // this is the number of pixels by which the tooltip will need to be pulled
// further to the right to center it over the `seekbarpoint`.
var pulltooltipby = tooltiprect.width / 2; // adjust the `pulltooltipby` distance to the left or right depending on
// the results of the space calculations above.
if (spaceleftofpoint < pulltooltipby) {
pulltooltipby += pulltooltipby - spaceleftofpoint;
} else if (spacerightofpoint < pulltooltipby) {
pulltooltipby = spacerightofpoint;
} // due to the imprecision of decimal/ratio based calculations and varying
// rounding behaviors, there are cases where the spacing adjustment is off
// by a pixel or two. this adds insurance to these calculations.
if (pulltooltipby < 0) {
pulltooltipby = 0;
} else if (pulltooltipby > tooltiprect.width) {
pulltooltipby = tooltiprect.width;
} // prevent small width fluctuations within 0.4px from
// changing the value below.
// this really helps for live to prevent the play
// progress time tooltip from jittering
pulltooltipby = math.round(pulltooltipby);
this.el_.style.right = "-" + pulltooltipby + "px";
this.write(content);
}
/**
* write the time to the tooltip dom element.
*
* @param {string} content
* the formatted time for the tooltip.
*/
;
_proto.write = function write(content) {
textcontent(this.el_, content);
}
/**
* updates the position of the time tooltip relative to the `seekbar`.
*
* @param {object} seekbarrect
* the `clientrect` for the {@link seekbar} element.
*
* @param {number} seekbarpoint
* a number from 0 to 1, representing a horizontal reference point
* from the left edge of the {@link seekbar}
*
* @param {number} time
* the time to update the tooltip to, not used during live playback
*
* @param {function} cb
* a function that will be called during the request animation frame
* for tooltips that need to do additional animations from the default
*/
;
_proto.updatetime = function updatetime(seekbarrect, seekbarpoint, time, cb) {
var _this2 = this;
this.requestnamedanimationframe('timetooltip#updatetime', function () {
var content;
var duration = _this2.player_.duration();
if (_this2.player_.livetracker && _this2.player_.livetracker.islive()) {
var livewindow = _this2.player_.livetracker.livewindow();
var secondsbehind = livewindow - seekbarpoint * livewindow;
content = (secondsbehind < 1 ? '' : '-') + formattime(secondsbehind, livewindow);
} else {
content = formattime(time, duration);
}
_this2.update(seekbarrect, seekbarpoint, content);
if (cb) {
cb();
}
});
};
return timetooltip;
}(component$1);
component$1.registercomponent('timetooltip', timetooltip);
/**
* used by {@link seekbar} to display media playback progress as part of the
* {@link progresscontrol}.
*
* @extends component
*/
var playprogressbar = /*#__pure__*/function (_component) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(playprogressbar, _component);
/**
* creates an instance of this class.
*
* @param {player} player
* the {@link player} that this class should be attached to.
*
* @param {object} [options]
* the key/value store of player options.
*/
function playprogressbar(player, options) {
var _this;
_this = _component.call(this, player, options) || this;
_this.update = throttle(bind(_babel_runtime_helpers_assertthisinitialized__webpack_imported_module_4___default()(_this), _this.update), update_refresh_interval);
return _this;
}
/**
* create the the dom element for this class.
*
* @return {element}
* the element that was created.
*/
var _proto = playprogressbar.prototype;
_proto.createel = function createel() {
return _component.prototype.createel.call(this, 'div', {
classname: 'vjs-play-progress vjs-slider-bar'
}, {
'aria-hidden': 'true'
});
}
/**
* enqueues updates to its own dom as well as the dom of its
* {@link timetooltip} child.
*
* @param {object} seekbarrect
* the `clientrect` for the {@link seekbar} element.
*
* @param {number} seekbarpoint
* a number from 0 to 1, representing a horizontal reference point
* from the left edge of the {@link seekbar}
*/
;
_proto.update = function update(seekbarrect, seekbarpoint) {
var timetooltip = this.getchild('timetooltip');
if (!timetooltip) {
return;
}
var time = this.player_.scrubbing() ? this.player_.getcache().currenttime : this.player_.currenttime();
timetooltip.updatetime(seekbarrect, seekbarpoint, time);
};
return playprogressbar;
}(component$1);
/**
* default options for {@link playprogressbar}.
*
* @type {object}
* @private
*/
playprogressbar.prototype.options_ = {
children: []
}; // time tooltips should not be added to a player on mobile devices
if (!is_ios && !is_android) {
playprogressbar.prototype.options_.children.push('timetooltip');
}
component$1.registercomponent('playprogressbar', playprogressbar);
/**
* the {@link mousetimedisplay} component tracks mouse movement over the
* {@link progresscontrol}. it displays an indicator and a {@link timetooltip}
* indicating the time which is represented by a given point in the
* {@link progresscontrol}.
*
* @extends component
*/
var mousetimedisplay = /*#__pure__*/function (_component) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(mousetimedisplay, _component);
/**
* creates an instance of this class.
*
* @param {player} player
* the {@link player} that this class should be attached to.
*
* @param {object} [options]
* the key/value store of player options.
*/
function mousetimedisplay(player, options) {
var _this;
_this = _component.call(this, player, options) || this;
_this.update = throttle(bind(_babel_runtime_helpers_assertthisinitialized__webpack_imported_module_4___default()(_this), _this.update), update_refresh_interval);
return _this;
}
/**
* create the dom element for this class.
*
* @return {element}
* the element that was created.
*/
var _proto = mousetimedisplay.prototype;
_proto.createel = function createel() {
return _component.prototype.createel.call(this, 'div', {
classname: 'vjs-mouse-display'
});
}
/**
* enqueues updates to its own dom as well as the dom of its
* {@link timetooltip} child.
*
* @param {object} seekbarrect
* the `clientrect` for the {@link seekbar} element.
*
* @param {number} seekbarpoint
* a number from 0 to 1, representing a horizontal reference point
* from the left edge of the {@link seekbar}
*/
;
_proto.update = function update(seekbarrect, seekbarpoint) {
var _this2 = this;
var time = seekbarpoint * this.player_.duration();
this.getchild('timetooltip').updatetime(seekbarrect, seekbarpoint, time, function () {
_this2.el_.style.left = seekbarrect.width * seekbarpoint + "px";
});
};
return mousetimedisplay;
}(component$1);
/**
* default options for `mousetimedisplay`
*
* @type {object}
* @private
*/
mousetimedisplay.prototype.options_ = {
children: ['timetooltip']
};
component$1.registercomponent('mousetimedisplay', mousetimedisplay);
var step_seconds = 5; // the multiplier of step_seconds that pgup/pgdown move the timeline.
var page_key_multiplier = 12;
/**
* seek bar and container for the progress bars. uses {@link playprogressbar}
* as its `bar`.
*
* @extends slider
*/
var seekbar = /*#__pure__*/function (_slider) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(seekbar, _slider);
/**
* creates an instance of this class.
*
* @param {player} player
* the `player` that this class should be attached to.
*
* @param {object} [options]
* the key/value store of player options.
*/
function seekbar(player, options) {
var _this;
_this = _slider.call(this, player, options) || this;
_this.seteventhandlers_();
return _this;
}
/**
* sets the event handlers
*
* @private
*/
var _proto = seekbar.prototype;
_proto.seteventhandlers_ = function seteventhandlers_() {
var _this2 = this;
this.update_ = bind(this, this.update);
this.update = throttle(this.update_, update_refresh_interval);
this.on(this.player_, ['ended', 'durationchange', 'timeupdate'], this.update);
if (this.player_.livetracker) {
this.on(this.player_.livetracker, 'liveedgechange', this.update);
} // when playing, let's ensure we smoothly update the play progress bar
// via an interval
this.updateinterval = null;
this.enableintervalhandler_ = function (e) {
return _this2.enableinterval_(e);
};
this.disableintervalhandler_ = function (e) {
return _this2.disableinterval_(e);
};
this.on(this.player_, ['playing'], this.enableintervalhandler_);
this.on(this.player_, ['ended', 'pause', 'waiting'], this.disableintervalhandler_); // we don't need to update the play progress if the document is hidden,
// also, this causes the cpu to spike and eventually crash the page on ie11.
if ('hidden' in global_document__webpack_imported_module_1___default.a && 'visibilitystate' in global_document__webpack_imported_module_1___default.a) {
this.on(global_document__webpack_imported_module_1___default.a, 'visibilitychange', this.togglevisibility_);
}
};
_proto.togglevisibility_ = function togglevisibility_(e) {
if (global_document__webpack_imported_module_1___default.a.visibilitystate === 'hidden') {
this.cancelnamedanimationframe('seekbar#update');
this.cancelnamedanimationframe('slider#update');
this.disableinterval_(e);
} else {
if (!this.player_.ended() && !this.player_.paused()) {
this.enableinterval_();
} // we just switched back to the page and someone may be looking, so, update asap
this.update();
}
};
_proto.enableinterval_ = function enableinterval_() {
if (this.updateinterval) {
return;
}
this.updateinterval = this.setinterval(this.update, update_refresh_interval);
};
_proto.disableinterval_ = function disableinterval_(e) {
if (this.player_.livetracker && this.player_.livetracker.islive() && e && e.type !== 'ended') {
return;
}
if (!this.updateinterval) {
return;
}
this.clearinterval(this.updateinterval);
this.updateinterval = null;
}
/**
* create the `component`'s dom element
*
* @return {element}
* the element that was created.
*/
;
_proto.createel = function createel() {
return _slider.prototype.createel.call(this, 'div', {
classname: 'vjs-progress-holder'
}, {
'aria-label': this.localize('progress bar')
});
}
/**
* this function updates the play progress bar and accessibility
* attributes to whatever is passed in.
*
* @param {eventtarget~event} [event]
* the `timeupdate` or `ended` event that caused this to run.
*
* @listens player#timeupdate
*
* @return {number}
* the current percent at a number from 0-1
*/
;
_proto.update = function update(event) {
var _this3 = this;
// ignore updates while the tab is hidden
if (global_document__webpack_imported_module_1___default.a.visibilitystate === 'hidden') {
return;
}
var percent = _slider.prototype.update.call(this);
this.requestnamedanimationframe('seekbar#update', function () {
var currenttime = _this3.player_.ended() ? _this3.player_.duration() : _this3.getcurrenttime_();
var livetracker = _this3.player_.livetracker;
var duration = _this3.player_.duration();
if (livetracker && livetracker.islive()) {
duration = _this3.player_.livetracker.livecurrenttime();
}
if (_this3.percent_ !== percent) {
// machine readable value of progress bar (percentage complete)
_this3.el_.setattribute('aria-valuenow', (percent * 100).tofixed(2));
_this3.percent_ = percent;
}
if (_this3.currenttime_ !== currenttime || _this3.duration_ !== duration) {
// human readable value of progress bar (time complete)
_this3.el_.setattribute('aria-valuetext', _this3.localize('progress bar timing: currenttime={1} duration={2}', [formattime(currenttime, duration), formattime(duration, duration)], '{1} of {2}'));
_this3.currenttime_ = currenttime;
_this3.duration_ = duration;
} // update the progress bar time tooltip with the current time
if (_this3.bar) {
_this3.bar.update(getboundingclientrect(_this3.el()), _this3.getprogress());
}
});
return percent;
}
/**
* prevent livethreshold from causing seeks to seem like they
* are not happening from a user perspective.
*
* @param {number} ct
* current time to seek to
*/
;
_proto.userseek_ = function userseek_(ct) {
if (this.player_.livetracker && this.player_.livetracker.islive()) {
this.player_.livetracker.nextseekedfromuser();
}
this.player_.currenttime(ct);
}
/**
* get the value of current time but allows for smooth scrubbing,
* when player can't keep up.
*
* @return {number}
* the current time value to display
*
* @private
*/
;
_proto.getcurrenttime_ = function getcurrenttime_() {
return this.player_.scrubbing() ? this.player_.getcache().currenttime : this.player_.currenttime();
}
/**
* get the percentage of media played so far.
*
* @return {number}
* the percentage of media played so far (0 to 1).
*/
;
_proto.getpercent = function getpercent() {
var currenttime = this.getcurrenttime_();
var percent;
var livetracker = this.player_.livetracker;
if (livetracker && livetracker.islive()) {
percent = (currenttime - livetracker.seekablestart()) / livetracker.livewindow(); // prevent the percent from changing at the live edge
if (livetracker.atliveedge()) {
percent = 1;
}
} else {
percent = currenttime / this.player_.duration();
}
return percent;
}
/**
* handle mouse down on seek bar
*
* @param {eventtarget~event} event
* the `mousedown` event that caused this to run.
*
* @listens mousedown
*/
;
_proto.handlemousedown = function handlemousedown(event) {
if (!issingleleftclick(event)) {
return;
} // stop event propagation to prevent double fire in progress-control.js
event.stoppropagation();
this.videowasplaying = !this.player_.paused();
this.player_.pause();
_slider.prototype.handlemousedown.call(this, event);
}
/**
* handle mouse move on seek bar
*
* @param {eventtarget~event} event
* the `mousemove` event that caused this to run.
* @param {boolean} mousedown this is a flag that should be set to true if `handlemousemove` is called directly. it allows us to skip things that should not happen if coming from mouse down but should happen on regular mouse move handler. defaults to false
*
* @listens mousemove
*/
;
_proto.handlemousemove = function handlemousemove(event, mousedown) {
if (mousedown === void 0) {
mousedown = false;
}
if (!issingleleftclick(event)) {
return;
}
if (!mousedown && !this.player_.scrubbing()) {
this.player_.scrubbing(true);
}
var newtime;
var distance = this.calculatedistance(event);
var livetracker = this.player_.livetracker;
if (!livetracker || !livetracker.islive()) {
newtime = distance * this.player_.duration(); // don't let video end while scrubbing.
if (newtime === this.player_.duration()) {
newtime = newtime - 0.1;
}
} else {
if (distance >= 0.99) {
livetracker.seektoliveedge();
return;
}
var seekablestart = livetracker.seekablestart();
var seekableend = livetracker.livecurrenttime();
newtime = seekablestart + distance * livetracker.livewindow(); // don't let video end while scrubbing.
if (newtime >= seekableend) {
newtime = seekableend;
} // compensate for precision differences so that currenttime is not less
// than seekable start
if (newtime <= seekablestart) {
newtime = seekablestart + 0.1;
} // on android seekableend can be infinity sometimes,
// this will cause newtime to be infinity, which is
// not a valid currenttime.
if (newtime === infinity) {
return;
}
} // set new time (tell player to seek to new time)
this.userseek_(newtime);
};
_proto.enable = function enable() {
_slider.prototype.enable.call(this);
var mousetimedisplay = this.getchild('mousetimedisplay');
if (!mousetimedisplay) {
return;
}
mousetimedisplay.show();
};
_proto.disable = function disable() {
_slider.prototype.disable.call(this);
var mousetimedisplay = this.getchild('mousetimedisplay');
if (!mousetimedisplay) {
return;
}
mousetimedisplay.hide();
}
/**
* handle mouse up on seek bar
*
* @param {eventtarget~event} event
* the `mouseup` event that caused this to run.
*
* @listens mouseup
*/
;
_proto.handlemouseup = function handlemouseup(event) {
_slider.prototype.handlemouseup.call(this, event); // stop event propagation to prevent double fire in progress-control.js
if (event) {
event.stoppropagation();
}
this.player_.scrubbing(false);
/**
* trigger timeupdate because we're done seeking and the time has changed.
* this is particularly useful for if the player is paused to time the time displays.
*
* @event tech#timeupdate
* @type {eventtarget~event}
*/
this.player_.trigger({
type: 'timeupdate',
target: this,
manuallytriggered: true
});
if (this.videowasplaying) {
silencepromise(this.player_.play());
} else {
// we're done seeking and the time has changed.
// if the player is paused, make sure we display the correct time on the seek bar.
this.update_();
}
}
/**
* move more quickly fast forward for keyboard-only users
*/
;
_proto.stepforward = function stepforward() {
this.userseek_(this.player_.currenttime() + step_seconds);
}
/**
* move more quickly rewind for keyboard-only users
*/
;
_proto.stepback = function stepback() {
this.userseek_(this.player_.currenttime() - step_seconds);
}
/**
* toggles the playback state of the player
* this gets called when enter or space is used on the seekbar
*
* @param {eventtarget~event} event
* the `keydown` event that caused this function to be called
*
*/
;
_proto.handleaction = function handleaction(event) {
if (this.player_.paused()) {
this.player_.play();
} else {
this.player_.pause();
}
}
/**
* called when this seekbar has focus and a key gets pressed down.
* supports the following keys:
*
* space or enter key fire a click event
* home key moves to start of the timeline
* end key moves to end of the timeline
* digit "0" through "9" keys move to 0%, 10% ... 80%, 90% of the timeline
* pagedown key moves back a larger step than arrowdown
* pageup key moves forward a large step
*
* @param {eventtarget~event} event
* the `keydown` event that caused this function to be called.
*
* @listens keydown
*/
;
_proto.handlekeydown = function handlekeydown(event) {
var livetracker = this.player_.livetracker;
if (keycode__webpack_imported_module_3___default.a.iseventkey(event, 'space') || keycode__webpack_imported_module_3___default.a.iseventkey(event, 'enter')) {
event.preventdefault();
event.stoppropagation();
this.handleaction(event);
} else if (keycode__webpack_imported_module_3___default.a.iseventkey(event, 'home')) {
event.preventdefault();
event.stoppropagation();
this.userseek_(0);
} else if (keycode__webpack_imported_module_3___default.a.iseventkey(event, 'end')) {
event.preventdefault();
event.stoppropagation();
if (livetracker && livetracker.islive()) {
this.userseek_(livetracker.livecurrenttime());
} else {
this.userseek_(this.player_.duration());
}
} else if (/^[0-9]$/.test(keycode__webpack_imported_module_3___default()(event))) {
event.preventdefault();
event.stoppropagation();
var gotofraction = (keycode__webpack_imported_module_3___default.a.codes[keycode__webpack_imported_module_3___default()(event)] - keycode__webpack_imported_module_3___default.a.codes['0']) * 10.0 / 100.0;
if (livetracker && livetracker.islive()) {
this.userseek_(livetracker.seekablestart() + livetracker.livewindow() * gotofraction);
} else {
this.userseek_(this.player_.duration() * gotofraction);
}
} else if (keycode__webpack_imported_module_3___default.a.iseventkey(event, 'pgdn')) {
event.preventdefault();
event.stoppropagation();
this.userseek_(this.player_.currenttime() - step_seconds * page_key_multiplier);
} else if (keycode__webpack_imported_module_3___default.a.iseventkey(event, 'pgup')) {
event.preventdefault();
event.stoppropagation();
this.userseek_(this.player_.currenttime() + step_seconds * page_key_multiplier);
} else {
// pass keydown handling up for unsupported keys
_slider.prototype.handlekeydown.call(this, event);
}
};
_proto.dispose = function dispose() {
this.disableinterval_();
this.off(this.player_, ['ended', 'durationchange', 'timeupdate'], this.update);
if (this.player_.livetracker) {
this.off(this.player_.livetracker, 'liveedgechange', this.update);
}
this.off(this.player_, ['playing'], this.enableintervalhandler_);
this.off(this.player_, ['ended', 'pause', 'waiting'], this.disableintervalhandler_); // we don't need to update the play progress if the document is hidden,
// also, this causes the cpu to spike and eventually crash the page on ie11.
if ('hidden' in global_document__webpack_imported_module_1___default.a && 'visibilitystate' in global_document__webpack_imported_module_1___default.a) {
this.off(global_document__webpack_imported_module_1___default.a, 'visibilitychange', this.togglevisibility_);
}
_slider.prototype.dispose.call(this);
};
return seekbar;
}(slider);
/**
* default options for the `seekbar`
*
* @type {object}
* @private
*/
seekbar.prototype.options_ = {
children: ['loadprogressbar', 'playprogressbar'],
barname: 'playprogressbar'
}; // mousetimedisplay tooltips should not be added to a player on mobile devices
if (!is_ios && !is_android) {
seekbar.prototype.options_.children.splice(1, 0, 'mousetimedisplay');
}
component$1.registercomponent('seekbar', seekbar);
/**
* the progress control component contains the seek bar, load progress,
* and play progress.
*
* @extends component
*/
var progresscontrol = /*#__pure__*/function (_component) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(progresscontrol, _component);
/**
* creates an instance of this class.
*
* @param {player} player
* the `player` that this class should be attached to.
*
* @param {object} [options]
* the key/value store of player options.
*/
function progresscontrol(player, options) {
var _this;
_this = _component.call(this, player, options) || this;
_this.handlemousemove = throttle(bind(_babel_runtime_helpers_assertthisinitialized__webpack_imported_module_4___default()(_this), _this.handlemousemove), update_refresh_interval);
_this.throttledhandlemouseseek = throttle(bind(_babel_runtime_helpers_assertthisinitialized__webpack_imported_module_4___default()(_this), _this.handlemouseseek), update_refresh_interval);
_this.handlemouseuphandler_ = function (e) {
return _this.handlemouseup(e);
};
_this.handlemousedownhandler_ = function (e) {
return _this.handlemousedown(e);
};
_this.enable();
return _this;
}
/**
* create the `component`'s dom element
*
* @return {element}
* the element that was created.
*/
var _proto = progresscontrol.prototype;
_proto.createel = function createel() {
return _component.prototype.createel.call(this, 'div', {
classname: 'vjs-progress-control vjs-control'
});
}
/**
* when the mouse moves over the `progresscontrol`, the pointer position
* gets passed down to the `mousetimedisplay` component.
*
* @param {eventtarget~event} event
* the `mousemove` event that caused this function to run.
*
* @listen mousemove
*/
;
_proto.handlemousemove = function handlemousemove(event) {
var seekbar = this.getchild('seekbar');
if (!seekbar) {
return;
}
var playprogressbar = seekbar.getchild('playprogressbar');
var mousetimedisplay = seekbar.getchild('mousetimedisplay');
if (!playprogressbar && !mousetimedisplay) {
return;
}
var seekbarel = seekbar.el();
var seekbarrect = findposition(seekbarel);
var seekbarpoint = getpointerposition(seekbarel, event).x; // the default skin has a gap on either side of the `seekbar`. this means
// that it's possible to trigger this behavior outside the boundaries of
// the `seekbar`. this ensures we stay within it at all times.
seekbarpoint = clamp(seekbarpoint, 0, 1);
if (mousetimedisplay) {
mousetimedisplay.update(seekbarrect, seekbarpoint);
}
if (playprogressbar) {
playprogressbar.update(seekbarrect, seekbar.getprogress());
}
}
/**
* a throttled version of the {@link progresscontrol#handlemouseseek} listener.
*
* @method progresscontrol#throttledhandlemouseseek
* @param {eventtarget~event} event
* the `mousemove` event that caused this function to run.
*
* @listen mousemove
* @listen touchmove
*/
/**
* handle `mousemove` or `touchmove` events on the `progresscontrol`.
*
* @param {eventtarget~event} event
* `mousedown` or `touchstart` event that triggered this function
*
* @listens mousemove
* @listens touchmove
*/
;
_proto.handlemouseseek = function handlemouseseek(event) {
var seekbar = this.getchild('seekbar');
if (seekbar) {
seekbar.handlemousemove(event);
}
}
/**
* are controls are currently enabled for this progress control.
*
* @return {boolean}
* true if controls are enabled, false otherwise
*/
;
_proto.enabled = function enabled() {
return this.enabled_;
}
/**
* disable all controls on the progress control and its children
*/
;
_proto.disable = function disable() {
this.children().foreach(function (child) {
return child.disable && child.disable();
});
if (!this.enabled()) {
return;
}
this.off(['mousedown', 'touchstart'], this.handlemousedownhandler_);
this.off(this.el_, 'mousemove', this.handlemousemove);
this.removelistenersaddedonmousedownandtouchstart();
this.addclass('disabled');
this.enabled_ = false; // restore normal playback state if controls are disabled while scrubbing
if (this.player_.scrubbing()) {
var seekbar = this.getchild('seekbar');
this.player_.scrubbing(false);
if (seekbar.videowasplaying) {
silencepromise(this.player_.play());
}
}
}
/**
* enable all controls on the progress control and its children
*/
;
_proto.enable = function enable() {
this.children().foreach(function (child) {
return child.enable && child.enable();
});
if (this.enabled()) {
return;
}
this.on(['mousedown', 'touchstart'], this.handlemousedownhandler_);
this.on(this.el_, 'mousemove', this.handlemousemove);
this.removeclass('disabled');
this.enabled_ = true;
}
/**
* cleanup listeners after the user finishes interacting with the progress controls
*/
;
_proto.removelistenersaddedonmousedownandtouchstart = function removelistenersaddedonmousedownandtouchstart() {
var doc = this.el_.ownerdocument;
this.off(doc, 'mousemove', this.throttledhandlemouseseek);
this.off(doc, 'touchmove', this.throttledhandlemouseseek);
this.off(doc, 'mouseup', this.handlemouseuphandler_);
this.off(doc, 'touchend', this.handlemouseuphandler_);
}
/**
* handle `mousedown` or `touchstart` events on the `progresscontrol`.
*
* @param {eventtarget~event} event
* `mousedown` or `touchstart` event that triggered this function
*
* @listens mousedown
* @listens touchstart
*/
;
_proto.handlemousedown = function handlemousedown(event) {
var doc = this.el_.ownerdocument;
var seekbar = this.getchild('seekbar');
if (seekbar) {
seekbar.handlemousedown(event);
}
this.on(doc, 'mousemove', this.throttledhandlemouseseek);
this.on(doc, 'touchmove', this.throttledhandlemouseseek);
this.on(doc, 'mouseup', this.handlemouseuphandler_);
this.on(doc, 'touchend', this.handlemouseuphandler_);
}
/**
* handle `mouseup` or `touchend` events on the `progresscontrol`.
*
* @param {eventtarget~event} event
* `mouseup` or `touchend` event that triggered this function.
*
* @listens touchend
* @listens mouseup
*/
;
_proto.handlemouseup = function handlemouseup(event) {
var seekbar = this.getchild('seekbar');
if (seekbar) {
seekbar.handlemouseup(event);
}
this.removelistenersaddedonmousedownandtouchstart();
};
return progresscontrol;
}(component$1);
/**
* default options for `progresscontrol`
*
* @type {object}
* @private
*/
progresscontrol.prototype.options_ = {
children: ['seekbar']
};
component$1.registercomponent('progresscontrol', progresscontrol);
/**
* toggle picture-in-picture mode
*
* @extends button
*/
var pictureinpicturetoggle = /*#__pure__*/function (_button) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(pictureinpicturetoggle, _button);
/**
* creates an instance of this class.
*
* @param {player} player
* the `player` that this class should be attached to.
*
* @param {object} [options]
* the key/value store of player options.
*
* @listens player#enterpictureinpicture
* @listens player#leavepictureinpicture
*/
function pictureinpicturetoggle(player, options) {
var _this;
_this = _button.call(this, player, options) || this;
_this.on(player, ['enterpictureinpicture', 'leavepictureinpicture'], function (e) {
return _this.handlepictureinpicturechange(e);
});
_this.on(player, ['disablepictureinpicturechanged', 'loadedmetadata'], function (e) {
return _this.handlepictureinpictureenabledchange(e);
});
_this.on(player, ['loadedmetadata', 'audioonlymodechange', 'audiopostermodechange'], function () {
// this audio detection will not detect hls or dash audio-only streams because there was no reliable way to detect them at the time
var issourceaudio = player.currenttype().substring(0, 5) === 'audio';
if (issourceaudio || player.audiopostermode() || player.audioonlymode()) {
if (player.isinpictureinpicture()) {
player.exitpictureinpicture();
}
_this.hide();
} else {
_this.show();
}
}); // todo: deactivate button on player emptied event.
_this.disable();
return _this;
}
/**
* builds the default dom `classname`.
*
* @return {string}
* the dom `classname` for this object.
*/
var _proto = pictureinpicturetoggle.prototype;
_proto.buildcssclass = function buildcssclass() {
return "vjs-picture-in-picture-control " + _button.prototype.buildcssclass.call(this);
}
/**
* enables or disables button based on document.pictureinpictureenabled property value
* or on value returned by player.disablepictureinpicture() method.
*/
;
_proto.handlepictureinpictureenabledchange = function handlepictureinpictureenabledchange() {
if (global_document__webpack_imported_module_1___default.a.pictureinpictureenabled && this.player_.disablepictureinpicture() === false) {
this.enable();
} else {
this.disable();
}
}
/**
* handles enterpictureinpicture and leavepictureinpicture on the player and change control text accordingly.
*
* @param {eventtarget~event} [event]
* the {@link player#enterpictureinpicture} or {@link player#leavepictureinpicture} event that caused this function to be
* called.
*
* @listens player#enterpictureinpicture
* @listens player#leavepictureinpicture
*/
;
_proto.handlepictureinpicturechange = function handlepictureinpicturechange(event) {
if (this.player_.isinpictureinpicture()) {
this.controltext('exit picture-in-picture');
} else {
this.controltext('picture-in-picture');
}
this.handlepictureinpictureenabledchange();
}
/**
* this gets called when an `pictureinpicturetoggle` is "clicked". see
* {@link clickablecomponent} for more detailed information on what a click can be.
*
* @param {eventtarget~event} [event]
* the `keydown`, `tap`, or `click` event that caused this function to be
* called.
*
* @listens tap
* @listens click
*/
;
_proto.handleclick = function handleclick(event) {
if (!this.player_.isinpictureinpicture()) {
this.player_.requestpictureinpicture();
} else {
this.player_.exitpictureinpicture();
}
};
return pictureinpicturetoggle;
}(button);
/**
* the text that should display over the `pictureinpicturetoggle`s controls. added for localization.
*
* @type {string}
* @private
*/
pictureinpicturetoggle.prototype.controltext_ = 'picture-in-picture';
component$1.registercomponent('pictureinpicturetoggle', pictureinpicturetoggle);
/**
* toggle fullscreen video
*
* @extends button
*/
var fullscreentoggle = /*#__pure__*/function (_button) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(fullscreentoggle, _button);
/**
* creates an instance of this class.
*
* @param {player} player
* the `player` that this class should be attached to.
*
* @param {object} [options]
* the key/value store of player options.
*/
function fullscreentoggle(player, options) {
var _this;
_this = _button.call(this, player, options) || this;
_this.on(player, 'fullscreenchange', function (e) {
return _this.handlefullscreenchange(e);
});
if (global_document__webpack_imported_module_1___default.a[player.fsapi_.fullscreenenabled] === false) {
_this.disable();
}
return _this;
}
/**
* builds the default dom `classname`.
*
* @return {string}
* the dom `classname` for this object.
*/
var _proto = fullscreentoggle.prototype;
_proto.buildcssclass = function buildcssclass() {
return "vjs-fullscreen-control " + _button.prototype.buildcssclass.call(this);
}
/**
* handles fullscreenchange on the player and change control text accordingly.
*
* @param {eventtarget~event} [event]
* the {@link player#fullscreenchange} event that caused this function to be
* called.
*
* @listens player#fullscreenchange
*/
;
_proto.handlefullscreenchange = function handlefullscreenchange(event) {
if (this.player_.isfullscreen()) {
this.controltext('non-fullscreen');
} else {
this.controltext('fullscreen');
}
}
/**
* this gets called when an `fullscreentoggle` is "clicked". see
* {@link clickablecomponent} for more detailed information on what a click can be.
*
* @param {eventtarget~event} [event]
* the `keydown`, `tap`, or `click` event that caused this function to be
* called.
*
* @listens tap
* @listens click
*/
;
_proto.handleclick = function handleclick(event) {
if (!this.player_.isfullscreen()) {
this.player_.requestfullscreen();
} else {
this.player_.exitfullscreen();
}
};
return fullscreentoggle;
}(button);
/**
* the text that should display over the `fullscreentoggle`s controls. added for localization.
*
* @type {string}
* @private
*/
fullscreentoggle.prototype.controltext_ = 'fullscreen';
component$1.registercomponent('fullscreentoggle', fullscreentoggle);
/**
* check if volume control is supported and if it isn't hide the
* `component` that was passed using the `vjs-hidden` class.
*
* @param {component} self
* the component that should be hidden if volume is unsupported
*
* @param {player} player
* a reference to the player
*
* @private
*/
var checkvolumesupport = function checkvolumesupport(self, player) {
// hide volume controls when they're not supported by the current tech
if (player.tech_ && !player.tech_.featuresvolumecontrol) {
self.addclass('vjs-hidden');
}
self.on(player, 'loadstart', function () {
if (!player.tech_.featuresvolumecontrol) {
self.addclass('vjs-hidden');
} else {
self.removeclass('vjs-hidden');
}
});
};
/**
* shows volume level
*
* @extends component
*/
var volumelevel = /*#__pure__*/function (_component) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(volumelevel, _component);
function volumelevel() {
return _component.apply(this, arguments) || this;
}
var _proto = volumelevel.prototype;
/**
* create the `component`'s dom element
*
* @return {element}
* the element that was created.
*/
_proto.createel = function createel() {
var el = _component.prototype.createel.call(this, 'div', {
classname: 'vjs-volume-level'
});
el.appendchild(_component.prototype.createel.call(this, 'span', {
classname: 'vjs-control-text'
}));
return el;
};
return volumelevel;
}(component$1);
component$1.registercomponent('volumelevel', volumelevel);
/**
* volume level tooltips display a volume above or side by side the volume bar.
*
* @extends component
*/
var volumeleveltooltip = /*#__pure__*/function (_component) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(volumeleveltooltip, _component);
/**
* creates an instance of this class.
*
* @param {player} player
* the {@link player} that this class should be attached to.
*
* @param {object} [options]
* the key/value store of player options.
*/
function volumeleveltooltip(player, options) {
var _this;
_this = _component.call(this, player, options) || this;
_this.update = throttle(bind(_babel_runtime_helpers_assertthisinitialized__webpack_imported_module_4___default()(_this), _this.update), update_refresh_interval);
return _this;
}
/**
* create the volume tooltip dom element
*
* @return {element}
* the element that was created.
*/
var _proto = volumeleveltooltip.prototype;
_proto.createel = function createel() {
return _component.prototype.createel.call(this, 'div', {
classname: 'vjs-volume-tooltip'
}, {
'aria-hidden': 'true'
});
}
/**
* updates the position of the tooltip relative to the `volumebar` and
* its content text.
*
* @param {object} rangebarrect
* the `clientrect` for the {@link volumebar} element.
*
* @param {number} rangebarpoint
* a number from 0 to 1, representing a horizontal/vertical reference point
* from the left edge of the {@link volumebar}
*
* @param {boolean} vertical
* referees to the volume control position
* in the control bar{@link volumecontrol}
*
*/
;
_proto.update = function update(rangebarrect, rangebarpoint, vertical, content) {
if (!vertical) {
var tooltiprect = getboundingclientrect(this.el_);
var playerrect = getboundingclientrect(this.player_.el());
var volumebarpointpx = rangebarrect.width * rangebarpoint;
if (!playerrect || !tooltiprect) {
return;
}
var spaceleftofpoint = rangebarrect.left - playerrect.left + volumebarpointpx;
var spacerightofpoint = rangebarrect.width - volumebarpointpx + (playerrect.right - rangebarrect.right);
var pulltooltipby = tooltiprect.width / 2;
if (spaceleftofpoint < pulltooltipby) {
pulltooltipby += pulltooltipby - spaceleftofpoint;
} else if (spacerightofpoint < pulltooltipby) {
pulltooltipby = spacerightofpoint;
}
if (pulltooltipby < 0) {
pulltooltipby = 0;
} else if (pulltooltipby > tooltiprect.width) {
pulltooltipby = tooltiprect.width;
}
this.el_.style.right = "-" + pulltooltipby + "px";
}
this.write(content + "%");
}
/**
* write the volume to the tooltip dom element.
*
* @param {string} content
* the formatted volume for the tooltip.
*/
;
_proto.write = function write(content) {
textcontent(this.el_, content);
}
/**
* updates the position of the volume tooltip relative to the `volumebar`.
*
* @param {object} rangebarrect
* the `clientrect` for the {@link volumebar} element.
*
* @param {number} rangebarpoint
* a number from 0 to 1, representing a horizontal/vertical reference point
* from the left edge of the {@link volumebar}
*
* @param {boolean} vertical
* referees to the volume control position
* in the control bar{@link volumecontrol}
*
* @param {number} volume
* the volume level to update the tooltip to
*
* @param {function} cb
* a function that will be called during the request animation frame
* for tooltips that need to do additional animations from the default
*/
;
_proto.updatevolume = function updatevolume(rangebarrect, rangebarpoint, vertical, volume, cb) {
var _this2 = this;
this.requestnamedanimationframe('volumeleveltooltip#updatevolume', function () {
_this2.update(rangebarrect, rangebarpoint, vertical, volume.tofixed(0));
if (cb) {
cb();
}
});
};
return volumeleveltooltip;
}(component$1);
component$1.registercomponent('volumeleveltooltip', volumeleveltooltip);
/**
* the {@link mousevolumeleveldisplay} component tracks mouse movement over the
* {@link volumecontrol}. it displays an indicator and a {@link volumeleveltooltip}
* indicating the volume level which is represented by a given point in the
* {@link volumebar}.
*
* @extends component
*/
var mousevolumeleveldisplay = /*#__pure__*/function (_component) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(mousevolumeleveldisplay, _component);
/**
* creates an instance of this class.
*
* @param {player} player
* the {@link player} that this class should be attached to.
*
* @param {object} [options]
* the key/value store of player options.
*/
function mousevolumeleveldisplay(player, options) {
var _this;
_this = _component.call(this, player, options) || this;
_this.update = throttle(bind(_babel_runtime_helpers_assertthisinitialized__webpack_imported_module_4___default()(_this), _this.update), update_refresh_interval);
return _this;
}
/**
* create the dom element for this class.
*
* @return {element}
* the element that was created.
*/
var _proto = mousevolumeleveldisplay.prototype;
_proto.createel = function createel() {
return _component.prototype.createel.call(this, 'div', {
classname: 'vjs-mouse-display'
});
}
/**
* enquires updates to its own dom as well as the dom of its
* {@link volumeleveltooltip} child.
*
* @param {object} rangebarrect
* the `clientrect` for the {@link volumebar} element.
*
* @param {number} rangebarpoint
* a number from 0 to 1, representing a horizontal/vertical reference point
* from the left edge of the {@link volumebar}
*
* @param {boolean} vertical
* referees to the volume control position
* in the control bar{@link volumecontrol}
*
*/
;
_proto.update = function update(rangebarrect, rangebarpoint, vertical) {
var _this2 = this;
var volume = 100 * rangebarpoint;
this.getchild('volumeleveltooltip').updatevolume(rangebarrect, rangebarpoint, vertical, volume, function () {
if (vertical) {
_this2.el_.style.bottom = rangebarrect.height * rangebarpoint + "px";
} else {
_this2.el_.style.left = rangebarrect.width * rangebarpoint + "px";
}
});
};
return mousevolumeleveldisplay;
}(component$1);
/**
* default options for `mousevolumeleveldisplay`
*
* @type {object}
* @private
*/
mousevolumeleveldisplay.prototype.options_ = {
children: ['volumeleveltooltip']
};
component$1.registercomponent('mousevolumeleveldisplay', mousevolumeleveldisplay);
/**
* the bar that contains the volume level and can be clicked on to adjust the level
*
* @extends slider
*/
var volumebar = /*#__pure__*/function (_slider) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(volumebar, _slider);
/**
* creates an instance of this class.
*
* @param {player} player
* the `player` that this class should be attached to.
*
* @param {object} [options]
* the key/value store of player options.
*/
function volumebar(player, options) {
var _this;
_this = _slider.call(this, player, options) || this;
_this.on('slideractive', function (e) {
return _this.updatelastvolume_(e);
});
_this.on(player, 'volumechange', function (e) {
return _this.updateariaattributes(e);
});
player.ready(function () {
return _this.updateariaattributes();
});
return _this;
}
/**
* create the `component`'s dom element
*
* @return {element}
* the element that was created.
*/
var _proto = volumebar.prototype;
_proto.createel = function createel() {
return _slider.prototype.createel.call(this, 'div', {
classname: 'vjs-volume-bar vjs-slider-bar'
}, {
'aria-label': this.localize('volume level'),
'aria-live': 'polite'
});
}
/**
* handle mouse down on volume bar
*
* @param {eventtarget~event} event
* the `mousedown` event that caused this to run.
*
* @listens mousedown
*/
;
_proto.handlemousedown = function handlemousedown(event) {
if (!issingleleftclick(event)) {
return;
}
_slider.prototype.handlemousedown.call(this, event);
}
/**
* handle movement events on the {@link volumemenubutton}.
*
* @param {eventtarget~event} event
* the event that caused this function to run.
*
* @listens mousemove
*/
;
_proto.handlemousemove = function handlemousemove(event) {
var mousevolumeleveldisplay = this.getchild('mousevolumeleveldisplay');
if (mousevolumeleveldisplay) {
var volumebarel = this.el();
var volumebarrect = getboundingclientrect(volumebarel);
var vertical = this.vertical();
var volumebarpoint = getpointerposition(volumebarel, event);
volumebarpoint = vertical ? volumebarpoint.y : volumebarpoint.x; // the default skin has a gap on either side of the `volumebar`. this means
// that it's possible to trigger this behavior outside the boundaries of
// the `volumebar`. this ensures we stay within it at all times.
volumebarpoint = clamp(volumebarpoint, 0, 1);
mousevolumeleveldisplay.update(volumebarrect, volumebarpoint, vertical);
}
if (!issingleleftclick(event)) {
return;
}
this.checkmuted();
this.player_.volume(this.calculatedistance(event));
}
/**
* if the player is muted unmute it.
*/
;
_proto.checkmuted = function checkmuted() {
if (this.player_.muted()) {
this.player_.muted(false);
}
}
/**
* get percent of volume level
*
* @return {number}
* volume level percent as a decimal number.
*/
;
_proto.getpercent = function getpercent() {
if (this.player_.muted()) {
return 0;
}
return this.player_.volume();
}
/**
* increase volume level for keyboard users
*/
;
_proto.stepforward = function stepforward() {
this.checkmuted();
this.player_.volume(this.player_.volume() + 0.1);
}
/**
* decrease volume level for keyboard users
*/
;
_proto.stepback = function stepback() {
this.checkmuted();
this.player_.volume(this.player_.volume() - 0.1);
}
/**
* update aria accessibility attributes
*
* @param {eventtarget~event} [event]
* the `volumechange` event that caused this function to run.
*
* @listens player#volumechange
*/
;
_proto.updateariaattributes = function updateariaattributes(event) {
var ariavalue = this.player_.muted() ? 0 : this.volumeaspercentage_();
this.el_.setattribute('aria-valuenow', ariavalue);
this.el_.setattribute('aria-valuetext', ariavalue + '%');
}
/**
* returns the current value of the player volume as a percentage
*
* @private
*/
;
_proto.volumeaspercentage_ = function volumeaspercentage_() {
return math.round(this.player_.volume() * 100);
}
/**
* when user starts dragging the volumebar, store the volume and listen for
* the end of the drag. when the drag ends, if the volume was set to zero,
* set lastvolume to the stored volume.
*
* @listens slideractive
* @private
*/
;
_proto.updatelastvolume_ = function updatelastvolume_() {
var _this2 = this;
var volumebeforedrag = this.player_.volume();
this.one('sliderinactive', function () {
if (_this2.player_.volume() === 0) {
_this2.player_.lastvolume_(volumebeforedrag);
}
});
};
return volumebar;
}(slider);
/**
* default options for the `volumebar`
*
* @type {object}
* @private
*/
volumebar.prototype.options_ = {
children: ['volumelevel'],
barname: 'volumelevel'
}; // mousevolumeleveldisplay tooltip should not be added to a player on mobile devices
if (!is_ios && !is_android) {
volumebar.prototype.options_.children.splice(0, 0, 'mousevolumeleveldisplay');
}
/**
* call the update event for this slider when this event happens on the player.
*
* @type {string}
*/
volumebar.prototype.playerevent = 'volumechange';
component$1.registercomponent('volumebar', volumebar);
/**
* the component for controlling the volume level
*
* @extends component
*/
var volumecontrol = /*#__pure__*/function (_component) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(volumecontrol, _component);
/**
* creates an instance of this class.
*
* @param {player} player
* the `player` that this class should be attached to.
*
* @param {object} [options={}]
* the key/value store of player options.
*/
function volumecontrol(player, options) {
var _this;
if (options === void 0) {
options = {};
}
options.vertical = options.vertical || false; // pass the vertical option down to the volumebar if
// the volumebar is turned on.
if (typeof options.volumebar === 'undefined' || isplain(options.volumebar)) {
options.volumebar = options.volumebar || {};
options.volumebar.vertical = options.vertical;
}
_this = _component.call(this, player, options) || this; // hide this control if volume support is missing
checkvolumesupport(_babel_runtime_helpers_assertthisinitialized__webpack_imported_module_4___default()(_this), player);
_this.throttledhandlemousemove = throttle(bind(_babel_runtime_helpers_assertthisinitialized__webpack_imported_module_4___default()(_this), _this.handlemousemove), update_refresh_interval);
_this.handlemouseuphandler_ = function (e) {
return _this.handlemouseup(e);
};
_this.on('mousedown', function (e) {
return _this.handlemousedown(e);
});
_this.on('touchstart', function (e) {
return _this.handlemousedown(e);
});
_this.on('mousemove', function (e) {
return _this.handlemousemove(e);
}); // while the slider is active (the mouse has been pressed down and
// is dragging) or in focus we do not want to hide the volumebar
_this.on(_this.volumebar, ['focus', 'slideractive'], function () {
_this.volumebar.addclass('vjs-slider-active');
_this.addclass('vjs-slider-active');
_this.trigger('slideractive');
});
_this.on(_this.volumebar, ['blur', 'sliderinactive'], function () {
_this.volumebar.removeclass('vjs-slider-active');
_this.removeclass('vjs-slider-active');
_this.trigger('sliderinactive');
});
return _this;
}
/**
* create the `component`'s dom element
*
* @return {element}
* the element that was created.
*/
var _proto = volumecontrol.prototype;
_proto.createel = function createel() {
var orientationclass = 'vjs-volume-horizontal';
if (this.options_.vertical) {
orientationclass = 'vjs-volume-vertical';
}
return _component.prototype.createel.call(this, 'div', {
classname: "vjs-volume-control vjs-control " + orientationclass
});
}
/**
* handle `mousedown` or `touchstart` events on the `volumecontrol`.
*
* @param {eventtarget~event} event
* `mousedown` or `touchstart` event that triggered this function
*
* @listens mousedown
* @listens touchstart
*/
;
_proto.handlemousedown = function handlemousedown(event) {
var doc = this.el_.ownerdocument;
this.on(doc, 'mousemove', this.throttledhandlemousemove);
this.on(doc, 'touchmove', this.throttledhandlemousemove);
this.on(doc, 'mouseup', this.handlemouseuphandler_);
this.on(doc, 'touchend', this.handlemouseuphandler_);
}
/**
* handle `mouseup` or `touchend` events on the `volumecontrol`.
*
* @param {eventtarget~event} event
* `mouseup` or `touchend` event that triggered this function.
*
* @listens touchend
* @listens mouseup
*/
;
_proto.handlemouseup = function handlemouseup(event) {
var doc = this.el_.ownerdocument;
this.off(doc, 'mousemove', this.throttledhandlemousemove);
this.off(doc, 'touchmove', this.throttledhandlemousemove);
this.off(doc, 'mouseup', this.handlemouseuphandler_);
this.off(doc, 'touchend', this.handlemouseuphandler_);
}
/**
* handle `mousedown` or `touchstart` events on the `volumecontrol`.
*
* @param {eventtarget~event} event
* `mousedown` or `touchstart` event that triggered this function
*
* @listens mousedown
* @listens touchstart
*/
;
_proto.handlemousemove = function handlemousemove(event) {
this.volumebar.handlemousemove(event);
};
return volumecontrol;
}(component$1);
/**
* default options for the `volumecontrol`
*
* @type {object}
* @private
*/
volumecontrol.prototype.options_ = {
children: ['volumebar']
};
component$1.registercomponent('volumecontrol', volumecontrol);
/**
* check if muting volume is supported and if it isn't hide the mute toggle
* button.
*
* @param {component} self
* a reference to the mute toggle button
*
* @param {player} player
* a reference to the player
*
* @private
*/
var checkmutesupport = function checkmutesupport(self, player) {
// hide mute toggle button if it's not supported by the current tech
if (player.tech_ && !player.tech_.featuresmutecontrol) {
self.addclass('vjs-hidden');
}
self.on(player, 'loadstart', function () {
if (!player.tech_.featuresmutecontrol) {
self.addclass('vjs-hidden');
} else {
self.removeclass('vjs-hidden');
}
});
};
/**
* a button component for muting the audio.
*
* @extends button
*/
var mutetoggle = /*#__pure__*/function (_button) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(mutetoggle, _button);
/**
* creates an instance of this class.
*
* @param {player} player
* the `player` that this class should be attached to.
*
* @param {object} [options]
* the key/value store of player options.
*/
function mutetoggle(player, options) {
var _this;
_this = _button.call(this, player, options) || this; // hide this control if volume support is missing
checkmutesupport(_babel_runtime_helpers_assertthisinitialized__webpack_imported_module_4___default()(_this), player);
_this.on(player, ['loadstart', 'volumechange'], function (e) {
return _this.update(e);
});
return _this;
}
/**
* builds the default dom `classname`.
*
* @return {string}
* the dom `classname` for this object.
*/
var _proto = mutetoggle.prototype;
_proto.buildcssclass = function buildcssclass() {
return "vjs-mute-control " + _button.prototype.buildcssclass.call(this);
}
/**
* this gets called when an `mutetoggle` is "clicked". see
* {@link clickablecomponent} for more detailed information on what a click can be.
*
* @param {eventtarget~event} [event]
* the `keydown`, `tap`, or `click` event that caused this function to be
* called.
*
* @listens tap
* @listens click
*/
;
_proto.handleclick = function handleclick(event) {
var vol = this.player_.volume();
var lastvolume = this.player_.lastvolume_();
if (vol === 0) {
var volumetoset = lastvolume < 0.1 ? 0.1 : lastvolume;
this.player_.volume(volumetoset);
this.player_.muted(false);
} else {
this.player_.muted(this.player_.muted() ? false : true);
}
}
/**
* update the `mutetoggle` button based on the state of `volume` and `muted`
* on the player.
*
* @param {eventtarget~event} [event]
* the {@link player#loadstart} event if this function was called
* through an event.
*
* @listens player#loadstart
* @listens player#volumechange
*/
;
_proto.update = function update(event) {
this.updateicon_();
this.updatecontroltext_();
}
/**
* update the appearance of the `mutetoggle` icon.
*
* possible states (given `level` variable below):
* - 0: crossed out
* - 1: zero bars of volume
* - 2: one bar of volume
* - 3: two bars of volume
*
* @private
*/
;
_proto.updateicon_ = function updateicon_() {
var vol = this.player_.volume();
var level = 3; // in ios when a player is loaded with muted attribute
// and volume is changed with a native mute button
// we want to make sure muted state is updated
if (is_ios && this.player_.tech_ && this.player_.tech_.el_) {
this.player_.muted(this.player_.tech_.el_.muted);
}
if (vol === 0 || this.player_.muted()) {
level = 0;
} else if (vol < 0.33) {
level = 1;
} else if (vol < 0.67) {
level = 2;
} // todo improve muted icon classes
for (var i = 0; i < 4; i++) {
removeclass(this.el_, "vjs-vol-" + i);
}
addclass(this.el_, "vjs-vol-" + level);
}
/**
* if `muted` has changed on the player, update the control text
* (`title` attribute on `vjs-mute-control` element and content of
* `vjs-control-text` element).
*
* @private
*/
;
_proto.updatecontroltext_ = function updatecontroltext_() {
var soundoff = this.player_.muted() || this.player_.volume() === 0;
var text = soundoff ? 'unmute' : 'mute';
if (this.controltext() !== text) {
this.controltext(text);
}
};
return mutetoggle;
}(button);
/**
* the text that should display over the `mutetoggle`s controls. added for localization.
*
* @type {string}
* @private
*/
mutetoggle.prototype.controltext_ = 'mute';
component$1.registercomponent('mutetoggle', mutetoggle);
/**
* a component to contain the mutetoggle and volumecontrol so that
* they can work together.
*
* @extends component
*/
var volumepanel = /*#__pure__*/function (_component) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(volumepanel, _component);
/**
* creates an instance of this class.
*
* @param {player} player
* the `player` that this class should be attached to.
*
* @param {object} [options={}]
* the key/value store of player options.
*/
function volumepanel(player, options) {
var _this;
if (options === void 0) {
options = {};
}
if (typeof options.inline !== 'undefined') {
options.inline = options.inline;
} else {
options.inline = true;
} // pass the inline option down to the volumecontrol as vertical if
// the volumecontrol is on.
if (typeof options.volumecontrol === 'undefined' || isplain(options.volumecontrol)) {
options.volumecontrol = options.volumecontrol || {};
options.volumecontrol.vertical = !options.inline;
}
_this = _component.call(this, player, options) || this; // this handler is used by mouse handler methods below
_this.handlekeypresshandler_ = function (e) {
return _this.handlekeypress(e);
};
_this.on(player, ['loadstart'], function (e) {
return _this.volumepanelstate_(e);
});
_this.on(_this.mutetoggle, 'keyup', function (e) {
return _this.handlekeypress(e);
});
_this.on(_this.volumecontrol, 'keyup', function (e) {
return _this.handlevolumecontrolkeyup(e);
});
_this.on('keydown', function (e) {
return _this.handlekeypress(e);
});
_this.on('mouseover', function (e) {
return _this.handlemouseover(e);
});
_this.on('mouseout', function (e) {
return _this.handlemouseout(e);
}); // while the slider is active (the mouse has been pressed down and
// is dragging) we do not want to hide the volumebar
_this.on(_this.volumecontrol, ['slideractive'], _this.slideractive_);
_this.on(_this.volumecontrol, ['sliderinactive'], _this.sliderinactive_);
return _this;
}
/**
* add vjs-slider-active class to the volumepanel
*
* @listens volumecontrol#slideractive
* @private
*/
var _proto = volumepanel.prototype;
_proto.slideractive_ = function slideractive_() {
this.addclass('vjs-slider-active');
}
/**
* removes vjs-slider-active class to the volumepanel
*
* @listens volumecontrol#sliderinactive
* @private
*/
;
_proto.sliderinactive_ = function sliderinactive_() {
this.removeclass('vjs-slider-active');
}
/**
* adds vjs-hidden or vjs-mute-toggle-only to the volumepanel
* depending on mutetoggle and volumecontrol state
*
* @listens player#loadstart
* @private
*/
;
_proto.volumepanelstate_ = function volumepanelstate_() {
// hide volume panel if neither volume control or mute toggle
// are displayed
if (this.volumecontrol.hasclass('vjs-hidden') && this.mutetoggle.hasclass('vjs-hidden')) {
this.addclass('vjs-hidden');
} // if only mute toggle is visible we don't want
// volume panel expanding when hovered or active
if (this.volumecontrol.hasclass('vjs-hidden') && !this.mutetoggle.hasclass('vjs-hidden')) {
this.addclass('vjs-mute-toggle-only');
}
}
/**
* create the `component`'s dom element
*
* @return {element}
* the element that was created.
*/
;
_proto.createel = function createel() {
var orientationclass = 'vjs-volume-panel-horizontal';
if (!this.options_.inline) {
orientationclass = 'vjs-volume-panel-vertical';
}
return _component.prototype.createel.call(this, 'div', {
classname: "vjs-volume-panel vjs-control " + orientationclass
});
}
/**
* dispose of the `volume-panel` and all child components.
*/
;
_proto.dispose = function dispose() {
this.handlemouseout();
_component.prototype.dispose.call(this);
}
/**
* handles `keyup` events on the `volumecontrol`, looking for esc, which closes
* the volume panel and sets focus on `mutetoggle`.
*
* @param {eventtarget~event} event
* the `keyup` event that caused this function to be called.
*
* @listens keyup
*/
;
_proto.handlevolumecontrolkeyup = function handlevolumecontrolkeyup(event) {
if (keycode__webpack_imported_module_3___default.a.iseventkey(event, 'esc')) {
this.mutetoggle.focus();
}
}
/**
* this gets called when a `volumepanel` gains hover via a `mouseover` event.
* turns on listening for `mouseover` event. when they happen it
* calls `this.handlemouseover`.
*
* @param {eventtarget~event} event
* the `mouseover` event that caused this function to be called.
*
* @listens mouseover
*/
;
_proto.handlemouseover = function handlemouseover(event) {
this.addclass('vjs-hover');
on(global_document__webpack_imported_module_1___default.a, 'keyup', this.handlekeypresshandler_);
}
/**
* this gets called when a `volumepanel` gains hover via a `mouseout` event.
* turns on listening for `mouseout` event. when they happen it
* calls `this.handlemouseout`.
*
* @param {eventtarget~event} event
* the `mouseout` event that caused this function to be called.
*
* @listens mouseout
*/
;
_proto.handlemouseout = function handlemouseout(event) {
this.removeclass('vjs-hover');
off(global_document__webpack_imported_module_1___default.a, 'keyup', this.handlekeypresshandler_);
}
/**
* handles `keyup` event on the document or `keydown` event on the `volumepanel`,
* looking for esc, which hides the `volumecontrol`.
*
* @param {eventtarget~event} event
* the keypress that triggered this event.
*
* @listens keydown | keyup
*/
;
_proto.handlekeypress = function handlekeypress(event) {
if (keycode__webpack_imported_module_3___default.a.iseventkey(event, 'esc')) {
this.handlemouseout();
}
};
return volumepanel;
}(component$1);
/**
* default options for the `volumecontrol`
*
* @type {object}
* @private
*/
volumepanel.prototype.options_ = {
children: ['mutetoggle', 'volumecontrol']
};
component$1.registercomponent('volumepanel', volumepanel);
/**
* the menu component is used to build popup menus, including subtitle and
* captions selection menus.
*
* @extends component
*/
var menu = /*#__pure__*/function (_component) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(menu, _component);
/**
* create an instance of this class.
*
* @param {player} player
* the player that this component should attach to
*
* @param {object} [options]
* object of option names and values
*
*/
function menu(player, options) {
var _this;
_this = _component.call(this, player, options) || this;
if (options) {
_this.menubutton_ = options.menubutton;
}
_this.focusedchild_ = -1;
_this.on('keydown', function (e) {
return _this.handlekeydown(e);
}); // all the menu item instances share the same blur handler provided by the menu container.
_this.boundhandleblur_ = function (e) {
return _this.handleblur(e);
};
_this.boundhandletapclick_ = function (e) {
return _this.handletapclick(e);
};
return _this;
}
/**
* add event listeners to the {@link menuitem}.
*
* @param {object} component
* the instance of the `menuitem` to add listeners to.
*
*/
var _proto = menu.prototype;
_proto.addeventlistenerforitem = function addeventlistenerforitem(component) {
if (!(component instanceof component$1)) {
return;
}
this.on(component, 'blur', this.boundhandleblur_);
this.on(component, ['tap', 'click'], this.boundhandletapclick_);
}
/**
* remove event listeners from the {@link menuitem}.
*
* @param {object} component
* the instance of the `menuitem` to remove listeners.
*
*/
;
_proto.removeeventlistenerforitem = function removeeventlistenerforitem(component) {
if (!(component instanceof component$1)) {
return;
}
this.off(component, 'blur', this.boundhandleblur_);
this.off(component, ['tap', 'click'], this.boundhandletapclick_);
}
/**
* this method will be called indirectly when the component has been added
* before the component adds to the new menu instance by `additem`.
* in this case, the original menu instance will remove the component
* by calling `removechild`.
*
* @param {object} component
* the instance of the `menuitem`
*/
;
_proto.removechild = function removechild(component) {
if (typeof component === 'string') {
component = this.getchild(component);
}
this.removeeventlistenerforitem(component);
_component.prototype.removechild.call(this, component);
}
/**
* add a {@link menuitem} to the menu.
*
* @param {object|string} component
* the name or instance of the `menuitem` to add.
*
*/
;
_proto.additem = function additem(component) {
var childcomponent = this.addchild(component);
if (childcomponent) {
this.addeventlistenerforitem(childcomponent);
}
}
/**
* create the `menu`s dom element.
*
* @return {element}
* the element that was created
*/
;
_proto.createel = function createel$1() {
var contenteltype = this.options_.contenteltype || 'ul';
this.contentel_ = createel(contenteltype, {
classname: 'vjs-menu-content'
});
this.contentel_.setattribute('role', 'menu');
var el = _component.prototype.createel.call(this, 'div', {
append: this.contentel_,
classname: 'vjs-menu'
});
el.appendchild(this.contentel_); // prevent clicks from bubbling up. needed for menu buttons,
// where a click on the parent is significant
on(el, 'click', function (event) {
event.preventdefault();
event.stopimmediatepropagation();
});
return el;
};
_proto.dispose = function dispose() {
this.contentel_ = null;
this.boundhandleblur_ = null;
this.boundhandletapclick_ = null;
_component.prototype.dispose.call(this);
}
/**
* called when a `menuitem` loses focus.
*
* @param {eventtarget~event} event
* the `blur` event that caused this function to be called.
*
* @listens blur
*/
;
_proto.handleblur = function handleblur(event) {
var relatedtarget = event.relatedtarget || global_document__webpack_imported_module_1___default.a.activeelement; // close menu popup when a user clicks outside the menu
if (!this.children().some(function (element) {
return element.el() === relatedtarget;
})) {
var btn = this.menubutton_;
if (btn && btn.buttonpressed_ && relatedtarget !== btn.el().firstchild) {
btn.unpressbutton();
}
}
}
/**
* called when a `menuitem` gets clicked or tapped.
*
* @param {eventtarget~event} event
* the `click` or `tap` event that caused this function to be called.
*
* @listens click,tap
*/
;
_proto.handletapclick = function handletapclick(event) {
// unpress the associated menubutton, and move focus back to it
if (this.menubutton_) {
this.menubutton_.unpressbutton();
var childcomponents = this.children();
if (!array.isarray(childcomponents)) {
return;
}
var foundcomponent = childcomponents.filter(function (component) {
return component.el() === event.target;
})[0];
if (!foundcomponent) {
return;
} // don't focus menu button if item is a caption settings item
// because focus will move elsewhere
if (foundcomponent.name() !== 'captionsettingsmenuitem') {
this.menubutton_.focus();
}
}
}
/**
* handle a `keydown` event on this menu. this listener is added in the constructor.
*
* @param {eventtarget~event} event
* a `keydown` event that happened on the menu.
*
* @listens keydown
*/
;
_proto.handlekeydown = function handlekeydown(event) {
// left and down arrows
if (keycode__webpack_imported_module_3___default.a.iseventkey(event, 'left') || keycode__webpack_imported_module_3___default.a.iseventkey(event, 'down')) {
event.preventdefault();
event.stoppropagation();
this.stepforward(); // up and right arrows
} else if (keycode__webpack_imported_module_3___default.a.iseventkey(event, 'right') || keycode__webpack_imported_module_3___default.a.iseventkey(event, 'up')) {
event.preventdefault();
event.stoppropagation();
this.stepback();
}
}
/**
* move to next (lower) menu item for keyboard users.
*/
;
_proto.stepforward = function stepforward() {
var stepchild = 0;
if (this.focusedchild_ !== undefined) {
stepchild = this.focusedchild_ + 1;
}
this.focus(stepchild);
}
/**
* move to previous (higher) menu item for keyboard users.
*/
;
_proto.stepback = function stepback() {
var stepchild = 0;
if (this.focusedchild_ !== undefined) {
stepchild = this.focusedchild_ - 1;
}
this.focus(stepchild);
}
/**
* set focus on a {@link menuitem} in the `menu`.
*
* @param {object|string} [item=0]
* index of child item set focus on.
*/
;
_proto.focus = function focus(item) {
if (item === void 0) {
item = 0;
}
var children = this.children().slice();
var havetitle = children.length && children[0].hasclass('vjs-menu-title');
if (havetitle) {
children.shift();
}
if (children.length > 0) {
if (item < 0) {
item = 0;
} else if (item >= children.length) {
item = children.length - 1;
}
this.focusedchild_ = item;
children[item].el_.focus();
}
};
return menu;
}(component$1);
component$1.registercomponent('menu', menu);
/**
* a `menubutton` class for any popup {@link menu}.
*
* @extends component
*/
var menubutton = /*#__pure__*/function (_component) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(menubutton, _component);
/**
* creates an instance of this class.
*
* @param {player} player
* the `player` that this class should be attached to.
*
* @param {object} [options={}]
* the key/value store of player options.
*/
function menubutton(player, options) {
var _this;
if (options === void 0) {
options = {};
}
_this = _component.call(this, player, options) || this;
_this.menubutton_ = new button(player, options);
_this.menubutton_.controltext(_this.controltext_);
_this.menubutton_.el_.setattribute('aria-haspopup', 'true'); // add buildcssclass values to the button, not the wrapper
var buttonclass = button.prototype.buildcssclass();
_this.menubutton_.el_.classname = _this.buildcssclass() + ' ' + buttonclass;
_this.menubutton_.removeclass('vjs-control');
_this.addchild(_this.menubutton_);
_this.update();
_this.enabled_ = true;
var handleclick = function handleclick(e) {
return _this.handleclick(e);
};
_this.handlemenukeyup_ = function (e) {
return _this.handlemenukeyup(e);
};
_this.on(_this.menubutton_, 'tap', handleclick);
_this.on(_this.menubutton_, 'click', handleclick);
_this.on(_this.menubutton_, 'keydown', function (e) {
return _this.handlekeydown(e);
});
_this.on(_this.menubutton_, 'mouseenter', function () {
_this.addclass('vjs-hover');
_this.menu.show();
on(global_document__webpack_imported_module_1___default.a, 'keyup', _this.handlemenukeyup_);
});
_this.on('mouseleave', function (e) {
return _this.handlemouseleave(e);
});
_this.on('keydown', function (e) {
return _this.handlesubmenukeydown(e);
});
return _this;
}
/**
* update the menu based on the current state of its items.
*/
var _proto = menubutton.prototype;
_proto.update = function update() {
var menu = this.createmenu();
if (this.menu) {
this.menu.dispose();
this.removechild(this.menu);
}
this.menu = menu;
this.addchild(menu);
/**
* track the state of the menu button
*
* @type {boolean}
* @private
*/
this.buttonpressed_ = false;
this.menubutton_.el_.setattribute('aria-expanded', 'false');
if (this.items && this.items.length <= this.hidethreshold_) {
this.hide();
this.menu.contentel_.removeattribute('role');
} else {
this.show();
this.menu.contentel_.setattribute('role', 'menu');
}
}
/**
* create the menu and add all items to it.
*
* @return {menu}
* the constructed menu
*/
;
_proto.createmenu = function createmenu() {
var menu = new menu(this.player_, {
menubutton: this
});
/**
* hide the menu if the number of items is less than or equal to this threshold. this defaults
* to 0 and whenever we add items which can be hidden to the menu we'll increment it. we list
* it here because every time we run `createmenu` we need to reset the value.
*
* @protected
* @type {number}
*/
this.hidethreshold_ = 0; // add a title list item to the top
if (this.options_.title) {
var titleel = createel('li', {
classname: 'vjs-menu-title',
textcontent: totitlecase$1(this.options_.title),
tabindex: -1
});
var titlecomponent = new component$1(this.player_, {
el: titleel
});
menu.additem(titlecomponent);
}
this.items = this.createitems();
if (this.items) {
// add menu items to the menu
for (var i = 0; i < this.items.length; i++) {
menu.additem(this.items[i]);
}
}
return menu;
}
/**
* create the list of menu items. specific to each subclass.
*
* @abstract
*/
;
_proto.createitems = function createitems() {}
/**
* create the `menubuttons`s dom element.
*
* @return {element}
* the element that gets created.
*/
;
_proto.createel = function createel() {
return _component.prototype.createel.call(this, 'div', {
classname: this.buildwrappercssclass()
}, {});
}
/**
* allow sub components to stack css class names for the wrapper element
*
* @return {string}
* the constructed wrapper dom `classname`
*/
;
_proto.buildwrappercssclass = function buildwrappercssclass() {
var menubuttonclass = 'vjs-menu-button'; // if the inline option is passed, we want to use different styles altogether.
if (this.options_.inline === true) {
menubuttonclass += '-inline';
} else {
menubuttonclass += '-popup';
} // todo: fix the css so that this isn't necessary
var buttonclass = button.prototype.buildcssclass();
return "vjs-menu-button " + menubuttonclass + " " + buttonclass + " " + _component.prototype.buildcssclass.call(this);
}
/**
* builds the default dom `classname`.
*
* @return {string}
* the dom `classname` for this object.
*/
;
_proto.buildcssclass = function buildcssclass() {
var menubuttonclass = 'vjs-menu-button'; // if the inline option is passed, we want to use different styles altogether.
if (this.options_.inline === true) {
menubuttonclass += '-inline';
} else {
menubuttonclass += '-popup';
}
return "vjs-menu-button " + menubuttonclass + " " + _component.prototype.buildcssclass.call(this);
}
/**
* get or set the localized control text that will be used for accessibility.
*
* > note: this will come from the internal `menubutton_` element.
*
* @param {string} [text]
* control text for element.
*
* @param {element} [el=this.menubutton_.el()]
* element to set the title on.
*
* @return {string}
* - the control text when getting
*/
;
_proto.controltext = function controltext(text, el) {
if (el === void 0) {
el = this.menubutton_.el();
}
return this.menubutton_.controltext(text, el);
}
/**
* dispose of the `menu-button` and all child components.
*/
;
_proto.dispose = function dispose() {
this.handlemouseleave();
_component.prototype.dispose.call(this);
}
/**
* handle a click on a `menubutton`.
* see {@link clickablecomponent#handleclick} for instances where this is called.
*
* @param {eventtarget~event} event
* the `keydown`, `tap`, or `click` event that caused this function to be
* called.
*
* @listens tap
* @listens click
*/
;
_proto.handleclick = function handleclick(event) {
if (this.buttonpressed_) {
this.unpressbutton();
} else {
this.pressbutton();
}
}
/**
* handle `mouseleave` for `menubutton`.
*
* @param {eventtarget~event} event
* the `mouseleave` event that caused this function to be called.
*
* @listens mouseleave
*/
;
_proto.handlemouseleave = function handlemouseleave(event) {
this.removeclass('vjs-hover');
off(global_document__webpack_imported_module_1___default.a, 'keyup', this.handlemenukeyup_);
}
/**
* set the focus to the actual button, not to this element
*/
;
_proto.focus = function focus() {
this.menubutton_.focus();
}
/**
* remove the focus from the actual button, not this element
*/
;
_proto.blur = function blur() {
this.menubutton_.blur();
}
/**
* handle tab, escape, down arrow, and up arrow keys for `menubutton`. see
* {@link clickablecomponent#handlekeydown} for instances where this is called.
*
* @param {eventtarget~event} event
* the `keydown` event that caused this function to be called.
*
* @listens keydown
*/
;
_proto.handlekeydown = function handlekeydown(event) {
// escape or tab unpress the 'button'
if (keycode__webpack_imported_module_3___default.a.iseventkey(event, 'esc') || keycode__webpack_imported_module_3___default.a.iseventkey(event, 'tab')) {
if (this.buttonpressed_) {
this.unpressbutton();
} // don't preventdefault for tab key - we still want to lose focus
if (!keycode__webpack_imported_module_3___default.a.iseventkey(event, 'tab')) {
event.preventdefault(); // set focus back to the menu button's button
this.menubutton_.focus();
} // up arrow or down arrow also 'press' the button to open the menu
} else if (keycode__webpack_imported_module_3___default.a.iseventkey(event, 'up') || keycode__webpack_imported_module_3___default.a.iseventkey(event, 'down')) {
if (!this.buttonpressed_) {
event.preventdefault();
this.pressbutton();
}
}
}
/**
* handle a `keyup` event on a `menubutton`. the listener for this is added in
* the constructor.
*
* @param {eventtarget~event} event
* key press event
*
* @listens keyup
*/
;
_proto.handlemenukeyup = function handlemenukeyup(event) {
// escape hides popup menu
if (keycode__webpack_imported_module_3___default.a.iseventkey(event, 'esc') || keycode__webpack_imported_module_3___default.a.iseventkey(event, 'tab')) {
this.removeclass('vjs-hover');
}
}
/**
* this method name now delegates to `handlesubmenukeydown`. this means
* anyone calling `handlesubmenukeypress` will not see their method calls
* stop working.
*
* @param {eventtarget~event} event
* the event that caused this function to be called.
*/
;
_proto.handlesubmenukeypress = function handlesubmenukeypress(event) {
this.handlesubmenukeydown(event);
}
/**
* handle a `keydown` event on a sub-menu. the listener for this is added in
* the constructor.
*
* @param {eventtarget~event} event
* key press event
*
* @listens keydown
*/
;
_proto.handlesubmenukeydown = function handlesubmenukeydown(event) {
// escape or tab unpress the 'button'
if (keycode__webpack_imported_module_3___default.a.iseventkey(event, 'esc') || keycode__webpack_imported_module_3___default.a.iseventkey(event, 'tab')) {
if (this.buttonpressed_) {
this.unpressbutton();
} // don't preventdefault for tab key - we still want to lose focus
if (!keycode__webpack_imported_module_3___default.a.iseventkey(event, 'tab')) {
event.preventdefault(); // set focus back to the menu button's button
this.menubutton_.focus();
}
}
}
/**
* put the current `menubutton` into a pressed state.
*/
;
_proto.pressbutton = function pressbutton() {
if (this.enabled_) {
this.buttonpressed_ = true;
this.menu.show();
this.menu.lockshowing();
this.menubutton_.el_.setattribute('aria-expanded', 'true'); // set the focus into the submenu, except on ios where it is resulting in
// undesired scrolling behavior when the player is in an iframe
if (is_ios && isinframe()) {
// return early so that the menu isn't focused
return;
}
this.menu.focus();
}
}
/**
* take the current `menubutton` out of a pressed state.
*/
;
_proto.unpressbutton = function unpressbutton() {
if (this.enabled_) {
this.buttonpressed_ = false;
this.menu.unlockshowing();
this.menu.hide();
this.menubutton_.el_.setattribute('aria-expanded', 'false');
}
}
/**
* disable the `menubutton`. don't allow it to be clicked.
*/
;
_proto.disable = function disable() {
this.unpressbutton();
this.enabled_ = false;
this.addclass('vjs-disabled');
this.menubutton_.disable();
}
/**
* enable the `menubutton`. allow it to be clicked.
*/
;
_proto.enable = function enable() {
this.enabled_ = true;
this.removeclass('vjs-disabled');
this.menubutton_.enable();
};
return menubutton;
}(component$1);
component$1.registercomponent('menubutton', menubutton);
/**
* the base class for buttons that toggle specific track types (e.g. subtitles).
*
* @extends menubutton
*/
var trackbutton = /*#__pure__*/function (_menubutton) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(trackbutton, _menubutton);
/**
* creates an instance of this class.
*
* @param {player} player
* the `player` that this class should be attached to.
*
* @param {object} [options]
* the key/value store of player options.
*/
function trackbutton(player, options) {
var _this;
var tracks = options.tracks;
_this = _menubutton.call(this, player, options) || this;
if (_this.items.length <= 1) {
_this.hide();
}
if (!tracks) {
return _babel_runtime_helpers_assertthisinitialized__webpack_imported_module_4___default()(_this);
}
var updatehandler = bind(_babel_runtime_helpers_assertthisinitialized__webpack_imported_module_4___default()(_this), _this.update);
tracks.addeventlistener('removetrack', updatehandler);
tracks.addeventlistener('addtrack', updatehandler);
tracks.addeventlistener('labelchange', updatehandler);
_this.player_.on('ready', updatehandler);
_this.player_.on('dispose', function () {
tracks.removeeventlistener('removetrack', updatehandler);
tracks.removeeventlistener('addtrack', updatehandler);
tracks.removeeventlistener('labelchange', updatehandler);
});
return _this;
}
return trackbutton;
}(menubutton);
component$1.registercomponent('trackbutton', trackbutton);
/**
* @file menu-keys.js
*/
/**
* all keys used for operation of a menu (`menubutton`, `menu`, and `menuitem`)
* note that 'enter' and 'space' are not included here (otherwise they would
* prevent the `menubutton` and `menuitem` from being keyboard-clickable)
* @typedef menukeys
* @array
*/
var menukeys = ['tab', 'esc', 'up', 'down', 'right', 'left'];
/**
* the component for a menu item. ``
*
* @extends clickablecomponent
*/
var menuitem = /*#__pure__*/function (_clickablecomponent) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(menuitem, _clickablecomponent);
/**
* creates an instance of the this class.
*
* @param {player} player
* the `player` that this class should be attached to.
*
* @param {object} [options={}]
* the key/value store of player options.
*
*/
function menuitem(player, options) {
var _this;
_this = _clickablecomponent.call(this, player, options) || this;
_this.selectable = options.selectable;
_this.isselected_ = options.selected || false;
_this.multiselectable = options.multiselectable;
_this.selected(_this.isselected_);
if (_this.selectable) {
if (_this.multiselectable) {
_this.el_.setattribute('role', 'menuitemcheckbox');
} else {
_this.el_.setattribute('role', 'menuitemradio');
}
} else {
_this.el_.setattribute('role', 'menuitem');
}
return _this;
}
/**
* create the `menuitem's dom element
*
* @param {string} [type=li]
* element's node type, not actually used, always set to `li`.
*
* @param {object} [props={}]
* an object of properties that should be set on the element
*
* @param {object} [attrs={}]
* an object of attributes that should be set on the element
*
* @return {element}
* the element that gets created.
*/
var _proto = menuitem.prototype;
_proto.createel = function createel$1(type, props, attrs) {
// the control is textual, not just an icon
this.noniconcontrol = true;
var el = _clickablecomponent.prototype.createel.call(this, 'li', assign({
classname: 'vjs-menu-item',
tabindex: -1
}, props), attrs); // swap icon with menu item text.
el.replacechild(createel('span', {
classname: 'vjs-menu-item-text',
textcontent: this.localize(this.options_.label)
}), el.queryselector('.vjs-icon-placeholder'));
return el;
}
/**
* ignore keys which are used by the menu, but pass any other ones up. see
* {@link clickablecomponent#handlekeydown} for instances where this is called.
*
* @param {eventtarget~event} event
* the `keydown` event that caused this function to be called.
*
* @listens keydown
*/
;
_proto.handlekeydown = function handlekeydown(event) {
if (!menukeys.some(function (key) {
return keycode__webpack_imported_module_3___default.a.iseventkey(event, key);
})) {
// pass keydown handling up for unused keys
_clickablecomponent.prototype.handlekeydown.call(this, event);
}
}
/**
* any click on a `menuitem` puts it into the selected state.
* see {@link clickablecomponent#handleclick} for instances where this is called.
*
* @param {eventtarget~event} event
* the `keydown`, `tap`, or `click` event that caused this function to be
* called.
*
* @listens tap
* @listens click
*/
;
_proto.handleclick = function handleclick(event) {
this.selected(true);
}
/**
* set the state for this menu item as selected or not.
*
* @param {boolean} selected
* if the menu item is selected or not
*/
;
_proto.selected = function selected(_selected) {
if (this.selectable) {
if (_selected) {
this.addclass('vjs-selected');
this.el_.setattribute('aria-checked', 'true'); // aria-checked isn't fully supported by browsers/screen readers,
// so indicate selected state to screen reader in the control text.
this.controltext(', selected');
this.isselected_ = true;
} else {
this.removeclass('vjs-selected');
this.el_.setattribute('aria-checked', 'false'); // indicate un-selected state to screen reader
this.controltext('');
this.isselected_ = false;
}
}
};
return menuitem;
}(clickablecomponent);
component$1.registercomponent('menuitem', menuitem);
/**
* the specific menu item type for selecting a language within a text track kind
*
* @extends menuitem
*/
var texttrackmenuitem = /*#__pure__*/function (_menuitem) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(texttrackmenuitem, _menuitem);
/**
* creates an instance of this class.
*
* @param {player} player
* the `player` that this class should be attached to.
*
* @param {object} [options]
* the key/value store of player options.
*/
function texttrackmenuitem(player, options) {
var _this;
var track = options.track;
var tracks = player.texttracks(); // modify options for parent menuitem class's init.
options.label = track.label || track.language || 'unknown';
options.selected = track.mode === 'showing';
_this = _menuitem.call(this, player, options) || this;
_this.track = track; // determine the relevant kind(s) of tracks for this component and filter
// out empty kinds.
_this.kinds = (options.kinds || [options.kind || _this.track.kind]).filter(boolean);
var changehandler = function changehandler() {
for (var _len = arguments.length, args = new array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this.handletrackschange.apply(_babel_runtime_helpers_assertthisinitialized__webpack_imported_module_4___default()(_this), args);
};
var selectedlanguagechangehandler = function selectedlanguagechangehandler() {
for (var _len2 = arguments.length, args = new array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
_this.handleselectedlanguagechange.apply(_babel_runtime_helpers_assertthisinitialized__webpack_imported_module_4___default()(_this), args);
};
player.on(['loadstart', 'texttrackchange'], changehandler);
tracks.addeventlistener('change', changehandler);
tracks.addeventlistener('selectedlanguagechange', selectedlanguagechangehandler);
_this.on('dispose', function () {
player.off(['loadstart', 'texttrackchange'], changehandler);
tracks.removeeventlistener('change', changehandler);
tracks.removeeventlistener('selectedlanguagechange', selectedlanguagechangehandler);
}); // ios7 doesn't dispatch change events to texttracklists when an
// associated track's mode changes. without something like
// object.observe() (also not present on ios7), it's not
// possible to detect changes to the mode attribute and polyfill
// the change event. as a poor substitute, we manually dispatch
// change events whenever the controls modify the mode.
if (tracks.onchange === undefined) {
var event;
_this.on(['tap', 'click'], function () {
if (typeof global_window__webpack_imported_module_0___default.a.event !== 'object') {
// android 2.3 throws an illegal constructor error for window.event
try {
event = new global_window__webpack_imported_module_0___default.a.event('change');
} catch (err) {// continue regardless of error
}
}
if (!event) {
event = global_document__webpack_imported_module_1___default.a.createevent('event');
event.initevent('change', true, true);
}
tracks.dispatchevent(event);
});
} // set the default state based on current tracks
_this.handletrackschange();
return _this;
}
/**
* this gets called when an `texttrackmenuitem` is "clicked". see
* {@link clickablecomponent} for more detailed information on what a click can be.
*
* @param {eventtarget~event} event
* the `keydown`, `tap`, or `click` event that caused this function to be
* called.
*
* @listens tap
* @listens click
*/
var _proto = texttrackmenuitem.prototype;
_proto.handleclick = function handleclick(event) {
var referencetrack = this.track;
var tracks = this.player_.texttracks();
_menuitem.prototype.handleclick.call(this, event);
if (!tracks) {
return;
}
for (var i = 0; i < tracks.length; i++) {
var track = tracks[i]; // if the track from the text tracks list is not of the right kind,
// skip it. we do not want to affect tracks of incompatible kind(s).
if (this.kinds.indexof(track.kind) === -1) {
continue;
} // if this text track is the component's track and it is not showing,
// set it to showing.
if (track === referencetrack) {
if (track.mode !== 'showing') {
track.mode = 'showing';
} // if this text track is not the component's track and it is not
// disabled, set it to disabled.
} else if (track.mode !== 'disabled') {
track.mode = 'disabled';
}
}
}
/**
* handle text track list change
*
* @param {eventtarget~event} event
* the `change` event that caused this function to be called.
*
* @listens texttracklist#change
*/
;
_proto.handletrackschange = function handletrackschange(event) {
var shouldbeselected = this.track.mode === 'showing'; // prevent redundant selected() calls because they may cause
// screen readers to read the appended control text unnecessarily
if (shouldbeselected !== this.isselected_) {
this.selected(shouldbeselected);
}
};
_proto.handleselectedlanguagechange = function handleselectedlanguagechange(event) {
if (this.track.mode === 'showing') {
var selectedlanguage = this.player_.cache_.selectedlanguage; // don't replace the kind of track across the same language
if (selectedlanguage && selectedlanguage.enabled && selectedlanguage.language === this.track.language && selectedlanguage.kind !== this.track.kind) {
return;
}
this.player_.cache_.selectedlanguage = {
enabled: true,
language: this.track.language,
kind: this.track.kind
};
}
};
_proto.dispose = function dispose() {
// remove reference to track object on dispose
this.track = null;
_menuitem.prototype.dispose.call(this);
};
return texttrackmenuitem;
}(menuitem);
component$1.registercomponent('texttrackmenuitem', texttrackmenuitem);
/**
* a special menu item for turning of a specific type of text track
*
* @extends texttrackmenuitem
*/
var offtexttrackmenuitem = /*#__pure__*/function (_texttrackmenuitem) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(offtexttrackmenuitem, _texttrackmenuitem);
/**
* creates an instance of this class.
*
* @param {player} player
* the `player` that this class should be attached to.
*
* @param {object} [options]
* the key/value store of player options.
*/
function offtexttrackmenuitem(player, options) {
// create pseudo track info
// requires options['kind']
options.track = {
player: player,
// it is no longer necessary to store `kind` or `kinds` on the track itself
// since they are now stored in the `kinds` property of all instances of
// texttrackmenuitem, but this will remain for backwards compatibility
kind: options.kind,
kinds: options.kinds,
"default": false,
mode: 'disabled'
};
if (!options.kinds) {
options.kinds = [options.kind];
}
if (options.label) {
options.track.label = options.label;
} else {
options.track.label = options.kinds.join(' and ') + ' off';
} // menuitem is selectable
options.selectable = true; // menuitem is not multiselectable (i.e. only one can be marked "selected" at a time)
options.multiselectable = false;
return _texttrackmenuitem.call(this, player, options) || this;
}
/**
* handle text track change
*
* @param {eventtarget~event} event
* the event that caused this function to run
*/
var _proto = offtexttrackmenuitem.prototype;
_proto.handletrackschange = function handletrackschange(event) {
var tracks = this.player().texttracks();
var shouldbeselected = true;
for (var i = 0, l = tracks.length; i < l; i++) {
var track = tracks[i];
if (this.options_.kinds.indexof(track.kind) > -1 && track.mode === 'showing') {
shouldbeselected = false;
break;
}
} // prevent redundant selected() calls because they may cause
// screen readers to read the appended control text unnecessarily
if (shouldbeselected !== this.isselected_) {
this.selected(shouldbeselected);
}
};
_proto.handleselectedlanguagechange = function handleselectedlanguagechange(event) {
var tracks = this.player().texttracks();
var allhidden = true;
for (var i = 0, l = tracks.length; i < l; i++) {
var track = tracks[i];
if (['captions', 'descriptions', 'subtitles'].indexof(track.kind) > -1 && track.mode === 'showing') {
allhidden = false;
break;
}
}
if (allhidden) {
this.player_.cache_.selectedlanguage = {
enabled: false
};
}
};
return offtexttrackmenuitem;
}(texttrackmenuitem);
component$1.registercomponent('offtexttrackmenuitem', offtexttrackmenuitem);
/**
* the base class for buttons that toggle specific text track types (e.g. subtitles)
*
* @extends menubutton
*/
var texttrackbutton = /*#__pure__*/function (_trackbutton) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(texttrackbutton, _trackbutton);
/**
* creates an instance of this class.
*
* @param {player} player
* the `player` that this class should be attached to.
*
* @param {object} [options={}]
* the key/value store of player options.
*/
function texttrackbutton(player, options) {
if (options === void 0) {
options = {};
}
options.tracks = player.texttracks();
return _trackbutton.call(this, player, options) || this;
}
/**
* create a menu item for each text track
*
* @param {texttrackmenuitem[]} [items=[]]
* existing array of items to use during creation
*
* @return {texttrackmenuitem[]}
* array of menu items that were created
*/
var _proto = texttrackbutton.prototype;
_proto.createitems = function createitems(items, trackmenuitem) {
if (items === void 0) {
items = [];
}
if (trackmenuitem === void 0) {
trackmenuitem = texttrackmenuitem;
}
// label is an override for the [track] off label
// used to localise captions/subtitles
var label;
if (this.label_) {
label = this.label_ + " off";
} // add an off menu item to turn all tracks off
items.push(new offtexttrackmenuitem(this.player_, {
kinds: this.kinds_,
kind: this.kind_,
label: label
}));
this.hidethreshold_ += 1;
var tracks = this.player_.texttracks();
if (!array.isarray(this.kinds_)) {
this.kinds_ = [this.kind_];
}
for (var i = 0; i < tracks.length; i++) {
var track = tracks[i]; // only add tracks that are of an appropriate kind and have a label
if (this.kinds_.indexof(track.kind) > -1) {
var item = new trackmenuitem(this.player_, {
track: track,
kinds: this.kinds_,
kind: this.kind_,
// menuitem is selectable
selectable: true,
// menuitem is not multiselectable (i.e. only one can be marked "selected" at a time)
multiselectable: false
});
item.addclass("vjs-" + track.kind + "-menu-item");
items.push(item);
}
}
return items;
};
return texttrackbutton;
}(trackbutton);
component$1.registercomponent('texttrackbutton', texttrackbutton);
/**
* the chapter track menu item
*
* @extends menuitem
*/
var chapterstrackmenuitem = /*#__pure__*/function (_menuitem) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(chapterstrackmenuitem, _menuitem);
/**
* creates an instance of this class.
*
* @param {player} player
* the `player` that this class should be attached to.
*
* @param {object} [options]
* the key/value store of player options.
*/
function chapterstrackmenuitem(player, options) {
var _this;
var track = options.track;
var cue = options.cue;
var currenttime = player.currenttime(); // modify options for parent menuitem class's init.
options.selectable = true;
options.multiselectable = false;
options.label = cue.text;
options.selected = cue.starttime <= currenttime && currenttime < cue.endtime;
_this = _menuitem.call(this, player, options) || this;
_this.track = track;
_this.cue = cue;
return _this;
}
/**
* this gets called when an `chapterstrackmenuitem` is "clicked". see
* {@link clickablecomponent} for more detailed information on what a click can be.
*
* @param {eventtarget~event} [event]
* the `keydown`, `tap`, or `click` event that caused this function to be
* called.
*
* @listens tap
* @listens click
*/
var _proto = chapterstrackmenuitem.prototype;
_proto.handleclick = function handleclick(event) {
_menuitem.prototype.handleclick.call(this);
this.player_.currenttime(this.cue.starttime);
};
return chapterstrackmenuitem;
}(menuitem);
component$1.registercomponent('chapterstrackmenuitem', chapterstrackmenuitem);
/**
* the button component for toggling and selecting chapters
* chapters act much differently than other text tracks
* cues are navigation vs. other tracks of alternative languages
*
* @extends texttrackbutton
*/
var chaptersbutton = /*#__pure__*/function (_texttrackbutton) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(chaptersbutton, _texttrackbutton);
/**
* creates an instance of this class.
*
* @param {player} player
* the `player` that this class should be attached to.
*
* @param {object} [options]
* the key/value store of player options.
*
* @param {component~readycallback} [ready]
* the function to call when this function is ready.
*/
function chaptersbutton(player, options, ready) {
var _this;
_this = _texttrackbutton.call(this, player, options, ready) || this;
_this.selectcurrentitem_ = function () {
_this.items.foreach(function (item) {
item.selected(_this.track_.activecues[0] === item.cue);
});
};
return _this;
}
/**
* builds the default dom `classname`.
*
* @return {string}
* the dom `classname` for this object.
*/
var _proto = chaptersbutton.prototype;
_proto.buildcssclass = function buildcssclass() {
return "vjs-chapters-button " + _texttrackbutton.prototype.buildcssclass.call(this);
};
_proto.buildwrappercssclass = function buildwrappercssclass() {
return "vjs-chapters-button " + _texttrackbutton.prototype.buildwrappercssclass.call(this);
}
/**
* update the menu based on the current state of its items.
*
* @param {eventtarget~event} [event]
* an event that triggered this function to run.
*
* @listens texttracklist#addtrack
* @listens texttracklist#removetrack
* @listens texttracklist#change
*/
;
_proto.update = function update(event) {
if (event && event.track && event.track.kind !== 'chapters') {
return;
}
var track = this.findchapterstrack();
if (track !== this.track_) {
this.settrack(track);
_texttrackbutton.prototype.update.call(this);
} else if (!this.items || track && track.cues && track.cues.length !== this.items.length) {
// update the menu initially or if the number of cues has changed since set
_texttrackbutton.prototype.update.call(this);
}
}
/**
* set the currently selected track for the chapters button.
*
* @param {texttrack} track
* the new track to select. nothing will change if this is the currently selected
* track.
*/
;
_proto.settrack = function settrack(track) {
if (this.track_ === track) {
return;
}
if (!this.updatehandler_) {
this.updatehandler_ = this.update.bind(this);
} // here this.track_ refers to the old track instance
if (this.track_) {
var remotetexttrackel = this.player_.remotetexttrackels().gettrackelementbytrack_(this.track_);
if (remotetexttrackel) {
remotetexttrackel.removeeventlistener('load', this.updatehandler_);
}
this.track_.removeeventlistener('cuechange', this.selectcurrentitem_);
this.track_ = null;
}
this.track_ = track; // here this.track_ refers to the new track instance
if (this.track_) {
this.track_.mode = 'hidden';
var _remotetexttrackel = this.player_.remotetexttrackels().gettrackelementbytrack_(this.track_);
if (_remotetexttrackel) {
_remotetexttrackel.addeventlistener('load', this.updatehandler_);
}
this.track_.addeventlistener('cuechange', this.selectcurrentitem_);
}
}
/**
* find the track object that is currently in use by this chaptersbutton
*
* @return {texttrack|undefined}
* the current track or undefined if none was found.
*/
;
_proto.findchapterstrack = function findchapterstrack() {
var tracks = this.player_.texttracks() || [];
for (var i = tracks.length - 1; i >= 0; i--) {
// we will always choose the last track as our chapterstrack
var track = tracks[i];
if (track.kind === this.kind_) {
return track;
}
}
}
/**
* get the caption for the chaptersbutton based on the track label. this will also
* use the current tracks localized kind as a fallback if a label does not exist.
*
* @return {string}
* the tracks current label or the localized track kind.
*/
;
_proto.getmenucaption = function getmenucaption() {
if (this.track_ && this.track_.label) {
return this.track_.label;
}
return this.localize(totitlecase$1(this.kind_));
}
/**
* create menu from chapter track
*
* @return {menu}
* new menu for the chapter buttons
*/
;
_proto.createmenu = function createmenu() {
this.options_.title = this.getmenucaption();
return _texttrackbutton.prototype.createmenu.call(this);
}
/**
* create a menu item for each text track
*
* @return {texttrackmenuitem[]}
* array of menu items
*/
;
_proto.createitems = function createitems() {
var items = [];
if (!this.track_) {
return items;
}
var cues = this.track_.cues;
if (!cues) {
return items;
}
for (var i = 0, l = cues.length; i < l; i++) {
var cue = cues[i];
var mi = new chapterstrackmenuitem(this.player_, {
track: this.track_,
cue: cue
});
items.push(mi);
}
return items;
};
return chaptersbutton;
}(texttrackbutton);
/**
* `kind` of texttrack to look for to associate it with this menu.
*
* @type {string}
* @private
*/
chaptersbutton.prototype.kind_ = 'chapters';
/**
* the text that should display over the `chaptersbutton`s controls. added for localization.
*
* @type {string}
* @private
*/
chaptersbutton.prototype.controltext_ = 'chapters';
component$1.registercomponent('chaptersbutton', chaptersbutton);
/**
* the button component for toggling and selecting descriptions
*
* @extends texttrackbutton
*/
var descriptionsbutton = /*#__pure__*/function (_texttrackbutton) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(descriptionsbutton, _texttrackbutton);
/**
* creates an instance of this class.
*
* @param {player} player
* the `player` that this class should be attached to.
*
* @param {object} [options]
* the key/value store of player options.
*
* @param {component~readycallback} [ready]
* the function to call when this component is ready.
*/
function descriptionsbutton(player, options, ready) {
var _this;
_this = _texttrackbutton.call(this, player, options, ready) || this;
var tracks = player.texttracks();
var changehandler = bind(_babel_runtime_helpers_assertthisinitialized__webpack_imported_module_4___default()(_this), _this.handletrackschange);
tracks.addeventlistener('change', changehandler);
_this.on('dispose', function () {
tracks.removeeventlistener('change', changehandler);
});
return _this;
}
/**
* handle text track change
*
* @param {eventtarget~event} event
* the event that caused this function to run
*
* @listens texttracklist#change
*/
var _proto = descriptionsbutton.prototype;
_proto.handletrackschange = function handletrackschange(event) {
var tracks = this.player().texttracks();
var disabled = false; // check whether a track of a different kind is showing
for (var i = 0, l = tracks.length; i < l; i++) {
var track = tracks[i];
if (track.kind !== this.kind_ && track.mode === 'showing') {
disabled = true;
break;
}
} // if another track is showing, disable this menu button
if (disabled) {
this.disable();
} else {
this.enable();
}
}
/**
* builds the default dom `classname`.
*
* @return {string}
* the dom `classname` for this object.
*/
;
_proto.buildcssclass = function buildcssclass() {
return "vjs-descriptions-button " + _texttrackbutton.prototype.buildcssclass.call(this);
};
_proto.buildwrappercssclass = function buildwrappercssclass() {
return "vjs-descriptions-button " + _texttrackbutton.prototype.buildwrappercssclass.call(this);
};
return descriptionsbutton;
}(texttrackbutton);
/**
* `kind` of texttrack to look for to associate it with this menu.
*
* @type {string}
* @private
*/
descriptionsbutton.prototype.kind_ = 'descriptions';
/**
* the text that should display over the `descriptionsbutton`s controls. added for localization.
*
* @type {string}
* @private
*/
descriptionsbutton.prototype.controltext_ = 'descriptions';
component$1.registercomponent('descriptionsbutton', descriptionsbutton);
/**
* the button component for toggling and selecting subtitles
*
* @extends texttrackbutton
*/
var subtitlesbutton = /*#__pure__*/function (_texttrackbutton) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(subtitlesbutton, _texttrackbutton);
/**
* creates an instance of this class.
*
* @param {player} player
* the `player` that this class should be attached to.
*
* @param {object} [options]
* the key/value store of player options.
*
* @param {component~readycallback} [ready]
* the function to call when this component is ready.
*/
function subtitlesbutton(player, options, ready) {
return _texttrackbutton.call(this, player, options, ready) || this;
}
/**
* builds the default dom `classname`.
*
* @return {string}
* the dom `classname` for this object.
*/
var _proto = subtitlesbutton.prototype;
_proto.buildcssclass = function buildcssclass() {
return "vjs-subtitles-button " + _texttrackbutton.prototype.buildcssclass.call(this);
};
_proto.buildwrappercssclass = function buildwrappercssclass() {
return "vjs-subtitles-button " + _texttrackbutton.prototype.buildwrappercssclass.call(this);
};
return subtitlesbutton;
}(texttrackbutton);
/**
* `kind` of texttrack to look for to associate it with this menu.
*
* @type {string}
* @private
*/
subtitlesbutton.prototype.kind_ = 'subtitles';
/**
* the text that should display over the `subtitlesbutton`s controls. added for localization.
*
* @type {string}
* @private
*/
subtitlesbutton.prototype.controltext_ = 'subtitles';
component$1.registercomponent('subtitlesbutton', subtitlesbutton);
/**
* the menu item for caption track settings menu
*
* @extends texttrackmenuitem
*/
var captionsettingsmenuitem = /*#__pure__*/function (_texttrackmenuitem) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(captionsettingsmenuitem, _texttrackmenuitem);
/**
* creates an instance of this class.
*
* @param {player} player
* the `player` that this class should be attached to.
*
* @param {object} [options]
* the key/value store of player options.
*/
function captionsettingsmenuitem(player, options) {
var _this;
options.track = {
player: player,
kind: options.kind,
label: options.kind + ' settings',
selectable: false,
"default": false,
mode: 'disabled'
}; // captionsettingsmenuitem has no concept of 'selected'
options.selectable = false;
options.name = 'captionsettingsmenuitem';
_this = _texttrackmenuitem.call(this, player, options) || this;
_this.addclass('vjs-texttrack-settings');
_this.controltext(', opens ' + options.kind + ' settings dialog');
return _this;
}
/**
* this gets called when an `captionsettingsmenuitem` is "clicked". see
* {@link clickablecomponent} for more detailed information on what a click can be.
*
* @param {eventtarget~event} [event]
* the `keydown`, `tap`, or `click` event that caused this function to be
* called.
*
* @listens tap
* @listens click
*/
var _proto = captionsettingsmenuitem.prototype;
_proto.handleclick = function handleclick(event) {
this.player().getchild('texttracksettings').open();
};
return captionsettingsmenuitem;
}(texttrackmenuitem);
component$1.registercomponent('captionsettingsmenuitem', captionsettingsmenuitem);
/**
* the button component for toggling and selecting captions
*
* @extends texttrackbutton
*/
var captionsbutton = /*#__pure__*/function (_texttrackbutton) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(captionsbutton, _texttrackbutton);
/**
* creates an instance of this class.
*
* @param {player} player
* the `player` that this class should be attached to.
*
* @param {object} [options]
* the key/value store of player options.
*
* @param {component~readycallback} [ready]
* the function to call when this component is ready.
*/
function captionsbutton(player, options, ready) {
return _texttrackbutton.call(this, player, options, ready) || this;
}
/**
* builds the default dom `classname`.
*
* @return {string}
* the dom `classname` for this object.
*/
var _proto = captionsbutton.prototype;
_proto.buildcssclass = function buildcssclass() {
return "vjs-captions-button " + _texttrackbutton.prototype.buildcssclass.call(this);
};
_proto.buildwrappercssclass = function buildwrappercssclass() {
return "vjs-captions-button " + _texttrackbutton.prototype.buildwrappercssclass.call(this);
}
/**
* create caption menu items
*
* @return {captionsettingsmenuitem[]}
* the array of current menu items.
*/
;
_proto.createitems = function createitems() {
var items = [];
if (!(this.player().tech_ && this.player().tech_.featuresnativetexttracks) && this.player().getchild('texttracksettings')) {
items.push(new captionsettingsmenuitem(this.player_, {
kind: this.kind_
}));
this.hidethreshold_ += 1;
}
return _texttrackbutton.prototype.createitems.call(this, items);
};
return captionsbutton;
}(texttrackbutton);
/**
* `kind` of texttrack to look for to associate it with this menu.
*
* @type {string}
* @private
*/
captionsbutton.prototype.kind_ = 'captions';
/**
* the text that should display over the `captionsbutton`s controls. added for localization.
*
* @type {string}
* @private
*/
captionsbutton.prototype.controltext_ = 'captions';
component$1.registercomponent('captionsbutton', captionsbutton);
/**
* subscapsmenuitem has an [cc] icon to distinguish captions from subtitles
* in the subscapsmenu.
*
* @extends texttrackmenuitem
*/
var subscapsmenuitem = /*#__pure__*/function (_texttrackmenuitem) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(subscapsmenuitem, _texttrackmenuitem);
function subscapsmenuitem() {
return _texttrackmenuitem.apply(this, arguments) || this;
}
var _proto = subscapsmenuitem.prototype;
_proto.createel = function createel$1(type, props, attrs) {
var el = _texttrackmenuitem.prototype.createel.call(this, type, props, attrs);
var parentspan = el.queryselector('.vjs-menu-item-text');
if (this.options_.track.kind === 'captions') {
parentspan.appendchild(createel('span', {
classname: 'vjs-icon-placeholder'
}, {
'aria-hidden': true
}));
parentspan.appendchild(createel('span', {
classname: 'vjs-control-text',
// space added as the text will visually flow with the
// label
textcontent: " " + this.localize('captions')
}));
}
return el;
};
return subscapsmenuitem;
}(texttrackmenuitem);
component$1.registercomponent('subscapsmenuitem', subscapsmenuitem);
/**
* the button component for toggling and selecting captions and/or subtitles
*
* @extends texttrackbutton
*/
var subscapsbutton = /*#__pure__*/function (_texttrackbutton) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(subscapsbutton, _texttrackbutton);
function subscapsbutton(player, options) {
var _this;
if (options === void 0) {
options = {};
}
_this = _texttrackbutton.call(this, player, options) || this; // although north america uses "captions" in most cases for
// "captions and subtitles" other locales use "subtitles"
_this.label_ = 'subtitles';
if (['en', 'en-us', 'en-ca', 'fr-ca'].indexof(_this.player_.language_) > -1) {
_this.label_ = 'captions';
}
_this.menubutton_.controltext(totitlecase$1(_this.label_));
return _this;
}
/**
* builds the default dom `classname`.
*
* @return {string}
* the dom `classname` for this object.
*/
var _proto = subscapsbutton.prototype;
_proto.buildcssclass = function buildcssclass() {
return "vjs-subs-caps-button " + _texttrackbutton.prototype.buildcssclass.call(this);
};
_proto.buildwrappercssclass = function buildwrappercssclass() {
return "vjs-subs-caps-button " + _texttrackbutton.prototype.buildwrappercssclass.call(this);
}
/**
* create caption/subtitles menu items
*
* @return {captionsettingsmenuitem[]}
* the array of current menu items.
*/
;
_proto.createitems = function createitems() {
var items = [];
if (!(this.player().tech_ && this.player().tech_.featuresnativetexttracks) && this.player().getchild('texttracksettings')) {
items.push(new captionsettingsmenuitem(this.player_, {
kind: this.label_
}));
this.hidethreshold_ += 1;
}
items = _texttrackbutton.prototype.createitems.call(this, items, subscapsmenuitem);
return items;
};
return subscapsbutton;
}(texttrackbutton);
/**
* `kind`s of texttrack to look for to associate it with this menu.
*
* @type {array}
* @private
*/
subscapsbutton.prototype.kinds_ = ['captions', 'subtitles'];
/**
* the text that should display over the `subscapsbutton`s controls.
*
*
* @type {string}
* @private
*/
subscapsbutton.prototype.controltext_ = 'subtitles';
component$1.registercomponent('subscapsbutton', subscapsbutton);
/**
* an {@link audiotrack} {@link menuitem}
*
* @extends menuitem
*/
var audiotrackmenuitem = /*#__pure__*/function (_menuitem) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(audiotrackmenuitem, _menuitem);
/**
* creates an instance of this class.
*
* @param {player} player
* the `player` that this class should be attached to.
*
* @param {object} [options]
* the key/value store of player options.
*/
function audiotrackmenuitem(player, options) {
var _this;
var track = options.track;
var tracks = player.audiotracks(); // modify options for parent menuitem class's init.
options.label = track.label || track.language || 'unknown';
options.selected = track.enabled;
_this = _menuitem.call(this, player, options) || this;
_this.track = track;
_this.addclass("vjs-" + track.kind + "-menu-item");
var changehandler = function changehandler() {
for (var _len = arguments.length, args = new array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this.handletrackschange.apply(_babel_runtime_helpers_assertthisinitialized__webpack_imported_module_4___default()(_this), args);
};
tracks.addeventlistener('change', changehandler);
_this.on('dispose', function () {
tracks.removeeventlistener('change', changehandler);
});
return _this;
}
var _proto = audiotrackmenuitem.prototype;
_proto.createel = function createel$1(type, props, attrs) {
var el = _menuitem.prototype.createel.call(this, type, props, attrs);
var parentspan = el.queryselector('.vjs-menu-item-text');
if (this.options_.track.kind === 'main-desc') {
parentspan.appendchild(createel('span', {
classname: 'vjs-icon-placeholder'
}, {
'aria-hidden': true
}));
parentspan.appendchild(createel('span', {
classname: 'vjs-control-text',
textcontent: ' ' + this.localize('descriptions')
}));
}
return el;
}
/**
* this gets called when an `audiotrackmenuitem is "clicked". see {@link clickablecomponent}
* for more detailed information on what a click can be.
*
* @param {eventtarget~event} [event]
* the `keydown`, `tap`, or `click` event that caused this function to be
* called.
*
* @listens tap
* @listens click
*/
;
_proto.handleclick = function handleclick(event) {
_menuitem.prototype.handleclick.call(this, event); // the audio track list will automatically toggle other tracks
// off for us.
this.track.enabled = true; // when native audio tracks are used, we want to make sure that other tracks are turned off
if (this.player_.tech_.featuresnativeaudiotracks) {
var tracks = this.player_.audiotracks();
for (var i = 0; i < tracks.length; i++) {
var track = tracks[i]; // skip the current track since we enabled it above
if (track === this.track) {
continue;
}
track.enabled = track === this.track;
}
}
}
/**
* handle any {@link audiotrack} change.
*
* @param {eventtarget~event} [event]
* the {@link audiotracklist#change} event that caused this to run.
*
* @listens audiotracklist#change
*/
;
_proto.handletrackschange = function handletrackschange(event) {
this.selected(this.track.enabled);
};
return audiotrackmenuitem;
}(menuitem);
component$1.registercomponent('audiotrackmenuitem', audiotrackmenuitem);
/**
* the base class for buttons that toggle specific {@link audiotrack} types.
*
* @extends trackbutton
*/
var audiotrackbutton = /*#__pure__*/function (_trackbutton) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(audiotrackbutton, _trackbutton);
/**
* creates an instance of this class.
*
* @param {player} player
* the `player` that this class should be attached to.
*
* @param {object} [options={}]
* the key/value store of player options.
*/
function audiotrackbutton(player, options) {
if (options === void 0) {
options = {};
}
options.tracks = player.audiotracks();
return _trackbutton.call(this, player, options) || this;
}
/**
* builds the default dom `classname`.
*
* @return {string}
* the dom `classname` for this object.
*/
var _proto = audiotrackbutton.prototype;
_proto.buildcssclass = function buildcssclass() {
return "vjs-audio-button " + _trackbutton.prototype.buildcssclass.call(this);
};
_proto.buildwrappercssclass = function buildwrappercssclass() {
return "vjs-audio-button " + _trackbutton.prototype.buildwrappercssclass.call(this);
}
/**
* create a menu item for each audio track
*
* @param {audiotrackmenuitem[]} [items=[]]
* an array of existing menu items to use.
*
* @return {audiotrackmenuitem[]}
* an array of menu items
*/
;
_proto.createitems = function createitems(items) {
if (items === void 0) {
items = [];
}
// if there's only one audio track, there no point in showing it
this.hidethreshold_ = 1;
var tracks = this.player_.audiotracks();
for (var i = 0; i < tracks.length; i++) {
var track = tracks[i];
items.push(new audiotrackmenuitem(this.player_, {
track: track,
// menuitem is selectable
selectable: true,
// menuitem is not multiselectable (i.e. only one can be marked "selected" at a time)
multiselectable: false
}));
}
return items;
};
return audiotrackbutton;
}(trackbutton);
/**
* the text that should display over the `audiotrackbutton`s controls. added for localization.
*
* @type {string}
* @private
*/
audiotrackbutton.prototype.controltext_ = 'audio track';
component$1.registercomponent('audiotrackbutton', audiotrackbutton);
/**
* the specific menu item type for selecting a playback rate.
*
* @extends menuitem
*/
var playbackratemenuitem = /*#__pure__*/function (_menuitem) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(playbackratemenuitem, _menuitem);
/**
* creates an instance of this class.
*
* @param {player} player
* the `player` that this class should be attached to.
*
* @param {object} [options]
* the key/value store of player options.
*/
function playbackratemenuitem(player, options) {
var _this;
var label = options.rate;
var rate = parsefloat(label, 10); // modify options for parent menuitem class's init.
options.label = label;
options.selected = rate === player.playbackrate();
options.selectable = true;
options.multiselectable = false;
_this = _menuitem.call(this, player, options) || this;
_this.label = label;
_this.rate = rate;
_this.on(player, 'ratechange', function (e) {
return _this.update(e);
});
return _this;
}
/**
* this gets called when an `playbackratemenuitem` is "clicked". see
* {@link clickablecomponent} for more detailed information on what a click can be.
*
* @param {eventtarget~event} [event]
* the `keydown`, `tap`, or `click` event that caused this function to be
* called.
*
* @listens tap
* @listens click
*/
var _proto = playbackratemenuitem.prototype;
_proto.handleclick = function handleclick(event) {
_menuitem.prototype.handleclick.call(this);
this.player().playbackrate(this.rate);
}
/**
* update the playbackratemenuitem when the playbackrate changes.
*
* @param {eventtarget~event} [event]
* the `ratechange` event that caused this function to run.
*
* @listens player#ratechange
*/
;
_proto.update = function update(event) {
this.selected(this.player().playbackrate() === this.rate);
};
return playbackratemenuitem;
}(menuitem);
/**
* the text that should display over the `playbackratemenuitem`s controls. added for localization.
*
* @type {string}
* @private
*/
playbackratemenuitem.prototype.contenteltype = 'button';
component$1.registercomponent('playbackratemenuitem', playbackratemenuitem);
/**
* the component for controlling the playback rate.
*
* @extends menubutton
*/
var playbackratemenubutton = /*#__pure__*/function (_menubutton) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(playbackratemenubutton, _menubutton);
/**
* creates an instance of this class.
*
* @param {player} player
* the `player` that this class should be attached to.
*
* @param {object} [options]
* the key/value store of player options.
*/
function playbackratemenubutton(player, options) {
var _this;
_this = _menubutton.call(this, player, options) || this;
_this.menubutton_.el_.setattribute('aria-describedby', _this.labelelid_);
_this.updatevisibility();
_this.updatelabel();
_this.on(player, 'loadstart', function (e) {
return _this.updatevisibility(e);
});
_this.on(player, 'ratechange', function (e) {
return _this.updatelabel(e);
});
_this.on(player, 'playbackrateschange', function (e) {
return _this.handleplaybackrateschange(e);
});
return _this;
}
/**
* create the `component`'s dom element
*
* @return {element}
* the element that was created.
*/
var _proto = playbackratemenubutton.prototype;
_proto.createel = function createel$1() {
var el = _menubutton.prototype.createel.call(this);
this.labelelid_ = 'vjs-playback-rate-value-label-' + this.id_;
this.labelel_ = createel('div', {
classname: 'vjs-playback-rate-value',
id: this.labelelid_,
textcontent: '1x'
});
el.appendchild(this.labelel_);
return el;
};
_proto.dispose = function dispose() {
this.labelel_ = null;
_menubutton.prototype.dispose.call(this);
}
/**
* builds the default dom `classname`.
*
* @return {string}
* the dom `classname` for this object.
*/
;
_proto.buildcssclass = function buildcssclass() {
return "vjs-playback-rate " + _menubutton.prototype.buildcssclass.call(this);
};
_proto.buildwrappercssclass = function buildwrappercssclass() {
return "vjs-playback-rate " + _menubutton.prototype.buildwrappercssclass.call(this);
}
/**
* create the list of menu items. specific to each subclass.
*
*/
;
_proto.createitems = function createitems() {
var rates = this.playbackrates();
var items = [];
for (var i = rates.length - 1; i >= 0; i--) {
items.push(new playbackratemenuitem(this.player(), {
rate: rates[i] + 'x'
}));
}
return items;
}
/**
* updates aria accessibility attributes
*/
;
_proto.updateariaattributes = function updateariaattributes() {
// current playback rate
this.el().setattribute('aria-valuenow', this.player().playbackrate());
}
/**
* this gets called when an `playbackratemenubutton` is "clicked". see
* {@link clickablecomponent} for more detailed information on what a click can be.
*
* @param {eventtarget~event} [event]
* the `keydown`, `tap`, or `click` event that caused this function to be
* called.
*
* @listens tap
* @listens click
*/
;
_proto.handleclick = function handleclick(event) {
// select next rate option
var currentrate = this.player().playbackrate();
var rates = this.playbackrates();
var currentindex = rates.indexof(currentrate); // this get the next rate and it will select first one if the last one currently selected
var newindex = (currentindex + 1) % rates.length;
this.player().playbackrate(rates[newindex]);
}
/**
* on playbackrateschange, update the menu to account for the new items.
*
* @listens player#playbackrateschange
*/
;
_proto.handleplaybackrateschange = function handleplaybackrateschange(event) {
this.update();
}
/**
* get possible playback rates
*
* @return {array}
* all possible playback rates
*/
;
_proto.playbackrates = function playbackrates() {
var player = this.player();
return player.playbackrates && player.playbackrates() || [];
}
/**
* get whether playback rates is supported by the tech
* and an array of playback rates exists
*
* @return {boolean}
* whether changing playback rate is supported
*/
;
_proto.playbackratesupported = function playbackratesupported() {
return this.player().tech_ && this.player().tech_.featuresplaybackrate && this.playbackrates() && this.playbackrates().length > 0;
}
/**
* hide playback rate controls when they're no playback rate options to select
*
* @param {eventtarget~event} [event]
* the event that caused this function to run.
*
* @listens player#loadstart
*/
;
_proto.updatevisibility = function updatevisibility(event) {
if (this.playbackratesupported()) {
this.removeclass('vjs-hidden');
} else {
this.addclass('vjs-hidden');
}
}
/**
* update button label when rate changed
*
* @param {eventtarget~event} [event]
* the event that caused this function to run.
*
* @listens player#ratechange
*/
;
_proto.updatelabel = function updatelabel(event) {
if (this.playbackratesupported()) {
this.labelel_.textcontent = this.player().playbackrate() + 'x';
}
};
return playbackratemenubutton;
}(menubutton);
/**
* the text that should display over the `fullscreentoggle`s controls. added for localization.
*
* @type {string}
* @private
*/
playbackratemenubutton.prototype.controltext_ = 'playback rate';
component$1.registercomponent('playbackratemenubutton', playbackratemenubutton);
/**
* just an empty spacer element that can be used as an append point for plugins, etc.
* also can be used to create space between elements when necessary.
*
* @extends component
*/
var spacer = /*#__pure__*/function (_component) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(spacer, _component);
function spacer() {
return _component.apply(this, arguments) || this;
}
var _proto = spacer.prototype;
/**
* builds the default dom `classname`.
*
* @return {string}
* the dom `classname` for this object.
*/
_proto.buildcssclass = function buildcssclass() {
return "vjs-spacer " + _component.prototype.buildcssclass.call(this);
}
/**
* create the `component`'s dom element
*
* @return {element}
* the element that was created.
*/
;
_proto.createel = function createel(tag, props, attributes) {
if (tag === void 0) {
tag = 'div';
}
if (props === void 0) {
props = {};
}
if (attributes === void 0) {
attributes = {};
}
if (!props.classname) {
props.classname = this.buildcssclass();
}
return _component.prototype.createel.call(this, tag, props, attributes);
};
return spacer;
}(component$1);
component$1.registercomponent('spacer', spacer);
/**
* spacer specifically meant to be used as an insertion point for new plugins, etc.
*
* @extends spacer
*/
var customcontrolspacer = /*#__pure__*/function (_spacer) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(customcontrolspacer, _spacer);
function customcontrolspacer() {
return _spacer.apply(this, arguments) || this;
}
var _proto = customcontrolspacer.prototype;
/**
* builds the default dom `classname`.
*
* @return {string}
* the dom `classname` for this object.
*/
_proto.buildcssclass = function buildcssclass() {
return "vjs-custom-control-spacer " + _spacer.prototype.buildcssclass.call(this);
}
/**
* create the `component`'s dom element
*
* @return {element}
* the element that was created.
*/
;
_proto.createel = function createel() {
return _spacer.prototype.createel.call(this, 'div', {
classname: this.buildcssclass(),
// no-flex/table-cell mode requires there be some content
// in the cell to fill the remaining space of the table.
textcontent: "\xa0"
});
};
return customcontrolspacer;
}(spacer);
component$1.registercomponent('customcontrolspacer', customcontrolspacer);
/**
* container of main controls.
*
* @extends component
*/
var controlbar = /*#__pure__*/function (_component) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(controlbar, _component);
function controlbar() {
return _component.apply(this, arguments) || this;
}
var _proto = controlbar.prototype;
/**
* create the `component`'s dom element
*
* @return {element}
* the element that was created.
*/
_proto.createel = function createel() {
return _component.prototype.createel.call(this, 'div', {
classname: 'vjs-control-bar',
dir: 'ltr'
});
};
return controlbar;
}(component$1);
/**
* default options for `controlbar`
*
* @type {object}
* @private
*/
controlbar.prototype.options_ = {
children: ['playtoggle', 'volumepanel', 'currenttimedisplay', 'timedivider', 'durationdisplay', 'progresscontrol', 'livedisplay', 'seektolive', 'remainingtimedisplay', 'customcontrolspacer', 'playbackratemenubutton', 'chaptersbutton', 'descriptionsbutton', 'subscapsbutton', 'audiotrackbutton', 'fullscreentoggle']
};
if ('exitpictureinpicture' in global_document__webpack_imported_module_1___default.a) {
controlbar.prototype.options_.children.splice(controlbar.prototype.options_.children.length - 1, 0, 'pictureinpicturetoggle');
}
component$1.registercomponent('controlbar', controlbar);
/**
* a display that indicates an error has occurred. this means that the video
* is unplayable.
*
* @extends modaldialog
*/
var errordisplay = /*#__pure__*/function (_modaldialog) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(errordisplay, _modaldialog);
/**
* creates an instance of this class.
*
* @param {player} player
* the `player` that this class should be attached to.
*
* @param {object} [options]
* the key/value store of player options.
*/
function errordisplay(player, options) {
var _this;
_this = _modaldialog.call(this, player, options) || this;
_this.on(player, 'error', function (e) {
return _this.open(e);
});
return _this;
}
/**
* builds the default dom `classname`.
*
* @return {string}
* the dom `classname` for this object.
*
* @deprecated since version 5.
*/
var _proto = errordisplay.prototype;
_proto.buildcssclass = function buildcssclass() {
return "vjs-error-display " + _modaldialog.prototype.buildcssclass.call(this);
}
/**
* gets the localized error message based on the `player`s error.
*
* @return {string}
* the `player`s error message localized or an empty string.
*/
;
_proto.content = function content() {
var error = this.player().error();
return error ? this.localize(error.message) : '';
};
return errordisplay;
}(modaldialog);
/**
* the default options for an `errordisplay`.
*
* @private
*/
errordisplay.prototype.options_ = _babel_runtime_helpers_extends__webpack_imported_module_2___default()({}, modaldialog.prototype.options_, {
pauseonopen: false,
fillalways: true,
temporary: false,
uncloseable: true
});
component$1.registercomponent('errordisplay', errordisplay);
var local_storage_key$1 = 'vjs-text-track-settings';
var color_black = ['#000', 'black'];
var color_blue = ['#00f', 'blue'];
var color_cyan = ['#0ff', 'cyan'];
var color_green = ['#0f0', 'green'];
var color_magenta = ['#f0f', 'magenta'];
var color_red = ['#f00', 'red'];
var color_white = ['#fff', 'white'];
var color_yellow = ['#ff0', 'yellow'];
var opacity_opaque = ['1', 'opaque'];
var opacity_semi = ['0.5', 'semi-transparent'];
var opacity_trans = ['0', 'transparent']; // configuration for the various elements in the dom of this component.
//
// possible keys include:
//
// `default`:
// the default option index. only needs to be provided if not zero.
// `parser`:
// a function which is used to parse the value from the selected option in
// a customized way.
// `selector`:
// the selector used to find the associated element.
var selectconfigs = {
backgroundcolor: {
selector: '.vjs-bg-color > select',
id: 'captions-background-color-%s',
label: 'color',
options: [color_black, color_white, color_red, color_green, color_blue, color_yellow, color_magenta, color_cyan]
},
backgroundopacity: {
selector: '.vjs-bg-opacity > select',
id: 'captions-background-opacity-%s',
label: 'transparency',
options: [opacity_opaque, opacity_semi, opacity_trans]
},
color: {
selector: '.vjs-fg-color > select',
id: 'captions-foreground-color-%s',
label: 'color',
options: [color_white, color_black, color_red, color_green, color_blue, color_yellow, color_magenta, color_cyan]
},
edgestyle: {
selector: '.vjs-edge-style > select',
id: '%s',
label: 'text edge style',
options: [['none', 'none'], ['raised', 'raised'], ['depressed', 'depressed'], ['uniform', 'uniform'], ['dropshadow', 'dropshadow']]
},
fontfamily: {
selector: '.vjs-font-family > select',
id: 'captions-font-family-%s',
label: 'font family',
options: [['proportionalsansserif', 'proportional sans-serif'], ['monospacesansserif', 'monospace sans-serif'], ['proportionalserif', 'proportional serif'], ['monospaceserif', 'monospace serif'], ['casual', 'casual'], ['script', 'script'], ['small-caps', 'small caps']]
},
fontpercent: {
selector: '.vjs-font-percent > select',
id: 'captions-font-size-%s',
label: 'font size',
options: [['0.50', '50%'], ['0.75', '75%'], ['1.00', '100%'], ['1.25', '125%'], ['1.50', '150%'], ['1.75', '175%'], ['2.00', '200%'], ['3.00', '300%'], ['4.00', '400%']],
"default": 2,
parser: function parser(v) {
return v === '1.00' ? null : number(v);
}
},
textopacity: {
selector: '.vjs-text-opacity > select',
id: 'captions-foreground-opacity-%s',
label: 'transparency',
options: [opacity_opaque, opacity_semi]
},
// options for this object are defined below.
windowcolor: {
selector: '.vjs-window-color > select',
id: 'captions-window-color-%s',
label: 'color'
},
// options for this object are defined below.
windowopacity: {
selector: '.vjs-window-opacity > select',
id: 'captions-window-opacity-%s',
label: 'transparency',
options: [opacity_trans, opacity_semi, opacity_opaque]
}
};
selectconfigs.windowcolor.options = selectconfigs.backgroundcolor.options;
/**
* get the actual value of an option.
*
* @param {string} value
* the value to get
*
* @param {function} [parser]
* optional function to adjust the value.
*
* @return {mixed}
* - will be `undefined` if no value exists
* - will be `undefined` if the given value is "none".
* - will be the actual value otherwise.
*
* @private
*/
function parseoptionvalue(value, parser) {
if (parser) {
value = parser(value);
}
if (value && value !== 'none') {
return value;
}
}
/**
* gets the value of the selected element within a element.
*
* @param {element} el
* the element to look in
*
* @param {function} [parser]
* optional function to adjust the value.
*
* @return {mixed}
* - will be `undefined` if no value exists
* - will be `undefined` if the given value is "none".
* - will be the actual value otherwise.
*
* @private
*/
function getselectedoptionvalue(el, parser) {
var value = el.options[el.options.selectedindex].value;
return parseoptionvalue(value, parser);
}
/**
* sets the selected element within a element based on a
* given value.
*
* @param {element} el
* the element to look in.
*
* @param {string} value
* the property to look on.
*
* @param {function} [parser]
* optional function to adjust the value before comparing.
*
* @private
*/
function setselectedoption(el, value, parser) {
if (!value) {
return;
}
for (var i = 0; i < el.options.length; i++) {
if (parseoptionvalue(el.options[i].value, parser) === value) {
el.selectedindex = i;
break;
}
}
}
/**
* manipulate text tracks settings.
*
* @extends modaldialog
*/
var texttracksettings = /*#__pure__*/function (_modaldialog) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(texttracksettings, _modaldialog);
/**
* creates an instance of this class.
*
* @param {player} player
* the `player` that this class should be attached to.
*
* @param {object} [options]
* the key/value store of player options.
*/
function texttracksettings(player, options) {
var _this;
options.temporary = false;
_this = _modaldialog.call(this, player, options) || this;
_this.updatedisplay = _this.updatedisplay.bind(_babel_runtime_helpers_assertthisinitialized__webpack_imported_module_4___default()(_this)); // fill the modal and pretend we have opened it
_this.fill();
_this.hasbeenopened_ = _this.hasbeenfilled_ = true;
_this.enddialog = createel('p', {
classname: 'vjs-control-text',
textcontent: _this.localize('end of dialog window.')
});
_this.el().appendchild(_this.enddialog);
_this.setdefaults(); // grab `persisttexttracksettings` from the player options if not passed in child options
if (options.persisttexttracksettings === undefined) {
_this.options_.persisttexttracksettings = _this.options_.playeroptions.persisttexttracksettings;
}
_this.on(_this.$('.vjs-done-button'), 'click', function () {
_this.savesettings();
_this.close();
});
_this.on(_this.$('.vjs-default-button'), 'click', function () {
_this.setdefaults();
_this.updatedisplay();
});
each(selectconfigs, function (config) {
_this.on(_this.$(config.selector), 'change', _this.updatedisplay);
});
if (_this.options_.persisttexttracksettings) {
_this.restoresettings();
}
return _this;
}
var _proto = texttracksettings.prototype;
_proto.dispose = function dispose() {
this.enddialog = null;
_modaldialog.prototype.dispose.call(this);
}
/**
* create a element with configured options.
*
* @param {string} key
* configuration key to use during creation.
*
* @return {string}
* an html string.
*
* @private
*/
;
_proto.createelselect_ = function createelselect_(key, legendid, type) {
var _this2 = this;
if (legendid === void 0) {
legendid = '';
}
if (type === void 0) {
type = 'label';
}
var config = selectconfigs[key];
var id = config.id.replace('%s', this.id_);
var selectlabelledbyids = [legendid, id].join(' ').trim();
return ["<" + type + " id=\"" + id + "\" class=\"" + (type === 'label' ? 'vjs-label' : '') + "\">", this.localize(config.label), "" + type + ">", ""].concat(config.options.map(function (o) {
var optionid = id + '-' + o[1].replace(/\w+/g, '');
return ["", _this2.localize(o[1]), ' '].join('');
})).concat(' ').join('');
}
/**
* create foreground color element for the component
*
* @return {string}
* an html string.
*
* @private
*/
;
_proto.createelfgcolor_ = function createelfgcolor_() {
var legendid = "captions-text-legend-" + this.id_;
return ['', "", this.localize('text'), ' ', this.createelselect_('color', legendid), '', this.createelselect_('textopacity', legendid), ' ', ' '].join('');
}
/**
* create background color element for the component
*
* @return {string}
* an html string.
*
* @private
*/
;
_proto.createelbgcolor_ = function createelbgcolor_() {
var legendid = "captions-background-" + this.id_;
return ['', "", this.localize('background'), ' ', this.createelselect_('backgroundcolor', legendid), '', this.createelselect_('backgroundopacity', legendid), ' ', ' '].join('');
}
/**
* create window color element for the component
*
* @return {string}
* an html string.
*
* @private
*/
;
_proto.createelwincolor_ = function createelwincolor_() {
var legendid = "captions-window-" + this.id_;
return ['', "", this.localize('window'), ' ', this.createelselect_('windowcolor', legendid), '', this.createelselect_('windowopacity', legendid), ' ', ' '].join('');
}
/**
* create color elements for the component
*
* @return {element}
* the element that was created
*
* @private
*/
;
_proto.createelcolors_ = function createelcolors_() {
return createel('div', {
classname: 'vjs-track-settings-colors',
innerhtml: [this.createelfgcolor_(), this.createelbgcolor_(), this.createelwincolor_()].join('')
});
}
/**
* create font elements for the component
*
* @return {element}
* the element that was created.
*
* @private
*/
;
_proto.createelfont_ = function createelfont_() {
return createel('div', {
classname: 'vjs-track-settings-font',
innerhtml: ['', this.createelselect_('fontpercent', '', 'legend'), ' ', '', this.createelselect_('edgestyle', '', 'legend'), ' ', '', this.createelselect_('fontfamily', '', 'legend'), ' '].join('')
});
}
/**
* create controls for the component
*
* @return {element}
* the element that was created.
*
* @private
*/
;
_proto.createelcontrols_ = function createelcontrols_() {
var defaultsdescription = this.localize('restore all settings to the default values');
return createel('div', {
classname: 'vjs-track-settings-controls',
innerhtml: ["", this.localize('reset'), " " + defaultsdescription + " ", ' ', "" + this.localize('done') + " "].join('')
});
};
_proto.content = function content() {
return [this.createelcolors_(), this.createelfont_(), this.createelcontrols_()];
};
_proto.label = function label() {
return this.localize('caption settings dialog');
};
_proto.description = function description() {
return this.localize('beginning of dialog window. escape will cancel and close the window.');
};
_proto.buildcssclass = function buildcssclass() {
return _modaldialog.prototype.buildcssclass.call(this) + ' vjs-text-track-settings';
}
/**
* gets an object of text track settings (or null).
*
* @return {object}
* an object with config values parsed from the dom or localstorage.
*/
;
_proto.getvalues = function getvalues() {
var _this3 = this;
return reduce(selectconfigs, function (accum, config, key) {
var value = getselectedoptionvalue(_this3.$(config.selector), config.parser);
if (value !== undefined) {
accum[key] = value;
}
return accum;
}, {});
}
/**
* sets text track settings from an object of values.
*
* @param {object} values
* an object with config values parsed from the dom or localstorage.
*/
;
_proto.setvalues = function setvalues(values) {
var _this4 = this;
each(selectconfigs, function (config, key) {
setselectedoption(_this4.$(config.selector), values[key], config.parser);
});
}
/**
* sets all `` elements to their default values.
*/
;
_proto.setdefaults = function setdefaults() {
var _this5 = this;
each(selectconfigs, function (config) {
var index = config.hasownproperty('default') ? config["default"] : 0;
_this5.$(config.selector).selectedindex = index;
});
}
/**
* restore texttrack settings from localstorage
*/
;
_proto.restoresettings = function restoresettings() {
var values;
try {
values = json.parse(global_window__webpack_imported_module_0___default.a.localstorage.getitem(local_storage_key$1));
} catch (err) {
log$1.warn(err);
}
if (values) {
this.setvalues(values);
}
}
/**
* save text track settings to localstorage
*/
;
_proto.savesettings = function savesettings() {
if (!this.options_.persisttexttracksettings) {
return;
}
var values = this.getvalues();
try {
if (object.keys(values).length) {
global_window__webpack_imported_module_0___default.a.localstorage.setitem(local_storage_key$1, json.stringify(values));
} else {
global_window__webpack_imported_module_0___default.a.localstorage.removeitem(local_storage_key$1);
}
} catch (err) {
log$1.warn(err);
}
}
/**
* update display of text track settings
*/
;
_proto.updatedisplay = function updatedisplay() {
var ttdisplay = this.player_.getchild('texttrackdisplay');
if (ttdisplay) {
ttdisplay.updatedisplay();
}
}
/**
* conditionally blur the element and refocus the captions button
*
* @private
*/
;
_proto.conditionalblur_ = function conditionalblur_() {
this.previouslyactiveel_ = null;
var cb = this.player_.controlbar;
var subscapsbtn = cb && cb.subscapsbutton;
var ccbtn = cb && cb.captionsbutton;
if (subscapsbtn) {
subscapsbtn.focus();
} else if (ccbtn) {
ccbtn.focus();
}
};
return texttracksettings;
}(modaldialog);
component$1.registercomponent('texttracksettings', texttracksettings);
/**
* a resize manager. it is in charge of triggering `playerresize` on the player in the right conditions.
*
* it'll either create an iframe and use a debounced resize handler on it or use the new {@link https://wicg.github.io/resizeobserver/|resizeobserver}.
*
* if the resizeobserver is available natively, it will be used. a polyfill can be passed in as an option.
* if a `playerresize` event is not needed, the resizemanager component can be removed from the player, see the example below.
* @example how to disable the resize manager
* const player = videojs('#vid', {
* resizemanager: false
* });
*
* @see {@link https://wicg.github.io/resizeobserver/|resizeobserver specification}
*
* @extends component
*/
var resizemanager = /*#__pure__*/function (_component) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(resizemanager, _component);
/**
* create the resizemanager.
*
* @param {object} player
* the `player` that this class should be attached to.
*
* @param {object} [options]
* the key/value store of resizemanager options.
*
* @param {object} [options.resizeobserver]
* a polyfill for resizeobserver can be passed in here.
* if this is set to null it will ignore the native resizeobserver and fall back to the iframe fallback.
*/
function resizemanager(player, options) {
var _this;
var resize_observer_available = options.resizeobserver || global_window__webpack_imported_module_0___default.a.resizeobserver; // if `null` was passed, we want to disable the resizeobserver
if (options.resizeobserver === null) {
resize_observer_available = false;
} // only create an element when resizeobserver isn't available
var options_ = mergeoptions$3({
createel: !resize_observer_available,
reporttouchactivity: false
}, options);
_this = _component.call(this, player, options_) || this;
_this.resizeobserver = options.resizeobserver || global_window__webpack_imported_module_0___default.a.resizeobserver;
_this.loadlistener_ = null;
_this.resizeobserver_ = null;
_this.debouncedhandler_ = debounce(function () {
_this.resizehandler();
}, 100, false, _babel_runtime_helpers_assertthisinitialized__webpack_imported_module_4___default()(_this));
if (resize_observer_available) {
_this.resizeobserver_ = new _this.resizeobserver(_this.debouncedhandler_);
_this.resizeobserver_.observe(player.el());
} else {
_this.loadlistener_ = function () {
if (!_this.el_ || !_this.el_.contentwindow) {
return;
}
var debouncedhandler_ = _this.debouncedhandler_;
var unloadlistener_ = _this.unloadlistener_ = function () {
off(this, 'resize', debouncedhandler_);
off(this, 'unload', unloadlistener_);
unloadlistener_ = null;
}; // safari and edge can unload the iframe before resizemanager dispose
// we have to dispose of event handlers correctly before that happens
on(_this.el_.contentwindow, 'unload', unloadlistener_);
on(_this.el_.contentwindow, 'resize', debouncedhandler_);
};
_this.one('load', _this.loadlistener_);
}
return _this;
}
var _proto = resizemanager.prototype;
_proto.createel = function createel() {
return _component.prototype.createel.call(this, 'iframe', {
classname: 'vjs-resize-manager',
tabindex: -1,
title: this.localize('no content')
}, {
'aria-hidden': 'true'
});
}
/**
* called when a resize is triggered on the iframe or a resize is observed via the resizeobserver
*
* @fires player#playerresize
*/
;
_proto.resizehandler = function resizehandler() {
/**
* called when the player size has changed
*
* @event player#playerresize
* @type {eventtarget~event}
*/
// make sure player is still around to trigger
// prevents this from causing an error after dispose
if (!this.player_ || !this.player_.trigger) {
return;
}
this.player_.trigger('playerresize');
};
_proto.dispose = function dispose() {
if (this.debouncedhandler_) {
this.debouncedhandler_.cancel();
}
if (this.resizeobserver_) {
if (this.player_.el()) {
this.resizeobserver_.unobserve(this.player_.el());
}
this.resizeobserver_.disconnect();
}
if (this.loadlistener_) {
this.off('load', this.loadlistener_);
}
if (this.el_ && this.el_.contentwindow && this.unloadlistener_) {
this.unloadlistener_.call(this.el_.contentwindow);
}
this.resizeobserver = null;
this.resizeobserver = null;
this.debouncedhandler_ = null;
this.loadlistener_ = null;
_component.prototype.dispose.call(this);
};
return resizemanager;
}(component$1);
component$1.registercomponent('resizemanager', resizemanager);
var defaults = {
trackingthreshold: 20,
livetolerance: 15
};
/*
track when we are at the live edge, and other helpers for live playback */
/**
* a class for checking live current time and determining when the player
* is at or behind the live edge.
*/
var livetracker = /*#__pure__*/function (_component) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(livetracker, _component);
/**
* creates an instance of this class.
*
* @param {player} player
* the `player` that this class should be attached to.
*
* @param {object} [options]
* the key/value store of player options.
*
* @param {number} [options.trackingthreshold=20]
* number of seconds of live window (seekableend - seekablestart) that
* media needs to have before the liveui will be shown.
*
* @param {number} [options.livetolerance=15]
* number of seconds behind live that we have to be
* before we will be considered non-live. note that this will only
* be used when playing at the live edge. this allows large seekable end
* changes to not effect wether we are live or not.
*/
function livetracker(player, options) {
var _this;
// livetracker does not need an element
var options_ = mergeoptions$3(defaults, options, {
createel: false
});
_this = _component.call(this, player, options_) || this;
_this.handlevisibilitychange_ = function (e) {
return _this.handlevisibilitychange(e);
};
_this.tracklivehandler_ = function () {
return _this.tracklive_();
};
_this.handleplay_ = function (e) {
return _this.handleplay(e);
};
_this.handlefirsttimeupdate_ = function (e) {
return _this.handlefirsttimeupdate(e);
};
_this.handleseeked_ = function (e) {
return _this.handleseeked(e);
};
_this.seektoliveedge_ = function (e) {
return _this.seektoliveedge(e);
};
_this.reset_();
_this.on(_this.player_, 'durationchange', function (e) {
return _this.handledurationchange(e);
}); // we should try to toggle tracking on canplay as native playback engines, like safari
// may not have the proper values for things like seekableend until then
_this.on(_this.player_, 'canplay', function () {
return _this.toggletracking();
}); // we don't need to track live playback if the document is hidden,
// also, tracking when the document is hidden can
// cause the cpu to spike and eventually crash the page on ie11.
if (ie_version && 'hidden' in global_document__webpack_imported_module_1___default.a && 'visibilitystate' in global_document__webpack_imported_module_1___default.a) {
_this.on(global_document__webpack_imported_module_1___default.a, 'visibilitychange', _this.handlevisibilitychange_);
}
return _this;
}
/**
* toggle tracking based on document visiblility
*/
var _proto = livetracker.prototype;
_proto.handlevisibilitychange = function handlevisibilitychange() {
if (this.player_.duration() !== infinity) {
return;
}
if (global_document__webpack_imported_module_1___default.a.hidden) {
this.stoptracking();
} else {
this.starttracking();
}
}
/**
* all the functionality for tracking when seek end changes
* and for tracking how far past seek end we should be
*/
;
_proto.tracklive_ = function tracklive_() {
var seekable = this.player_.seekable(); // skip undefined seekable
if (!seekable || !seekable.length) {
return;
}
var newtime = number(global_window__webpack_imported_module_0___default.a.performance.now().tofixed(4));
var deltatime = this.lasttime_ === -1 ? 0 : (newtime - this.lasttime_) / 1000;
this.lasttime_ = newtime;
this.pastseekend_ = this.pastseekend() + deltatime;
var livecurrenttime = this.livecurrenttime();
var currenttime = this.player_.currenttime(); // we are behind live if any are true
// 1. the player is paused
// 2. the user seeked to a location 2 seconds away from live
// 3. the difference between live and current time is greater
// livetolerance which defaults to 15s
var isbehind = this.player_.paused() || this.seekedbehindlive_ || math.abs(livecurrenttime - currenttime) > this.options_.livetolerance; // we cannot be behind if
// 1. until we have not seen a timeupdate yet
// 2. livecurrenttime is infinity, which happens on android and native safari
if (!this.timeupdateseen_ || livecurrenttime === infinity) {
isbehind = false;
}
if (isbehind !== this.behindliveedge_) {
this.behindliveedge_ = isbehind;
this.trigger('liveedgechange');
}
}
/**
* handle a durationchange event on the player
* and start/stop tracking accordingly.
*/
;
_proto.handledurationchange = function handledurationchange() {
this.toggletracking();
}
/**
* start/stop tracking
*/
;
_proto.toggletracking = function toggletracking() {
if (this.player_.duration() === infinity && this.livewindow() >= this.options_.trackingthreshold) {
if (this.player_.options_.liveui) {
this.player_.addclass('vjs-liveui');
}
this.starttracking();
} else {
this.player_.removeclass('vjs-liveui');
this.stoptracking();
}
}
/**
* start tracking live playback
*/
;
_proto.starttracking = function starttracking() {
if (this.istracking()) {
return;
} // if we haven't seen a timeupdate, we need to check whether playback
// began before this component started tracking. this can happen commonly
// when using autoplay.
if (!this.timeupdateseen_) {
this.timeupdateseen_ = this.player_.hasstarted();
}
this.trackinginterval_ = this.setinterval(this.tracklivehandler_, update_refresh_interval);
this.tracklive_();
this.on(this.player_, ['play', 'pause'], this.tracklivehandler_);
if (!this.timeupdateseen_) {
this.one(this.player_, 'play', this.handleplay_);
this.one(this.player_, 'timeupdate', this.handlefirsttimeupdate_);
} else {
this.on(this.player_, 'seeked', this.handleseeked_);
}
}
/**
* handle the first timeupdate on the player if it wasn't already playing
* when live tracker started tracking.
*/
;
_proto.handlefirsttimeupdate = function handlefirsttimeupdate() {
this.timeupdateseen_ = true;
this.on(this.player_, 'seeked', this.handleseeked_);
}
/**
* keep track of what time a seek starts, and listen for seeked
* to find where a seek ends.
*/
;
_proto.handleseeked = function handleseeked() {
var timediff = math.abs(this.livecurrenttime() - this.player_.currenttime());
this.seekedbehindlive_ = this.nextseekedfromuser_ && timediff > 2;
this.nextseekedfromuser_ = false;
this.tracklive_();
}
/**
* handle the first play on the player, and make sure that we seek
* right to the live edge.
*/
;
_proto.handleplay = function handleplay() {
this.one(this.player_, 'timeupdate', this.seektoliveedge_);
}
/**
* stop tracking, and set all internal variables to
* their initial value.
*/
;
_proto.reset_ = function reset_() {
this.lasttime_ = -1;
this.pastseekend_ = 0;
this.lastseekend_ = -1;
this.behindliveedge_ = true;
this.timeupdateseen_ = false;
this.seekedbehindlive_ = false;
this.nextseekedfromuser_ = false;
this.clearinterval(this.trackinginterval_);
this.trackinginterval_ = null;
this.off(this.player_, ['play', 'pause'], this.tracklivehandler_);
this.off(this.player_, 'seeked', this.handleseeked_);
this.off(this.player_, 'play', this.handleplay_);
this.off(this.player_, 'timeupdate', this.handlefirsttimeupdate_);
this.off(this.player_, 'timeupdate', this.seektoliveedge_);
}
/**
* the next seeked event is from the user. meaning that any seek
* > 2s behind live will be considered behind live for real and
* livetolerance will be ignored.
*/
;
_proto.nextseekedfromuser = function nextseekedfromuser() {
this.nextseekedfromuser_ = true;
}
/**
* stop tracking live playback
*/
;
_proto.stoptracking = function stoptracking() {
if (!this.istracking()) {
return;
}
this.reset_();
this.trigger('liveedgechange');
}
/**
* a helper to get the player seekable end
* so that we don't have to null check everywhere
*
* @return {number}
* the furthest seekable end or infinity.
*/
;
_proto.seekableend = function seekableend() {
var seekable = this.player_.seekable();
var seekableends = [];
var i = seekable ? seekable.length : 0;
while (i--) {
seekableends.push(seekable.end(i));
} // grab the furthest seekable end after sorting, or if there are none
// default to infinity
return seekableends.length ? seekableends.sort()[seekableends.length - 1] : infinity;
}
/**
* a helper to get the player seekable start
* so that we don't have to null check everywhere
*
* @return {number}
* the earliest seekable start or 0.
*/
;
_proto.seekablestart = function seekablestart() {
var seekable = this.player_.seekable();
var seekablestarts = [];
var i = seekable ? seekable.length : 0;
while (i--) {
seekablestarts.push(seekable.start(i));
} // grab the first seekable start after sorting, or if there are none
// default to 0
return seekablestarts.length ? seekablestarts.sort()[0] : 0;
}
/**
* get the live time window aka
* the amount of time between seekable start and
* live current time.
*
* @return {number}
* the amount of seconds that are seekable in
* the live video.
*/
;
_proto.livewindow = function livewindow() {
var livecurrenttime = this.livecurrenttime(); // if livecurrentime is infinity then we don't have a livewindow at all
if (livecurrenttime === infinity) {
return 0;
}
return livecurrenttime - this.seekablestart();
}
/**
* determines if the player is live, only checks if this component
* is tracking live playback or not
*
* @return {boolean}
* wether livetracker is tracking
*/
;
_proto.islive = function islive() {
return this.istracking();
}
/**
* determines if currenttime is at the live edge and won't fall behind
* on each seekableendchange
*
* @return {boolean}
* wether playback is at the live edge
*/
;
_proto.atliveedge = function atliveedge() {
return !this.behindliveedge();
}
/**
* get what we expect the live current time to be
*
* @return {number}
* the expected live current time
*/
;
_proto.livecurrenttime = function livecurrenttime() {
return this.pastseekend() + this.seekableend();
}
/**
* the number of seconds that have occured after seekable end
* changed. this will be reset to 0 once seekable end changes.
*
* @return {number}
* seconds past the current seekable end
*/
;
_proto.pastseekend = function pastseekend() {
var seekableend = this.seekableend();
if (this.lastseekend_ !== -1 && seekableend !== this.lastseekend_) {
this.pastseekend_ = 0;
}
this.lastseekend_ = seekableend;
return this.pastseekend_;
}
/**
* if we are currently behind the live edge, aka currenttime will be
* behind on a seekableendchange
*
* @return {boolean}
* if we are behind the live edge
*/
;
_proto.behindliveedge = function behindliveedge() {
return this.behindliveedge_;
}
/**
* wether live tracker is currently tracking or not.
*/
;
_proto.istracking = function istracking() {
return typeof this.trackinginterval_ === 'number';
}
/**
* seek to the live edge if we are behind the live edge
*/
;
_proto.seektoliveedge = function seektoliveedge() {
this.seekedbehindlive_ = false;
if (this.atliveedge()) {
return;
}
this.nextseekedfromuser_ = false;
this.player_.currenttime(this.livecurrenttime());
}
/**
* dispose of livetracker
*/
;
_proto.dispose = function dispose() {
this.off(global_document__webpack_imported_module_1___default.a, 'visibilitychange', this.handlevisibilitychange_);
this.stoptracking();
_component.prototype.dispose.call(this);
};
return livetracker;
}(component$1);
component$1.registercomponent('livetracker', livetracker);
/**
* this function is used to fire a sourceset when there is something
* similar to `mediael.load()` being called. it will try to find the source via
* the `src` attribute and then the `` elements. it will then fire `sourceset`
* with the source that was found or empty string if we cannot know. if it cannot
* find a source then `sourceset` will not be fired.
*
* @param {html5} tech
* the tech object that sourceset was setup on
*
* @return {boolean}
* returns false if the sourceset was not fired and true otherwise.
*/
var sourcesetload = function sourcesetload(tech) {
var el = tech.el(); // if `el.src` is set, that source will be loaded.
if (el.hasattribute('src')) {
tech.triggersourceset(el.src);
return true;
}
/**
* since there isn't a src property on the media element, source elements will be used for
* implementing the source selection algorithm. this happens asynchronously and
* for most cases were there is more than one source we cannot tell what source will
* be loaded, without re-implementing the source selection algorithm. at this time we are not
* going to do that. there are three special cases that we do handle here though:
*
* 1. if there are no sources, do not fire `sourceset`.
* 2. if there is only one `` with a `src` property/attribute that is our `src`
* 3. if there is more than one `` but all of them have the same `src` url.
* that will be our src.
*/
var sources = tech.$$('source');
var srcurls = [];
var src = ''; // if there are no sources, do not fire sourceset
if (!sources.length) {
return false;
} // only count valid/non-duplicate source elements
for (var i = 0; i < sources.length; i++) {
var url = sources[i].src;
if (url && srcurls.indexof(url) === -1) {
srcurls.push(url);
}
} // there were no valid sources
if (!srcurls.length) {
return false;
} // there is only one valid source element url
// use that
if (srcurls.length === 1) {
src = srcurls[0];
}
tech.triggersourceset(src);
return true;
};
/**
* our implementation of an `innerhtml` descriptor for browsers
* that do not have one.
*/
var innerhtmldescriptorpolyfill = object.defineproperty({}, 'innerhtml', {
get: function get() {
return this.clonenode(true).innerhtml;
},
set: function set(v) {
// make a dummy node to use innerhtml on
var dummy = global_document__webpack_imported_module_1___default.a.createelement(this.nodename.tolowercase()); // set innerhtml to the value provided
dummy.innerhtml = v; // make a document fragment to hold the nodes from dummy
var docfrag = global_document__webpack_imported_module_1___default.a.createdocumentfragment(); // copy all of the nodes created by the innerhtml on dummy
// to the document fragment
while (dummy.childnodes.length) {
docfrag.appendchild(dummy.childnodes[0]);
} // remove content
this.innertext = ''; // now we add all of that html in one by appending the
// document fragment. this is how innerhtml does it.
global_window__webpack_imported_module_0___default.a.element.prototype.appendchild.call(this, docfrag); // then return the result that innerhtml's setter would
return this.innerhtml;
}
});
/**
* get a property descriptor given a list of priorities and the
* property to get.
*/
var getdescriptor = function getdescriptor(priority, prop) {
var descriptor = {};
for (var i = 0; i < priority.length; i++) {
descriptor = object.getownpropertydescriptor(priority[i], prop);
if (descriptor && descriptor.set && descriptor.get) {
break;
}
}
descriptor.enumerable = true;
descriptor.configurable = true;
return descriptor;
};
var getinnerhtmldescriptor = function getinnerhtmldescriptor(tech) {
return getdescriptor([tech.el(), global_window__webpack_imported_module_0___default.a.htmlmediaelement.prototype, global_window__webpack_imported_module_0___default.a.element.prototype, innerhtmldescriptorpolyfill], 'innerhtml');
};
/**
* patches browser internal functions so that we can tell synchronously
* if a `` was appended to the media element. for some reason this
* causes a `sourceset` if the the media element is ready and has no source.
* this happens when:
* - the page has just loaded and the media element does not have a source.
* - the media element was emptied of all sources, then `load()` was called.
*
* it does this by patching the following functions/properties when they are supported:
*
* - `append()` - can be used to add a `` element to the media element
* - `appendchild()` - can be used to add a `` element to the media element
* - `insertadjacenthtml()` - can be used to add a `` element to the media element
* - `innerhtml` - can be used to add a `` element to the media element
*
* @param {html5} tech
* the tech object that sourceset is being setup on.
*/
var firstsourcewatch = function firstsourcewatch(tech) {
var el = tech.el(); // make sure firstsourcewatch isn't setup twice.
if (el.resetsourcewatch_) {
return;
}
var old = {};
var innerdescriptor = getinnerhtmldescriptor(tech);
var appendwrapper = function appendwrapper(appendfn) {
return function () {
for (var _len = arguments.length, args = new array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
var retval = appendfn.apply(el, args);
sourcesetload(tech);
return retval;
};
};
['append', 'appendchild', 'insertadjacenthtml'].foreach(function (k) {
if (!el[k]) {
return;
} // store the old function
old[k] = el[k]; // call the old function with a sourceset if a source
// was loaded
el[k] = appendwrapper(old[k]);
});
object.defineproperty(el, 'innerhtml', mergeoptions$3(innerdescriptor, {
set: appendwrapper(innerdescriptor.set)
}));
el.resetsourcewatch_ = function () {
el.resetsourcewatch_ = null;
object.keys(old).foreach(function (k) {
el[k] = old[k];
});
object.defineproperty(el, 'innerhtml', innerdescriptor);
}; // on the first sourceset, we need to revert our changes
tech.one('sourceset', el.resetsourcewatch_);
};
/**
* our implementation of a `src` descriptor for browsers
* that do not have one.
*/
var srcdescriptorpolyfill = object.defineproperty({}, 'src', {
get: function get() {
if (this.hasattribute('src')) {
return getabsoluteurl(global_window__webpack_imported_module_0___default.a.element.prototype.getattribute.call(this, 'src'));
}
return '';
},
set: function set(v) {
global_window__webpack_imported_module_0___default.a.element.prototype.setattribute.call(this, 'src', v);
return v;
}
});
var getsrcdescriptor = function getsrcdescriptor(tech) {
return getdescriptor([tech.el(), global_window__webpack_imported_module_0___default.a.htmlmediaelement.prototype, srcdescriptorpolyfill], 'src');
};
/**
* setup `sourceset` handling on the `html5` tech. this function
* patches the following element properties/functions:
*
* - `src` - to determine when `src` is set
* - `setattribute()` - to determine when `src` is set
* - `load()` - this re-triggers the source selection algorithm, and can
* cause a sourceset.
*
* if there is no source when we are adding `sourceset` support or during a `load()`
* we also patch the functions listed in `firstsourcewatch`.
*
* @param {html5} tech
* the tech to patch
*/
var setupsourceset = function setupsourceset(tech) {
if (!tech.featuressourceset) {
return;
}
var el = tech.el(); // make sure sourceset isn't setup twice.
if (el.resetsourceset_) {
return;
}
var srcdescriptor = getsrcdescriptor(tech);
var oldsetattribute = el.setattribute;
var oldload = el.load;
object.defineproperty(el, 'src', mergeoptions$3(srcdescriptor, {
set: function set(v) {
var retval = srcdescriptor.set.call(el, v); // we use the getter here to get the actual value set on src
tech.triggersourceset(el.src);
return retval;
}
}));
el.setattribute = function (n, v) {
var retval = oldsetattribute.call(el, n, v);
if (/src/i.test(n)) {
tech.triggersourceset(el.src);
}
return retval;
};
el.load = function () {
var retval = oldload.call(el); // if load was called, but there was no source to fire
// sourceset on. we have to watch for a source append
// as that can trigger a `sourceset` when the media element
// has no source
if (!sourcesetload(tech)) {
tech.triggersourceset('');
firstsourcewatch(tech);
}
return retval;
};
if (el.currentsrc) {
tech.triggersourceset(el.currentsrc);
} else if (!sourcesetload(tech)) {
firstsourcewatch(tech);
}
el.resetsourceset_ = function () {
el.resetsourceset_ = null;
el.load = oldload;
el.setattribute = oldsetattribute;
object.defineproperty(el, 'src', srcdescriptor);
if (el.resetsourcewatch_) {
el.resetsourcewatch_();
}
};
};
/**
* object.defineproperty but "lazy", which means that the value is only set after
* it retrieved the first time, rather than being set right away.
*
* @param {object} obj the object to set the property on
* @param {string} key the key for the property to set
* @param {function} getvalue the function used to get the value when it is needed.
* @param {boolean} setter wether a setter shoould be allowed or not
*/
var definelazyproperty = function definelazyproperty(obj, key, getvalue, setter) {
if (setter === void 0) {
setter = true;
}
var set = function set(value) {
return object.defineproperty(obj, key, {
value: value,
enumerable: true,
writable: true
});
};
var options = {
configurable: true,
enumerable: true,
get: function get() {
var value = getvalue();
set(value);
return value;
}
};
if (setter) {
options.set = set;
}
return object.defineproperty(obj, key, options);
};
/**
* html5 media controller - wrapper for html5 media api
*
* @mixes tech~sourcehandleradditions
* @extends tech
*/
var html5 = /*#__pure__*/function (_tech) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(html5, _tech);
/**
* create an instance of this tech.
*
* @param {object} [options]
* the key/value store of player options.
*
* @param {component~readycallback} ready
* callback function to call when the `html5` tech is ready.
*/
function html5(options, ready) {
var _this;
_this = _tech.call(this, options, ready) || this;
var source = options.source;
var crossorigintracks = false;
_this.featuresvideoframecallback = _this.featuresvideoframecallback && _this.el_.tagname === 'video'; // set the source if one is provided
// 1) check if the source is new (if not, we want to keep the original so playback isn't interrupted)
// 2) check to see if the network state of the tag was failed at init, and if so, reset the source
// anyway so the error gets fired.
if (source && (_this.el_.currentsrc !== source.src || options.tag && options.tag.initnetworkstate_ === 3)) {
_this.setsource(source);
} else {
_this.handlelateinit_(_this.el_);
} // setup sourceset after late sourceset/init
if (options.enablesourceset) {
_this.setupsourcesethandling_();
}
_this.isscrubbing_ = false;
if (_this.el_.haschildnodes()) {
var nodes = _this.el_.childnodes;
var nodeslength = nodes.length;
var removenodes = [];
while (nodeslength--) {
var node = nodes[nodeslength];
var nodename = node.nodename.tolowercase();
if (nodename === 'track') {
if (!_this.featuresnativetexttracks) {
// empty video tag tracks so the built-in player doesn't use them also.
// this may not be fast enough to stop html5 browsers from reading the tags
// so we'll need to turn off any default tracks if we're manually doing
// captions and subtitles. videoelement.texttracks
removenodes.push(node);
} else {
// store htmltrackelement and texttrack to remote list
_this.remotetexttrackels().addtrackelement_(node);
_this.remotetexttracks().addtrack(node.track);
_this.texttracks().addtrack(node.track);
if (!crossorigintracks && !_this.el_.hasattribute('crossorigin') && iscrossorigin(node.src)) {
crossorigintracks = true;
}
}
}
}
for (var i = 0; i < removenodes.length; i++) {
_this.el_.removechild(removenodes[i]);
}
}
_this.proxynativetracks_();
if (_this.featuresnativetexttracks && crossorigintracks) {
log$1.warn('text tracks are being loaded from another origin but the crossorigin attribute isn\'t used.\n' + 'this may prevent text tracks from loading.');
} // prevent ios safari from disabling metadata text tracks during native playback
_this.restoremetadatatracksiniosnativeplayer_(); // determine if native controls should be used
// our goal should be to get the custom controls on mobile solid everywhere
// so we can remove this all together. right now this will block custom
// controls on touch enabled laptops like the chrome pixel
if ((touch_enabled || is_iphone || is_native_android) && options.nativecontrolsfortouch === true) {
_this.setcontrols(true);
} // on ios, we want to proxy `webkitbeginfullscreen` and `webkitendfullscreen`
// into a `fullscreenchange` event
_this.proxywebkitfullscreen_();
_this.triggerready();
return _this;
}
/**
* dispose of `html5` media element and remove all tracks.
*/
var _proto = html5.prototype;
_proto.dispose = function dispose() {
if (this.el_ && this.el_.resetsourceset_) {
this.el_.resetsourceset_();
}
html5.disposemediaelement(this.el_);
this.options_ = null; // tech will handle clearing of the emulated track list
_tech.prototype.dispose.call(this);
}
/**
* modify the media element so that we can detect when
* the source is changed. fires `sourceset` just after the source has changed
*/
;
_proto.setupsourcesethandling_ = function setupsourcesethandling_() {
setupsourceset(this);
}
/**
* when a captions track is enabled in the ios safari native player, all other
* tracks are disabled (including metadata tracks), which nulls all of their
* associated cue points. this will restore metadata tracks to their pre-fullscreen
* state in those cases so that cue points are not needlessly lost.
*
* @private
*/
;
_proto.restoremetadatatracksiniosnativeplayer_ = function restoremetadatatracksiniosnativeplayer_() {
var texttracks = this.texttracks();
var metadatatracksprefullscreenstate; // captures a snapshot of every metadata track's current state
var takemetadatatracksnapshot = function takemetadatatracksnapshot() {
metadatatracksprefullscreenstate = [];
for (var i = 0; i < texttracks.length; i++) {
var track = texttracks[i];
if (track.kind === 'metadata') {
metadatatracksprefullscreenstate.push({
track: track,
storedmode: track.mode
});
}
}
}; // snapshot each metadata track's initial state, and update the snapshot
// each time there is a track 'change' event
takemetadatatracksnapshot();
texttracks.addeventlistener('change', takemetadatatracksnapshot);
this.on('dispose', function () {
return texttracks.removeeventlistener('change', takemetadatatracksnapshot);
});
var restoretrackmode = function restoretrackmode() {
for (var i = 0; i < metadatatracksprefullscreenstate.length; i++) {
var storedtrack = metadatatracksprefullscreenstate[i];
if (storedtrack.track.mode === 'disabled' && storedtrack.track.mode !== storedtrack.storedmode) {
storedtrack.track.mode = storedtrack.storedmode;
}
} // we only want this handler to be executed on the first 'change' event
texttracks.removeeventlistener('change', restoretrackmode);
}; // when we enter fullscreen playback, stop updating the snapshot and
// restore all track modes to their pre-fullscreen state
this.on('webkitbeginfullscreen', function () {
texttracks.removeeventlistener('change', takemetadatatracksnapshot); // remove the listener before adding it just in case it wasn't previously removed
texttracks.removeeventlistener('change', restoretrackmode);
texttracks.addeventlistener('change', restoretrackmode);
}); // start updating the snapshot again after leaving fullscreen
this.on('webkitendfullscreen', function () {
// remove the listener before adding it just in case it wasn't previously removed
texttracks.removeeventlistener('change', takemetadatatracksnapshot);
texttracks.addeventlistener('change', takemetadatatracksnapshot); // remove the restoretrackmode handler in case it wasn't triggered during fullscreen playback
texttracks.removeeventlistener('change', restoretrackmode);
});
}
/**
* attempt to force override of tracks for the given type
*
* @param {string} type - track type to override, possible values include 'audio',
* 'video', and 'text'.
* @param {boolean} override - if set to true native audio/video will be overridden,
* otherwise native audio/video will potentially be used.
* @private
*/
;
_proto.overridenative_ = function overridenative_(type, override) {
var _this2 = this;
// if there is no behavioral change don't add/remove listeners
if (override !== this["featuresnative" + type + "tracks"]) {
return;
}
var lowercasetype = type.tolowercase();
if (this[lowercasetype + "trackslisteners_"]) {
object.keys(this[lowercasetype + "trackslisteners_"]).foreach(function (eventname) {
var eltracks = _this2.el()[lowercasetype + "tracks"];
eltracks.removeeventlistener(eventname, _this2[lowercasetype + "trackslisteners_"][eventname]);
});
}
this["featuresnative" + type + "tracks"] = !override;
this[lowercasetype + "trackslisteners_"] = null;
this.proxynativetracksfortype_(lowercasetype);
}
/**
* attempt to force override of native audio tracks.
*
* @param {boolean} override - if set to true native audio will be overridden,
* otherwise native audio will potentially be used.
*/
;
_proto.overridenativeaudiotracks = function overridenativeaudiotracks(override) {
this.overridenative_('audio', override);
}
/**
* attempt to force override of native video tracks.
*
* @param {boolean} override - if set to true native video will be overridden,
* otherwise native video will potentially be used.
*/
;
_proto.overridenativevideotracks = function overridenativevideotracks(override) {
this.overridenative_('video', override);
}
/**
* proxy native track list events for the given type to our track
* lists if the browser we are playing in supports that type of track list.
*
* @param {string} name - track type; values include 'audio', 'video', and 'text'
* @private
*/
;
_proto.proxynativetracksfortype_ = function proxynativetracksfortype_(name) {
var _this3 = this;
var props = normal[name];
var eltracks = this.el()[props.gettername];
var techtracks = this[props.gettername]();
if (!this["featuresnative" + props.capitalname + "tracks"] || !eltracks || !eltracks.addeventlistener) {
return;
}
var listeners = {
change: function change(e) {
var event = {
type: 'change',
target: techtracks,
currenttarget: techtracks,
srcelement: techtracks
};
techtracks.trigger(event); // if we are a text track change event, we should also notify the
// remote text track list. this can potentially cause a false positive
// if we were to get a change event on a non-remote track and
// we triggered the event on the remote text track list which doesn't
// contain that track. however, best practices mean looping through the
// list of tracks and searching for the appropriate mode value, so,
// this shouldn't pose an issue
if (name === 'text') {
_this3[remote.remotetext.gettername]().trigger(event);
}
},
addtrack: function addtrack(e) {
techtracks.addtrack(e.track);
},
removetrack: function removetrack(e) {
techtracks.removetrack(e.track);
}
};
var removeoldtracks = function removeoldtracks() {
var removetracks = [];
for (var i = 0; i < techtracks.length; i++) {
var found = false;
for (var j = 0; j < eltracks.length; j++) {
if (eltracks[j] === techtracks[i]) {
found = true;
break;
}
}
if (!found) {
removetracks.push(techtracks[i]);
}
}
while (removetracks.length) {
techtracks.removetrack(removetracks.shift());
}
};
this[props.gettername + 'listeners_'] = listeners;
object.keys(listeners).foreach(function (eventname) {
var listener = listeners[eventname];
eltracks.addeventlistener(eventname, listener);
_this3.on('dispose', function (e) {
return eltracks.removeeventlistener(eventname, listener);
});
}); // remove (native) tracks that are not used anymore
this.on('loadstart', removeoldtracks);
this.on('dispose', function (e) {
return _this3.off('loadstart', removeoldtracks);
});
}
/**
* proxy all native track list events to our track lists if the browser we are playing
* in supports that type of track list.
*
* @private
*/
;
_proto.proxynativetracks_ = function proxynativetracks_() {
var _this4 = this;
normal.names.foreach(function (name) {
_this4.proxynativetracksfortype_(name);
});
}
/**
* create the `html5` tech's dom element.
*
* @return {element}
* the element that gets created.
*/
;
_proto.createel = function createel() {
var el = this.options_.tag; // check if this browser supports moving the element into the box.
// on the iphone video will break if you move the element,
// so we have to create a brand new element.
// if we ingested the player div, we do not need to move the media element.
if (!el || !(this.options_.playerelingest || this.movingmediaelementindom)) {
// if the original tag is still there, clone and remove it.
if (el) {
var clone = el.clonenode(true);
if (el.parentnode) {
el.parentnode.insertbefore(clone, el);
}
html5.disposemediaelement(el);
el = clone;
} else {
el = global_document__webpack_imported_module_1___default.a.createelement('video'); // determine if native controls should be used
var tagattributes = this.options_.tag && getattributes(this.options_.tag);
var attributes = mergeoptions$3({}, tagattributes);
if (!touch_enabled || this.options_.nativecontrolsfortouch !== true) {
delete attributes.controls;
}
setattributes(el, assign(attributes, {
id: this.options_.techid,
"class": 'vjs-tech'
}));
}
el.playerid = this.options_.playerid;
}
if (typeof this.options_.preload !== 'undefined') {
setattribute(el, 'preload', this.options_.preload);
}
if (this.options_.disablepictureinpicture !== undefined) {
el.disablepictureinpicture = this.options_.disablepictureinpicture;
} // update specific tag settings, in case they were overridden
// `autoplay` has to be *last* so that `muted` and `playsinline` are present
// when ios/safari or other browsers attempt to autoplay.
var settingsattrs = ['loop', 'muted', 'playsinline', 'autoplay'];
for (var i = 0; i < settingsattrs.length; i++) {
var attr = settingsattrs[i];
var value = this.options_[attr];
if (typeof value !== 'undefined') {
if (value) {
setattribute(el, attr, attr);
} else {
removeattribute(el, attr);
}
el[attr] = value;
}
}
return el;
}
/**
* this will be triggered if the loadstart event has already fired, before videojs was
* ready. two known examples of when this can happen are:
* 1. if we're loading the playback object after it has started loading
* 2. the media is already playing the (often with autoplay on) then
*
* this function will fire another loadstart so that videojs can catchup.
*
* @fires tech#loadstart
*
* @return {undefined}
* returns nothing.
*/
;
_proto.handlelateinit_ = function handlelateinit_(el) {
if (el.networkstate === 0 || el.networkstate === 3) {
// the video element hasn't started loading the source yet
// or didn't find a source
return;
}
if (el.readystate === 0) {
// networkstate is set synchronously but loadstart is fired at the
// end of the current stack, usually before setinterval(fn, 0).
// so at this point we know loadstart may have already fired or is
// about to fire, and either way the player hasn't seen it yet.
// we don't want to fire loadstart prematurely here and cause a
// double loadstart so we'll wait and see if it happens between now
// and the next loop, and fire it if not.
// however, we also want to make sure it fires before loadedmetadata
// which could also happen between now and the next loop, so we'll
// watch for that also.
var loadstartfired = false;
var setloadstartfired = function setloadstartfired() {
loadstartfired = true;
};
this.on('loadstart', setloadstartfired);
var triggerloadstart = function triggerloadstart() {
// we did miss the original loadstart. make sure the player
// sees loadstart before loadedmetadata
if (!loadstartfired) {
this.trigger('loadstart');
}
};
this.on('loadedmetadata', triggerloadstart);
this.ready(function () {
this.off('loadstart', setloadstartfired);
this.off('loadedmetadata', triggerloadstart);
if (!loadstartfired) {
// we did miss the original native loadstart. fire it now.
this.trigger('loadstart');
}
});
return;
} // from here on we know that loadstart already fired and we missed it.
// the other readystate events aren't as much of a problem if we double
// them, so not going to go to as much trouble as loadstart to prevent
// that unless we find reason to.
var eventstotrigger = ['loadstart']; // loadedmetadata: newly equal to have_metadata (1) or greater
eventstotrigger.push('loadedmetadata'); // loadeddata: newly increased to have_current_data (2) or greater
if (el.readystate >= 2) {
eventstotrigger.push('loadeddata');
} // canplay: newly increased to have_future_data (3) or greater
if (el.readystate >= 3) {
eventstotrigger.push('canplay');
} // canplaythrough: newly equal to have_enough_data (4)
if (el.readystate >= 4) {
eventstotrigger.push('canplaythrough');
} // we still need to give the player time to add event listeners
this.ready(function () {
eventstotrigger.foreach(function (type) {
this.trigger(type);
}, this);
});
}
/**
* set whether we are scrubbing or not.
* this is used to decide whether we should use `fastseek` or not.
* `fastseek` is used to provide trick play on safari browsers.
*
* @param {boolean} isscrubbing
* - true for we are currently scrubbing
* - false for we are no longer scrubbing
*/
;
_proto.setscrubbing = function setscrubbing(isscrubbing) {
this.isscrubbing_ = isscrubbing;
}
/**
* get whether we are scrubbing or not.
*
* @return {boolean} isscrubbing
* - true for we are currently scrubbing
* - false for we are no longer scrubbing
*/
;
_proto.scrubbing = function scrubbing() {
return this.isscrubbing_;
}
/**
* set current time for the `html5` tech.
*
* @param {number} seconds
* set the current time of the media to this.
*/
;
_proto.setcurrenttime = function setcurrenttime(seconds) {
try {
if (this.isscrubbing_ && this.el_.fastseek && is_any_safari) {
this.el_.fastseek(seconds);
} else {
this.el_.currenttime = seconds;
}
} catch (e) {
log$1(e, 'video is not ready. (video.js)'); // this.warning(videojs.warnings.videonotready);
}
}
/**
* get the current duration of the html5 media element.
*
* @return {number}
* the duration of the media or 0 if there is no duration.
*/
;
_proto.duration = function duration() {
var _this5 = this;
// android chrome will report duration as infinity for vod hls until after
// playback has started, which triggers the live display erroneously.
// return nan if playback has not started and trigger a durationupdate once
// the duration can be reliably known.
if (this.el_.duration === infinity && is_android && is_chrome && this.el_.currenttime === 0) {
// wait for the first `timeupdate` with currenttime > 0 - there may be
// several with 0
var checkprogress = function checkprogress() {
if (_this5.el_.currenttime > 0) {
// trigger durationchange for genuinely live video
if (_this5.el_.duration === infinity) {
_this5.trigger('durationchange');
}
_this5.off('timeupdate', checkprogress);
}
};
this.on('timeupdate', checkprogress);
return nan;
}
return this.el_.duration || nan;
}
/**
* get the current width of the html5 media element.
*
* @return {number}
* the width of the html5 media element.
*/
;
_proto.width = function width() {
return this.el_.offsetwidth;
}
/**
* get the current height of the html5 media element.
*
* @return {number}
* the height of the html5 media element.
*/
;
_proto.height = function height() {
return this.el_.offsetheight;
}
/**
* proxy ios `webkitbeginfullscreen` and `webkitendfullscreen` into
* `fullscreenchange` event.
*
* @private
* @fires fullscreenchange
* @listens webkitendfullscreen
* @listens webkitbeginfullscreen
* @listens webkitbeginfullscreen
*/
;
_proto.proxywebkitfullscreen_ = function proxywebkitfullscreen_() {
var _this6 = this;
if (!('webkitdisplayingfullscreen' in this.el_)) {
return;
}
var endfn = function endfn() {
this.trigger('fullscreenchange', {
isfullscreen: false
}); // safari will sometimes set contols on the videoelement when existing fullscreen.
if (this.el_.controls && !this.options_.nativecontrolsfortouch && this.controls()) {
this.el_.controls = false;
}
};
var beginfn = function beginfn() {
if ('webkitpresentationmode' in this.el_ && this.el_.webkitpresentationmode !== 'picture-in-picture') {
this.one('webkitendfullscreen', endfn);
this.trigger('fullscreenchange', {
isfullscreen: true,
// set a flag in case another tech triggers fullscreenchange
nativeiosfullscreen: true
});
}
};
this.on('webkitbeginfullscreen', beginfn);
this.on('dispose', function () {
_this6.off('webkitbeginfullscreen', beginfn);
_this6.off('webkitendfullscreen', endfn);
});
}
/**
* check if fullscreen is supported on the current playback device.
*
* @return {boolean}
* - true if fullscreen is supported.
* - false if fullscreen is not supported.
*/
;
_proto.supportsfullscreen = function supportsfullscreen() {
if (typeof this.el_.webkitenterfullscreen === 'function') {
var useragent = global_window__webpack_imported_module_0___default.a.navigator && global_window__webpack_imported_module_0___default.a.navigator.useragent || ''; // seems to be broken in chromium/chrome && safari in leopard
if (/android/.test(useragent) || !/chrome|mac os x 10.5/.test(useragent)) {
return true;
}
}
return false;
}
/**
* request that the `html5` tech enter fullscreen.
*/
;
_proto.enterfullscreen = function enterfullscreen() {
var video = this.el_;
if (video.paused && video.networkstate <= video.have_metadata) {
// attempt to prime the video element for programmatic access
// this isn't necessary on the desktop but shouldn't hurt
silencepromise(this.el_.play()); // playing and pausing synchronously during the transition to fullscreen
// can get ios ~6.1 devices into a play/pause loop
this.settimeout(function () {
video.pause();
try {
video.webkitenterfullscreen();
} catch (e) {
this.trigger('fullscreenerror', e);
}
}, 0);
} else {
try {
video.webkitenterfullscreen();
} catch (e) {
this.trigger('fullscreenerror', e);
}
}
}
/**
* request that the `html5` tech exit fullscreen.
*/
;
_proto.exitfullscreen = function exitfullscreen() {
if (!this.el_.webkitdisplayingfullscreen) {
this.trigger('fullscreenerror', new error('the video is not fullscreen'));
return;
}
this.el_.webkitexitfullscreen();
}
/**
* create a floating video window always on top of other windows so that users may
* continue consuming media while they interact with other content sites, or
* applications on their device.
*
* @see [spec]{@link https://wicg.github.io/picture-in-picture}
*
* @return {promise}
* a promise with a picture-in-picture window.
*/
;
_proto.requestpictureinpicture = function requestpictureinpicture() {
return this.el_.requestpictureinpicture();
}
/**
* native requestvideoframecallback if supported by browser/tech, or fallback
* don't use rvcf on safari when drm is playing, as it doesn't fire
* needs to be checked later than the constructor
* this will be a false positive for clear sources loaded after a fairplay source
*
* @param {function} cb function to call
* @return {number} id of request
*/
;
_proto.requestvideoframecallback = function requestvideoframecallback(cb) {
if (this.featuresvideoframecallback && !this.el_.webkitkeys) {
return this.el_.requestvideoframecallback(cb);
}
return _tech.prototype.requestvideoframecallback.call(this, cb);
}
/**
* native or fallback requestvideoframecallback
*
* @param {number} id request id to cancel
*/
;
_proto.cancelvideoframecallback = function cancelvideoframecallback(id) {
if (this.featuresvideoframecallback && !this.el_.webkitkeys) {
this.el_.cancelvideoframecallback(id);
} else {
_tech.prototype.cancelvideoframecallback.call(this, id);
}
}
/**
* a getter/setter for the `html5` tech's source object.
* > note: please use {@link html5#setsource}
*
* @param {tech~sourceobject} [src]
* the source object you want to set on the `html5` techs element.
*
* @return {tech~sourceobject|undefined}
* - the current source object when a source is not passed in.
* - undefined when setting
*
* @deprecated since version 5.
*/
;
_proto.src = function src(_src) {
if (_src === undefined) {
return this.el_.src;
} // setting src through `src` instead of `setsrc` will be deprecated
this.setsrc(_src);
}
/**
* reset the tech by removing all sources and then calling
* {@link html5.resetmediaelement}.
*/
;
_proto.reset = function reset() {
html5.resetmediaelement(this.el_);
}
/**
* get the current source on the `html5` tech. falls back to returning the source from
* the html5 media element.
*
* @return {tech~sourceobject}
* the current source object from the html5 tech. with a fallback to the
* elements source.
*/
;
_proto.currentsrc = function currentsrc() {
if (this.currentsource_) {
return this.currentsource_.src;
}
return this.el_.currentsrc;
}
/**
* set controls attribute for the html5 media element.
*
* @param {string} val
* value to set the controls attribute to
*/
;
_proto.setcontrols = function setcontrols(val) {
this.el_.controls = !!val;
}
/**
* create and returns a remote {@link texttrack} object.
*
* @param {string} kind
* `texttrack` kind (subtitles, captions, descriptions, chapters, or metadata)
*
* @param {string} [label]
* label to identify the text track
*
* @param {string} [language]
* two letter language abbreviation
*
* @return {texttrack}
* the texttrack that gets created.
*/
;
_proto.addtexttrack = function addtexttrack(kind, label, language) {
if (!this.featuresnativetexttracks) {
return _tech.prototype.addtexttrack.call(this, kind, label, language);
}
return this.el_.addtexttrack(kind, label, language);
}
/**
* creates either native texttrack or an emulated texttrack depending
* on the value of `featuresnativetexttracks`
*
* @param {object} options
* the object should contain the options to initialize the texttrack with.
*
* @param {string} [options.kind]
* `texttrack` kind (subtitles, captions, descriptions, chapters, or metadata).
*
* @param {string} [options.label]
* label to identify the text track
*
* @param {string} [options.language]
* two letter language abbreviation.
*
* @param {boolean} [options.default]
* default this track to on.
*
* @param {string} [options.id]
* the internal id to assign this track.
*
* @param {string} [options.src]
* a source url for the track.
*
* @return {htmltrackelement}
* the track element that gets created.
*/
;
_proto.createremotetexttrack = function createremotetexttrack(options) {
if (!this.featuresnativetexttracks) {
return _tech.prototype.createremotetexttrack.call(this, options);
}
var htmltrackelement = global_document__webpack_imported_module_1___default.a.createelement('track');
if (options.kind) {
htmltrackelement.kind = options.kind;
}
if (options.label) {
htmltrackelement.label = options.label;
}
if (options.language || options.srclang) {
htmltrackelement.srclang = options.language || options.srclang;
}
if (options["default"]) {
htmltrackelement["default"] = options["default"];
}
if (options.id) {
htmltrackelement.id = options.id;
}
if (options.src) {
htmltrackelement.src = options.src;
}
return htmltrackelement;
}
/**
* creates a remote text track object and returns an html track element.
*
* @param {object} options the object should contain values for
* kind, language, label, and src (location of the webvtt file)
* @param {boolean} [manualcleanup=true] if set to false, the texttrack will be
* automatically removed from the video element whenever the source changes
* @return {htmltrackelement} an html track element.
* this can be an emulated {@link htmltrackelement} or a native one.
* @deprecated the default value of the "manualcleanup" parameter will default
* to "false" in upcoming versions of video.js
*/
;
_proto.addremotetexttrack = function addremotetexttrack(options, manualcleanup) {
var htmltrackelement = _tech.prototype.addremotetexttrack.call(this, options, manualcleanup);
if (this.featuresnativetexttracks) {
this.el().appendchild(htmltrackelement);
}
return htmltrackelement;
}
/**
* remove remote `texttrack` from `texttracklist` object
*
* @param {texttrack} track
* `texttrack` object to remove
*/
;
_proto.removeremotetexttrack = function removeremotetexttrack(track) {
_tech.prototype.removeremotetexttrack.call(this, track);
if (this.featuresnativetexttracks) {
var tracks = this.$$('track');
var i = tracks.length;
while (i--) {
if (track === tracks[i] || track === tracks[i].track) {
this.el().removechild(tracks[i]);
}
}
}
}
/**
* gets available media playback quality metrics as specified by the w3c's media
* playback quality api.
*
* @see [spec]{@link https://wicg.github.io/media-playback-quality}
*
* @return {object}
* an object with supported media playback quality metrics
*/
;
_proto.getvideoplaybackquality = function getvideoplaybackquality() {
if (typeof this.el().getvideoplaybackquality === 'function') {
return this.el().getvideoplaybackquality();
}
var videoplaybackquality = {};
if (typeof this.el().webkitdroppedframecount !== 'undefined' && typeof this.el().webkitdecodedframecount !== 'undefined') {
videoplaybackquality.droppedvideoframes = this.el().webkitdroppedframecount;
videoplaybackquality.totalvideoframes = this.el().webkitdecodedframecount;
}
if (global_window__webpack_imported_module_0___default.a.performance && typeof global_window__webpack_imported_module_0___default.a.performance.now === 'function') {
videoplaybackquality.creationtime = global_window__webpack_imported_module_0___default.a.performance.now();
} else if (global_window__webpack_imported_module_0___default.a.performance && global_window__webpack_imported_module_0___default.a.performance.timing && typeof global_window__webpack_imported_module_0___default.a.performance.timing.navigationstart === 'number') {
videoplaybackquality.creationtime = global_window__webpack_imported_module_0___default.a.date.now() - global_window__webpack_imported_module_0___default.a.performance.timing.navigationstart;
}
return videoplaybackquality;
};
return html5;
}(tech);
/* html5 support testing ---------------------------------------------------- */
/**
* element for testing browser html5 media capabilities
*
* @type {element}
* @constant
* @private
*/
definelazyproperty(html5, 'test_vid', function () {
if (!isreal()) {
return;
}
var video = global_document__webpack_imported_module_1___default.a.createelement('video');
var track = global_document__webpack_imported_module_1___default.a.createelement('track');
track.kind = 'captions';
track.srclang = 'en';
track.label = 'english';
video.appendchild(track);
return video;
});
/**
* check if html5 media is supported by this browser/device.
*
* @return {boolean}
* - true if html5 media is supported.
* - false if html5 media is not supported.
*/
html5.issupported = function () {
// ie with no media player is a liar! (#984)
try {
html5.test_vid.volume = 0.5;
} catch (e) {
return false;
}
return !!(html5.test_vid && html5.test_vid.canplaytype);
};
/**
* check if the tech can support the given type
*
* @param {string} type
* the mimetype to check
* @return {string} 'probably', 'maybe', or '' (empty string)
*/
html5.canplaytype = function (type) {
return html5.test_vid.canplaytype(type);
};
/**
* check if the tech can support the given source
*
* @param {object} srcobj
* the source object
* @param {object} options
* the options passed to the tech
* @return {string} 'probably', 'maybe', or '' (empty string)
*/
html5.canplaysource = function (srcobj, options) {
return html5.canplaytype(srcobj.type);
};
/**
* check if the volume can be changed in this browser/device.
* volume cannot be changed in a lot of mobile devices.
* specifically, it can't be changed from 1 on ios.
*
* @return {boolean}
* - true if volume can be controlled
* - false otherwise
*/
html5.cancontrolvolume = function () {
// ie will error if windows media player not installed #3315
try {
var volume = html5.test_vid.volume;
html5.test_vid.volume = volume / 2 + 0.1;
var cancontrol = volume !== html5.test_vid.volume; // with the introduction of ios 15, there are cases where the volume is read as
// changed but reverts back to its original state at the start of the next tick.
// to determine whether volume can be controlled on ios,
// a timeout is set and the volume is checked asynchronously.
// since `features` doesn't currently work asynchronously, the value is manually set.
if (cancontrol && is_ios) {
global_window__webpack_imported_module_0___default.a.settimeout(function () {
if (html5 && html5.prototype) {
html5.prototype.featuresvolumecontrol = volume !== html5.test_vid.volume;
}
}); // default ios to false, which will be updated in the timeout above.
return false;
}
return cancontrol;
} catch (e) {
return false;
}
};
/**
* check if the volume can be muted in this browser/device.
* some devices, e.g. ios, don't allow changing volume
* but permits muting/unmuting.
*
* @return {bolean}
* - true if volume can be muted
* - false otherwise
*/
html5.canmutevolume = function () {
try {
var muted = html5.test_vid.muted; // in some versions of ios muted property doesn't always
// work, so we want to set both property and attribute
html5.test_vid.muted = !muted;
if (html5.test_vid.muted) {
setattribute(html5.test_vid, 'muted', 'muted');
} else {
removeattribute(html5.test_vid, 'muted', 'muted');
}
return muted !== html5.test_vid.muted;
} catch (e) {
return false;
}
};
/**
* check if the playback rate can be changed in this browser/device.
*
* @return {boolean}
* - true if playback rate can be controlled
* - false otherwise
*/
html5.cancontrolplaybackrate = function () {
// playback rate api is implemented in android chrome, but doesn't do anything
// https://github.com/videojs/video.js/issues/3180
if (is_android && is_chrome && chrome_version < 58) {
return false;
} // ie will error if windows media player not installed #3315
try {
var playbackrate = html5.test_vid.playbackrate;
html5.test_vid.playbackrate = playbackrate / 2 + 0.1;
return playbackrate !== html5.test_vid.playbackrate;
} catch (e) {
return false;
}
};
/**
* check if we can override a video/audio elements attributes, with
* object.defineproperty.
*
* @return {boolean}
* - true if builtin attributes can be overridden
* - false otherwise
*/
html5.canoverrideattributes = function () {
// if we cannot overwrite the src/innerhtml property, there is no support
// ios 7 safari for instance cannot do this.
try {
var noop = function noop() {};
object.defineproperty(global_document__webpack_imported_module_1___default.a.createelement('video'), 'src', {
get: noop,
set: noop
});
object.defineproperty(global_document__webpack_imported_module_1___default.a.createelement('audio'), 'src', {
get: noop,
set: noop
});
object.defineproperty(global_document__webpack_imported_module_1___default.a.createelement('video'), 'innerhtml', {
get: noop,
set: noop
});
object.defineproperty(global_document__webpack_imported_module_1___default.a.createelement('audio'), 'innerhtml', {
get: noop,
set: noop
});
} catch (e) {
return false;
}
return true;
};
/**
* check to see if native `texttrack`s are supported by this browser/device.
*
* @return {boolean}
* - true if native `texttrack`s are supported.
* - false otherwise
*/
html5.supportsnativetexttracks = function () {
return is_any_safari || is_ios && is_chrome;
};
/**
* check to see if native `videotrack`s are supported by this browser/device
*
* @return {boolean}
* - true if native `videotrack`s are supported.
* - false otherwise
*/
html5.supportsnativevideotracks = function () {
return !!(html5.test_vid && html5.test_vid.videotracks);
};
/**
* check to see if native `audiotrack`s are supported by this browser/device
*
* @return {boolean}
* - true if native `audiotrack`s are supported.
* - false otherwise
*/
html5.supportsnativeaudiotracks = function () {
return !!(html5.test_vid && html5.test_vid.audiotracks);
};
/**
* an array of events available on the html5 tech.
*
* @private
* @type {array}
*/
html5.events = ['loadstart', 'suspend', 'abort', 'error', 'emptied', 'stalled', 'loadedmetadata', 'loadeddata', 'canplay', 'canplaythrough', 'playing', 'waiting', 'seeking', 'seeked', 'ended', 'durationchange', 'timeupdate', 'progress', 'play', 'pause', 'ratechange', 'resize', 'volumechange'];
/**
* boolean indicating whether the `tech` supports volume control.
*
* @type {boolean}
* @default {@link html5.cancontrolvolume}
*/
/**
* boolean indicating whether the `tech` supports muting volume.
*
* @type {bolean}
* @default {@link html5.canmutevolume}
*/
/**
* boolean indicating whether the `tech` supports changing the speed at which the media
* plays. examples:
* - set player to play 2x (twice) as fast
* - set player to play 0.5x (half) as fast
*
* @type {boolean}
* @default {@link html5.cancontrolplaybackrate}
*/
/**
* boolean indicating whether the `tech` supports the `sourceset` event.
*
* @type {boolean}
* @default
*/
/**
* boolean indicating whether the `html5` tech currently supports native `texttrack`s.
*
* @type {boolean}
* @default {@link html5.supportsnativetexttracks}
*/
/**
* boolean indicating whether the `html5` tech currently supports native `videotrack`s.
*
* @type {boolean}
* @default {@link html5.supportsnativevideotracks}
*/
/**
* boolean indicating whether the `html5` tech currently supports native `audiotrack`s.
*
* @type {boolean}
* @default {@link html5.supportsnativeaudiotracks}
*/
[['featuresmutecontrol', 'canmutevolume'], ['featuresplaybackrate', 'cancontrolplaybackrate'], ['featuressourceset', 'canoverrideattributes'], ['featuresnativetexttracks', 'supportsnativetexttracks'], ['featuresnativevideotracks', 'supportsnativevideotracks'], ['featuresnativeaudiotracks', 'supportsnativeaudiotracks']].foreach(function (_ref) {
var key = _ref[0],
fn = _ref[1];
definelazyproperty(html5.prototype, key, function () {
return html5[fn]();
}, true);
});
html5.prototype.featuresvolumecontrol = html5.cancontrolvolume();
/**
* boolean indicating whether the `html5` tech currently supports the media element
* moving in the dom. ios breaks if you move the media element, so this is set this to
* false there. everywhere else this should be true.
*
* @type {boolean}
* @default
*/
html5.prototype.movingmediaelementindom = !is_ios; // todo: previous comment: no longer appears to be used. can probably be removed.
// is this true?
/**
* boolean indicating whether the `html5` tech currently supports automatic media resize
* when going into fullscreen.
*
* @type {boolean}
* @default
*/
html5.prototype.featuresfullscreenresize = true;
/**
* boolean indicating whether the `html5` tech currently supports the progress event.
* if this is false, manual `progress` events will be triggered instead.
*
* @type {boolean}
* @default
*/
html5.prototype.featuresprogressevents = true;
/**
* boolean indicating whether the `html5` tech currently supports the timeupdate event.
* if this is false, manual `timeupdate` events will be triggered instead.
*
* @default
*/
html5.prototype.featurestimeupdateevents = true;
/**
* whether the html5 el supports `requestvideoframecallback`
*
* @type {boolean}
*/
html5.prototype.featuresvideoframecallback = !!(html5.test_vid && html5.test_vid.requestvideoframecallback); // html5 feature detection and device fixes --------------------------------- //
var canplaytype;
html5.patchcanplaytype = function () {
// android 4.0 and above can play hls to some extent but it reports being unable to do so
// firefox and chrome report correctly
if (android_version >= 4.0 && !is_firefox && !is_chrome) {
canplaytype = html5.test_vid && html5.test_vid.constructor.prototype.canplaytype;
html5.test_vid.constructor.prototype.canplaytype = function (type) {
var mpegurlre = /^application\/(?:x-|vnd\.apple\.)mpegurl/i;
if (type && mpegurlre.test(type)) {
return 'maybe';
}
return canplaytype.call(this, type);
};
}
};
html5.unpatchcanplaytype = function () {
var r = html5.test_vid.constructor.prototype.canplaytype;
if (canplaytype) {
html5.test_vid.constructor.prototype.canplaytype = canplaytype;
}
return r;
}; // by default, patch the media element
html5.patchcanplaytype();
html5.disposemediaelement = function (el) {
if (!el) {
return;
}
if (el.parentnode) {
el.parentnode.removechild(el);
} // remove any child track or source nodes to prevent their loading
while (el.haschildnodes()) {
el.removechild(el.firstchild);
} // remove any src reference. not setting `src=''` because that causes a warning
// in firefox
el.removeattribute('src'); // force the media element to update its loading state by calling load()
// however ie on windows 7n has a bug that throws an error so need a try/catch (#793)
if (typeof el.load === 'function') {
// wrapping in an iife so it's not deoptimized (#1060#discussion_r10324473)
(function () {
try {
el.load();
} catch (e) {// not supported
}
})();
}
};
html5.resetmediaelement = function (el) {
if (!el) {
return;
}
var sources = el.queryselectorall('source');
var i = sources.length;
while (i--) {
el.removechild(sources[i]);
} // remove any src reference.
// not setting `src=''` because that throws an error
el.removeattribute('src');
if (typeof el.load === 'function') {
// wrapping in an iife so it's not deoptimized (#1060#discussion_r10324473)
(function () {
try {
el.load();
} catch (e) {// satisfy linter
}
})();
}
};
/* native html5 element property wrapping ----------------------------------- */
// wrap native boolean attributes with getters that check both property and attribute
// the list is as followed:
// muted, defaultmuted, autoplay, controls, loop, playsinline
[
/**
* get the value of `muted` from the media element. `muted` indicates
* that the volume for the media should be set to silent. this does not actually change
* the `volume` attribute.
*
* @method html5#muted
* @return {boolean}
* - true if the value of `volume` should be ignored and the audio set to silent.
* - false if the value of `volume` should be used.
*
* @see [spec]{@link https://www.w3.org/tr/html5/embedded-content-0.html#dom-media-muted}
*/
'muted',
/**
* get the value of `defaultmuted` from the media element. `defaultmuted` indicates
* whether the media should start muted or not. only changes the default state of the
* media. `muted` and `defaultmuted` can have different values. {@link html5#muted} indicates the
* current state.
*
* @method html5#defaultmuted
* @return {boolean}
* - the value of `defaultmuted` from the media element.
* - true indicates that the media should start muted.
* - false indicates that the media should not start muted
*
* @see [spec]{@link https://www.w3.org/tr/html5/embedded-content-0.html#dom-media-defaultmuted}
*/
'defaultmuted',
/**
* get the value of `autoplay` from the media element. `autoplay` indicates
* that the media should start to play as soon as the page is ready.
*
* @method html5#autoplay
* @return {boolean}
* - the value of `autoplay` from the media element.
* - true indicates that the media should start as soon as the page loads.
* - false indicates that the media should not start as soon as the page loads.
*
* @see [spec]{@link https://www.w3.org/tr/html5/embedded-content-0.html#attr-media-autoplay}
*/
'autoplay',
/**
* get the value of `controls` from the media element. `controls` indicates
* whether the native media controls should be shown or hidden.
*
* @method html5#controls
* @return {boolean}
* - the value of `controls` from the media element.
* - true indicates that native controls should be showing.
* - false indicates that native controls should be hidden.
*
* @see [spec]{@link https://www.w3.org/tr/html5/embedded-content-0.html#attr-media-controls}
*/
'controls',
/**
* get the value of `loop` from the media element. `loop` indicates
* that the media should return to the start of the media and continue playing once
* it reaches the end.
*
* @method html5#loop
* @return {boolean}
* - the value of `loop` from the media element.
* - true indicates that playback should seek back to start once
* the end of a media is reached.
* - false indicates that playback should not loop back to the start when the
* end of the media is reached.
*
* @see [spec]{@link https://www.w3.org/tr/html5/embedded-content-0.html#attr-media-loop}
*/
'loop',
/**
* get the value of `playsinline` from the media element. `playsinline` indicates
* to the browser that non-fullscreen playback is preferred when fullscreen
* playback is the native default, such as in ios safari.
*
* @method html5#playsinline
* @return {boolean}
* - the value of `playsinline` from the media element.
* - true indicates that the media should play inline.
* - false indicates that the media should not play inline.
*
* @see [spec]{@link https://html.spec.whatwg.org/#attr-video-playsinline}
*/
'playsinline'].foreach(function (prop) {
html5.prototype[prop] = function () {
return this.el_[prop] || this.el_.hasattribute(prop);
};
}); // wrap native boolean attributes with setters that set both property and attribute
// the list is as followed:
// setmuted, setdefaultmuted, setautoplay, setloop, setplaysinline
// setcontrols is special-cased above
[
/**
* set the value of `muted` on the media element. `muted` indicates that the current
* audio level should be silent.
*
* @method html5#setmuted
* @param {boolean} muted
* - true if the audio should be set to silent
* - false otherwise
*
* @see [spec]{@link https://www.w3.org/tr/html5/embedded-content-0.html#dom-media-muted}
*/
'muted',
/**
* set the value of `defaultmuted` on the media element. `defaultmuted` indicates that the current
* audio level should be silent, but will only effect the muted level on initial playback..
*
* @method html5.prototype.setdefaultmuted
* @param {boolean} defaultmuted
* - true if the audio should be set to silent
* - false otherwise
*
* @see [spec]{@link https://www.w3.org/tr/html5/embedded-content-0.html#dom-media-defaultmuted}
*/
'defaultmuted',
/**
* set the value of `autoplay` on the media element. `autoplay` indicates
* that the media should start to play as soon as the page is ready.
*
* @method html5#setautoplay
* @param {boolean} autoplay
* - true indicates that the media should start as soon as the page loads.
* - false indicates that the media should not start as soon as the page loads.
*
* @see [spec]{@link https://www.w3.org/tr/html5/embedded-content-0.html#attr-media-autoplay}
*/
'autoplay',
/**
* set the value of `loop` on the media element. `loop` indicates
* that the media should return to the start of the media and continue playing once
* it reaches the end.
*
* @method html5#setloop
* @param {boolean} loop
* - true indicates that playback should seek back to start once
* the end of a media is reached.
* - false indicates that playback should not loop back to the start when the
* end of the media is reached.
*
* @see [spec]{@link https://www.w3.org/tr/html5/embedded-content-0.html#attr-media-loop}
*/
'loop',
/**
* set the value of `playsinline` from the media element. `playsinline` indicates
* to the browser that non-fullscreen playback is preferred when fullscreen
* playback is the native default, such as in ios safari.
*
* @method html5#setplaysinline
* @param {boolean} playsinline
* - true indicates that the media should play inline.
* - false indicates that the media should not play inline.
*
* @see [spec]{@link https://html.spec.whatwg.org/#attr-video-playsinline}
*/
'playsinline'].foreach(function (prop) {
html5.prototype['set' + totitlecase$1(prop)] = function (v) {
this.el_[prop] = v;
if (v) {
this.el_.setattribute(prop, prop);
} else {
this.el_.removeattribute(prop);
}
};
}); // wrap native properties with a getter
// the list is as followed
// paused, currenttime, buffered, volume, poster, preload, error, seeking
// seekable, ended, playbackrate, defaultplaybackrate, disablepictureinpicture
// played, networkstate, readystate, videowidth, videoheight, crossorigin
[
/**
* get the value of `paused` from the media element. `paused` indicates whether the media element
* is currently paused or not.
*
* @method html5#paused
* @return {boolean}
* the value of `paused` from the media element.
*
* @see [spec]{@link https://www.w3.org/tr/html5/embedded-content-0.html#dom-media-paused}
*/
'paused',
/**
* get the value of `currenttime` from the media element. `currenttime` indicates
* the current second that the media is at in playback.
*
* @method html5#currenttime
* @return {number}
* the value of `currenttime` from the media element.
*
* @see [spec]{@link https://www.w3.org/tr/html5/embedded-content-0.html#dom-media-currenttime}
*/
'currenttime',
/**
* get the value of `buffered` from the media element. `buffered` is a `timerange`
* object that represents the parts of the media that are already downloaded and
* available for playback.
*
* @method html5#buffered
* @return {timerange}
* the value of `buffered` from the media element.
*
* @see [spec]{@link https://www.w3.org/tr/html5/embedded-content-0.html#dom-media-buffered}
*/
'buffered',
/**
* get the value of `volume` from the media element. `volume` indicates
* the current playback volume of audio for a media. `volume` will be a value from 0
* (silent) to 1 (loudest and default).
*
* @method html5#volume
* @return {number}
* the value of `volume` from the media element. value will be between 0-1.
*
* @see [spec]{@link https://www.w3.org/tr/html5/embedded-content-0.html#dom-a-volume}
*/
'volume',
/**
* get the value of `poster` from the media element. `poster` indicates
* that the url of an image file that can/will be shown when no media data is available.
*
* @method html5#poster
* @return {string}
* the value of `poster` from the media element. value will be a url to an
* image.
*
* @see [spec]{@link https://www.w3.org/tr/html5/embedded-content-0.html#attr-video-poster}
*/
'poster',
/**
* get the value of `preload` from the media element. `preload` indicates
* what should download before the media is interacted with. it can have the following
* values:
* - none: nothing should be downloaded
* - metadata: poster and the first few frames of the media may be downloaded to get
* media dimensions and other metadata
* - auto: allow the media and metadata for the media to be downloaded before
* interaction
*
* @method html5#preload
* @return {string}
* the value of `preload` from the media element. will be 'none', 'metadata',
* or 'auto'.
*
* @see [spec]{@link https://www.w3.org/tr/html5/embedded-content-0.html#attr-media-preload}
*/
'preload',
/**
* get the value of the `error` from the media element. `error` indicates any
* mediaerror that may have occurred during playback. if error returns null there is no
* current error.
*
* @method html5#error
* @return {mediaerror|null}
* the value of `error` from the media element. will be `mediaerror` if there
* is a current error and null otherwise.
*
* @see [spec]{@link https://www.w3.org/tr/html5/embedded-content-0.html#dom-media-error}
*/
'error',
/**
* get the value of `seeking` from the media element. `seeking` indicates whether the
* media is currently seeking to a new position or not.
*
* @method html5#seeking
* @return {boolean}
* - the value of `seeking` from the media element.
* - true indicates that the media is currently seeking to a new position.
* - false indicates that the media is not seeking to a new position at this time.
*
* @see [spec]{@link https://www.w3.org/tr/html5/embedded-content-0.html#dom-media-seeking}
*/
'seeking',
/**
* get the value of `seekable` from the media element. `seekable` returns a
* `timerange` object indicating ranges of time that can currently be `seeked` to.
*
* @method html5#seekable
* @return {timerange}
* the value of `seekable` from the media element. a `timerange` object
* indicating the current ranges of time that can be seeked to.
*
* @see [spec]{@link https://www.w3.org/tr/html5/embedded-content-0.html#dom-media-seekable}
*/
'seekable',
/**
* get the value of `ended` from the media element. `ended` indicates whether
* the media has reached the end or not.
*
* @method html5#ended
* @return {boolean}
* - the value of `ended` from the media element.
* - true indicates that the media has ended.
* - false indicates that the media has not ended.
*
* @see [spec]{@link https://www.w3.org/tr/html5/embedded-content-0.html#dom-media-ended}
*/
'ended',
/**
* get the value of `playbackrate` from the media element. `playbackrate` indicates
* the rate at which the media is currently playing back. examples:
* - if playbackrate is set to 2, media will play twice as fast.
* - if playbackrate is set to 0.5, media will play half as fast.
*
* @method html5#playbackrate
* @return {number}
* the value of `playbackrate` from the media element. a number indicating
* the current playback speed of the media, where 1 is normal speed.
*
* @see [spec]{@link https://www.w3.org/tr/html5/embedded-content-0.html#dom-media-playbackrate}
*/
'playbackrate',
/**
* get the value of `defaultplaybackrate` from the media element. `defaultplaybackrate` indicates
* the rate at which the media is currently playing back. this value will not indicate the current
* `playbackrate` after playback has started, use {@link html5#playbackrate} for that.
*
* examples:
* - if defaultplaybackrate is set to 2, media will play twice as fast.
* - if defaultplaybackrate is set to 0.5, media will play half as fast.
*
* @method html5.prototype.defaultplaybackrate
* @return {number}
* the value of `defaultplaybackrate` from the media element. a number indicating
* the current playback speed of the media, where 1 is normal speed.
*
* @see [spec]{@link https://www.w3.org/tr/html5/embedded-content-0.html#dom-media-playbackrate}
*/
'defaultplaybackrate',
/**
* get the value of 'disablepictureinpicture' from the video element.
*
* @method html5#disablepictureinpicture
* @return {boolean} value
* - the value of `disablepictureinpicture` from the video element.
* - true indicates that the video can't be played in picture-in-picture mode
* - false indicates that the video can be played in picture-in-picture mode
*
* @see [spec]{@link https://w3c.github.io/picture-in-picture/#disable-pip}
*/
'disablepictureinpicture',
/**
* get the value of `played` from the media element. `played` returns a `timerange`
* object representing points in the media timeline that have been played.
*
* @method html5#played
* @return {timerange}
* the value of `played` from the media element. a `timerange` object indicating
* the ranges of time that have been played.
*
* @see [spec]{@link https://www.w3.org/tr/html5/embedded-content-0.html#dom-media-played}
*/
'played',
/**
* get the value of `networkstate` from the media element. `networkstate` indicates
* the current network state. it returns an enumeration from the following list:
* - 0: network_empty
* - 1: network_idle
* - 2: network_loading
* - 3: network_no_source
*
* @method html5#networkstate
* @return {number}
* the value of `networkstate` from the media element. this will be a number
* from the list in the description.
*
* @see [spec] {@link https://www.w3.org/tr/html5/embedded-content-0.html#dom-media-networkstate}
*/
'networkstate',
/**
* get the value of `readystate` from the media element. `readystate` indicates
* the current state of the media element. it returns an enumeration from the
* following list:
* - 0: have_nothing
* - 1: have_metadata
* - 2: have_current_data
* - 3: have_future_data
* - 4: have_enough_data
*
* @method html5#readystate
* @return {number}
* the value of `readystate` from the media element. this will be a number
* from the list in the description.
*
* @see [spec] {@link https://www.w3.org/tr/html5/embedded-content-0.html#ready-states}
*/
'readystate',
/**
* get the value of `videowidth` from the video element. `videowidth` indicates
* the current width of the video in css pixels.
*
* @method html5#videowidth
* @return {number}
* the value of `videowidth` from the video element. this will be a number
* in css pixels.
*
* @see [spec] {@link https://www.w3.org/tr/html5/embedded-content-0.html#dom-video-videowidth}
*/
'videowidth',
/**
* get the value of `videoheight` from the video element. `videoheight` indicates
* the current height of the video in css pixels.
*
* @method html5#videoheight
* @return {number}
* the value of `videoheight` from the video element. this will be a number
* in css pixels.
*
* @see [spec] {@link https://www.w3.org/tr/html5/embedded-content-0.html#dom-video-videowidth}
*/
'videoheight',
/**
* get the value of `crossorigin` from the media element. `crossorigin` indicates
* to the browser that should sent the cookies along with the requests for the
* different assets/playlists
*
* @method html5#crossorigin
* @return {string}
* - anonymous indicates that the media should not sent cookies.
* - use-credentials indicates that the media should sent cookies along the requests.
*
* @see [spec]{@link https://html.spec.whatwg.org/#attr-media-crossorigin}
*/
'crossorigin'].foreach(function (prop) {
html5.prototype[prop] = function () {
return this.el_[prop];
};
}); // wrap native properties with a setter in this format:
// set + totitlecase(name)
// the list is as follows:
// setvolume, setsrc, setposter, setpreload, setplaybackrate, setdefaultplaybackrate,
// setdisablepictureinpicture, setcrossorigin
[
/**
* set the value of `volume` on the media element. `volume` indicates the current
* audio level as a percentage in decimal form. this means that 1 is 100%, 0.5 is 50%, and
* so on.
*
* @method html5#setvolume
* @param {number} percentasdecimal
* the volume percent as a decimal. valid range is from 0-1.
*
* @see [spec]{@link https://www.w3.org/tr/html5/embedded-content-0.html#dom-a-volume}
*/
'volume',
/**
* set the value of `src` on the media element. `src` indicates the current
* {@link tech~sourceobject} for the media.
*
* @method html5#setsrc
* @param {tech~sourceobject} src
* the source object to set as the current source.
*
* @see [spec]{@link https://www.w3.org/tr/html5/embedded-content-0.html#dom-media-src}
*/
'src',
/**
* set the value of `poster` on the media element. `poster` is the url to
* an image file that can/will be shown when no media data is available.
*
* @method html5#setposter
* @param {string} poster
* the url to an image that should be used as the `poster` for the media
* element.
*
* @see [spec]{@link https://www.w3.org/tr/html5/embedded-content-0.html#attr-media-poster}
*/
'poster',
/**
* set the value of `preload` on the media element. `preload` indicates
* what should download before the media is interacted with. it can have the following
* values:
* - none: nothing should be downloaded
* - metadata: poster and the first few frames of the media may be downloaded to get
* media dimensions and other metadata
* - auto: allow the media and metadata for the media to be downloaded before
* interaction
*
* @method html5#setpreload
* @param {string} preload
* the value of `preload` to set on the media element. must be 'none', 'metadata',
* or 'auto'.
*
* @see [spec]{@link https://www.w3.org/tr/html5/embedded-content-0.html#attr-media-preload}
*/
'preload',
/**
* set the value of `playbackrate` on the media element. `playbackrate` indicates
* the rate at which the media should play back. examples:
* - if playbackrate is set to 2, media will play twice as fast.
* - if playbackrate is set to 0.5, media will play half as fast.
*
* @method html5#setplaybackrate
* @return {number}
* the value of `playbackrate` from the media element. a number indicating
* the current playback speed of the media, where 1 is normal speed.
*
* @see [spec]{@link https://www.w3.org/tr/html5/embedded-content-0.html#dom-media-playbackrate}
*/
'playbackrate',
/**
* set the value of `defaultplaybackrate` on the media element. `defaultplaybackrate` indicates
* the rate at which the media should play back upon initial startup. changing this value
* after a video has started will do nothing. instead you should used {@link html5#setplaybackrate}.
*
* example values:
* - if playbackrate is set to 2, media will play twice as fast.
* - if playbackrate is set to 0.5, media will play half as fast.
*
* @method html5.prototype.setdefaultplaybackrate
* @return {number}
* the value of `defaultplaybackrate` from the media element. a number indicating
* the current playback speed of the media, where 1 is normal speed.
*
* @see [spec]{@link https://www.w3.org/tr/html5/embedded-content-0.html#dom-media-defaultplaybackrate}
*/
'defaultplaybackrate',
/**
* prevents the browser from suggesting a picture-in-picture context menu
* or to request picture-in-picture automatically in some cases.
*
* @method html5#setdisablepictureinpicture
* @param {boolean} value
* the true value will disable picture-in-picture mode.
*
* @see [spec]{@link https://w3c.github.io/picture-in-picture/#disable-pip}
*/
'disablepictureinpicture',
/**
* set the value of `crossorigin` from the media element. `crossorigin` indicates
* to the browser that should sent the cookies along with the requests for the
* different assets/playlists
*
* @method html5#setcrossorigin
* @param {string} crossorigin
* - anonymous indicates that the media should not sent cookies.
* - use-credentials indicates that the media should sent cookies along the requests.
*
* @see [spec]{@link https://html.spec.whatwg.org/#attr-media-crossorigin}
*/
'crossorigin'].foreach(function (prop) {
html5.prototype['set' + totitlecase$1(prop)] = function (v) {
this.el_[prop] = v;
};
}); // wrap native functions with a function
// the list is as follows:
// pause, load, play
[
/**
* a wrapper around the media elements `pause` function. this will call the `html5`
* media elements `pause` function.
*
* @method html5#pause
* @see [spec]{@link https://www.w3.org/tr/html5/embedded-content-0.html#dom-media-pause}
*/
'pause',
/**
* a wrapper around the media elements `load` function. this will call the `html5`s
* media element `load` function.
*
* @method html5#load
* @see [spec]{@link https://www.w3.org/tr/html5/embedded-content-0.html#dom-media-load}
*/
'load',
/**
* a wrapper around the media elements `play` function. this will call the `html5`s
* media element `play` function.
*
* @method html5#play
* @see [spec]{@link https://www.w3.org/tr/html5/embedded-content-0.html#dom-media-play}
*/
'play'].foreach(function (prop) {
html5.prototype[prop] = function () {
return this.el_[prop]();
};
});
tech.withsourcehandlers(html5);
/**
* native source handler for html5, simply passes the source to the media element.
*
* @property {tech~sourceobject} source
* the source object
*
* @property {html5} tech
* the instance of the html5 tech.
*/
html5.nativesourcehandler = {};
/**
* check if the media element can play the given mime type.
*
* @param {string} type
* the mimetype to check
*
* @return {string}
* 'probably', 'maybe', or '' (empty string)
*/
html5.nativesourcehandler.canplaytype = function (type) {
// ie without mediaplayer throws an error (#519)
try {
return html5.test_vid.canplaytype(type);
} catch (e) {
return '';
}
};
/**
* check if the media element can handle a source natively.
*
* @param {tech~sourceobject} source
* the source object
*
* @param {object} [options]
* options to be passed to the tech.
*
* @return {string}
* 'probably', 'maybe', or '' (empty string).
*/
html5.nativesourcehandler.canhandlesource = function (source, options) {
// if a type was provided we should rely on that
if (source.type) {
return html5.nativesourcehandler.canplaytype(source.type); // if no type, fall back to checking 'video/[extension]'
} else if (source.src) {
var ext = getfileextension(source.src);
return html5.nativesourcehandler.canplaytype("video/" + ext);
}
return '';
};
/**
* pass the source to the native media element.
*
* @param {tech~sourceobject} source
* the source object
*
* @param {html5} tech
* the instance of the html5 tech
*
* @param {object} [options]
* the options to pass to the source
*/
html5.nativesourcehandler.handlesource = function (source, tech, options) {
tech.setsrc(source.src);
};
/**
* a noop for the native dispose function, as cleanup is not needed.
*/
html5.nativesourcehandler.dispose = function () {}; // register the native source handler
html5.registersourcehandler(html5.nativesourcehandler);
tech.registertech('html5', html5);
// on the player when they happen
var tech_events_retrigger = [
/**
* fired while the user agent is downloading media data.
*
* @event player#progress
* @type {eventtarget~event}
*/
/**
* retrigger the `progress` event that was triggered by the {@link tech}.
*
* @private
* @method player#handletechprogress_
* @fires player#progress
* @listens tech#progress
*/
'progress',
/**
* fires when the loading of an audio/video is aborted.
*
* @event player#abort
* @type {eventtarget~event}
*/
/**
* retrigger the `abort` event that was triggered by the {@link tech}.
*
* @private
* @method player#handletechabort_
* @fires player#abort
* @listens tech#abort
*/
'abort',
/**
* fires when the browser is intentionally not getting media data.
*
* @event player#suspend
* @type {eventtarget~event}
*/
/**
* retrigger the `suspend` event that was triggered by the {@link tech}.
*
* @private
* @method player#handletechsuspend_
* @fires player#suspend
* @listens tech#suspend
*/
'suspend',
/**
* fires when the current playlist is empty.
*
* @event player#emptied
* @type {eventtarget~event}
*/
/**
* retrigger the `emptied` event that was triggered by the {@link tech}.
*
* @private
* @method player#handletechemptied_
* @fires player#emptied
* @listens tech#emptied
*/
'emptied',
/**
* fires when the browser is trying to get media data, but data is not available.
*
* @event player#stalled
* @type {eventtarget~event}
*/
/**
* retrigger the `stalled` event that was triggered by the {@link tech}.
*
* @private
* @method player#handletechstalled_
* @fires player#stalled
* @listens tech#stalled
*/
'stalled',
/**
* fires when the browser has loaded meta data for the audio/video.
*
* @event player#loadedmetadata
* @type {eventtarget~event}
*/
/**
* retrigger the `loadedmetadata` event that was triggered by the {@link tech}.
*
* @private
* @method player#handletechloadedmetadata_
* @fires player#loadedmetadata
* @listens tech#loadedmetadata
*/
'loadedmetadata',
/**
* fires when the browser has loaded the current frame of the audio/video.
*
* @event player#loadeddata
* @type {event}
*/
/**
* retrigger the `loadeddata` event that was triggered by the {@link tech}.
*
* @private
* @method player#handletechloaddeddata_
* @fires player#loadeddata
* @listens tech#loadeddata
*/
'loadeddata',
/**
* fires when the current playback position has changed.
*
* @event player#timeupdate
* @type {event}
*/
/**
* retrigger the `timeupdate` event that was triggered by the {@link tech}.
*
* @private
* @method player#handletechtimeupdate_
* @fires player#timeupdate
* @listens tech#timeupdate
*/
'timeupdate',
/**
* fires when the video's intrinsic dimensions change
*
* @event player#resize
* @type {event}
*/
/**
* retrigger the `resize` event that was triggered by the {@link tech}.
*
* @private
* @method player#handletechresize_
* @fires player#resize
* @listens tech#resize
*/
'resize',
/**
* fires when the volume has been changed
*
* @event player#volumechange
* @type {event}
*/
/**
* retrigger the `volumechange` event that was triggered by the {@link tech}.
*
* @private
* @method player#handletechvolumechange_
* @fires player#volumechange
* @listens tech#volumechange
*/
'volumechange',
/**
* fires when the text track has been changed
*
* @event player#texttrackchange
* @type {event}
*/
/**
* retrigger the `texttrackchange` event that was triggered by the {@link tech}.
*
* @private
* @method player#handletechtexttrackchange_
* @fires player#texttrackchange
* @listens tech#texttrackchange
*/
'texttrackchange']; // events to queue when playback rate is zero
// this is a hash for the sole purpose of mapping non-camel-cased event names
// to camel-cased function names
var tech_events_queue = {
canplay: 'canplay',
canplaythrough: 'canplaythrough',
playing: 'playing',
seeked: 'seeked'
};
var breakpoint_order = ['tiny', 'xsmall', 'small', 'medium', 'large', 'xlarge', 'huge'];
var breakpoint_classes = {}; // grep: vjs-layout-tiny
// grep: vjs-layout-x-small
// grep: vjs-layout-small
// grep: vjs-layout-medium
// grep: vjs-layout-large
// grep: vjs-layout-x-large
// grep: vjs-layout-huge
breakpoint_order.foreach(function (k) {
var v = k.charat(0) === 'x' ? "x-" + k.substring(1) : k;
breakpoint_classes[k] = "vjs-layout-" + v;
});
var default_breakpoints = {
tiny: 210,
xsmall: 320,
small: 425,
medium: 768,
large: 1440,
xlarge: 2560,
huge: infinity
};
/**
* an instance of the `player` class is created when any of the video.js setup methods
* are used to initialize a video.
*
* after an instance has been created it can be accessed globally in two ways:
* 1. by calling `videojs('example_video_1');`
* 2. by using it directly via `videojs.players.example_video_1;`
*
* @extends component
*/
var player = /*#__pure__*/function (_component) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(player, _component);
/**
* create an instance of this class.
*
* @param {element} tag
* the original video dom element used for configuring options.
*
* @param {object} [options]
* object of option names and values.
*
* @param {component~readycallback} [ready]
* ready callback function.
*/
function player(tag, options, ready) {
var _this;
// make sure tag id exists
tag.id = tag.id || options.id || "vjs_video_" + newguid(); // set options
// the options argument overrides options set in the video tag
// which overrides globally set options.
// this latter part coincides with the load order
// (tag must exist before player)
options = assign(player.gettagsettings(tag), options); // delay the initialization of children because we need to set up
// player properties first, and can't use `this` before `super()`
options.initchildren = false; // same with creating the element
options.createel = false; // don't auto mixin the evented mixin
options.evented = false; // we don't want the player to report touch activity on itself
// see enabletouchactivity in component
options.reporttouchactivity = false; // if language is not set, get the closest lang attribute
if (!options.language) {
if (typeof tag.closest === 'function') {
var closest = tag.closest('[lang]');
if (closest && closest.getattribute) {
options.language = closest.getattribute('lang');
}
} else {
var element = tag;
while (element && element.nodetype === 1) {
if (getattributes(element).hasownproperty('lang')) {
options.language = element.getattribute('lang');
break;
}
element = element.parentnode;
}
}
} // run base component initializing with new options
_this = _component.call(this, null, options, ready) || this; // create bound methods for document listeners.
_this.bounddocumentfullscreenchange_ = function (e) {
return _this.documentfullscreenchange_(e);
};
_this.boundfullwindowonesckey_ = function (e) {
return _this.fullwindowonesckey(e);
};
_this.boundupdatestyleel_ = function (e) {
return _this.updatestyleel_(e);
};
_this.boundapplyinittime_ = function (e) {
return _this.applyinittime_(e);
};
_this.boundupdatecurrentbreakpoint_ = function (e) {
return _this.updatecurrentbreakpoint_(e);
};
_this.boundhandletechclick_ = function (e) {
return _this.handletechclick_(e);
};
_this.boundhandletechdoubleclick_ = function (e) {
return _this.handletechdoubleclick_(e);
};
_this.boundhandletechtouchstart_ = function (e) {
return _this.handletechtouchstart_(e);
};
_this.boundhandletechtouchmove_ = function (e) {
return _this.handletechtouchmove_(e);
};
_this.boundhandletechtouchend_ = function (e) {
return _this.handletechtouchend_(e);
};
_this.boundhandletechtap_ = function (e) {
return _this.handletechtap_(e);
}; // default isfullscreen_ to false
_this.isfullscreen_ = false; // create logger
_this.log = createlogger(_this.id_); // hold our own reference to fullscreen api so it can be mocked in tests
_this.fsapi_ = fullscreenapi; // tracks when a tech changes the poster
_this.isposterfromtech_ = false; // holds callback info that gets queued when playback rate is zero
// and a seek is happening
_this.queuedcallbacks_ = []; // turn off api access because we're loading a new tech that might load asynchronously
_this.isready_ = false; // init state hasstarted_
_this.hasstarted_ = false; // init state useractive_
_this.useractive_ = false; // init debugenabled_
_this.debugenabled_ = false; // init state audioonlymode_
_this.audioonlymode_ = false; // init state audiopostermode_
_this.audiopostermode_ = false; // init state audioonlycache_
_this.audioonlycache_ = {
playerheight: null,
hiddenchildren: []
}; // if the global option object was accidentally blown away by
// someone, bail early with an informative error
if (!_this.options_ || !_this.options_.techorder || !_this.options_.techorder.length) {
throw new error('no techorder specified. did you overwrite ' + 'videojs.options instead of just changing the ' + 'properties you want to override?');
} // store the original tag used to set options
_this.tag = tag; // store the tag attributes used to restore html5 element
_this.tagattributes = tag && getattributes(tag); // update current language
_this.language(_this.options_.language); // update supported languages
if (options.languages) {
// normalise player option languages to lowercase
var languagestolower = {};
object.getownpropertynames(options.languages).foreach(function (name) {
languagestolower[name.tolowercase()] = options.languages[name];
});
_this.languages_ = languagestolower;
} else {
_this.languages_ = player.prototype.options_.languages;
}
_this.resetcache_(); // set poster
_this.poster_ = options.poster || ''; // set controls
_this.controls_ = !!options.controls; // original tag settings stored in options
// now remove immediately so native controls don't flash.
// may be turned back on by html5 tech if nativecontrolsfortouch is true
tag.controls = false;
tag.removeattribute('controls');
_this.changingsrc_ = false;
_this.playcallbacks_ = [];
_this.playterminatedqueue_ = []; // the attribute overrides the option
if (tag.hasattribute('autoplay')) {
_this.autoplay(true);
} else {
// otherwise use the setter to validate and
// set the correct value.
_this.autoplay(_this.options_.autoplay);
} // check plugins
if (options.plugins) {
object.keys(options.plugins).foreach(function (name) {
if (typeof _this[name] !== 'function') {
throw new error("plugin \"" + name + "\" does not exist");
}
});
}
/*
* store the internal state of scrubbing
*
* @private
* @return {boolean} true if the user is scrubbing
*/
_this.scrubbing_ = false;
_this.el_ = _this.createel(); // make this an evented object and use `el_` as its event bus.
evented(_babel_runtime_helpers_assertthisinitialized__webpack_imported_module_4___default()(_this), {
eventbuskey: 'el_'
}); // listen to document and player fullscreenchange handlers so we receive those events
// before a user can receive them so we can update isfullscreen appropriately.
// make sure that we listen to fullscreenchange events before everything else to make sure that
// our isfullscreen method is updated properly for internal components as well as external.
if (_this.fsapi_.requestfullscreen) {
on(global_document__webpack_imported_module_1___default.a, _this.fsapi_.fullscreenchange, _this.bounddocumentfullscreenchange_);
_this.on(_this.fsapi_.fullscreenchange, _this.bounddocumentfullscreenchange_);
}
if (_this.fluid_) {
_this.on(['playerreset', 'resize'], _this.boundupdatestyleel_);
} // we also want to pass the original player options to each component and plugin
// as well so they don't need to reach back into the player for options later.
// we also need to do another copy of this.options_ so we don't end up with
// an infinite loop.
var playeroptionscopy = mergeoptions$3(_this.options_); // load plugins
if (options.plugins) {
object.keys(options.plugins).foreach(function (name) {
_this[name](options.plugins[name]);
});
} // enable debug mode to fire debugon event for all plugins.
if (options.debug) {
_this.debug(true);
}
_this.options_.playeroptions = playeroptionscopy;
_this.middleware_ = [];
_this.playbackrates(options.playbackrates);
_this.initchildren(); // set isaudio based on whether or not an audio tag was used
_this.isaudio(tag.nodename.tolowercase() === 'audio'); // update controls classname. can't do this when the controls are initially
// set because the element doesn't exist yet.
if (_this.controls()) {
_this.addclass('vjs-controls-enabled');
} else {
_this.addclass('vjs-controls-disabled');
} // set aria label and region role depending on player type
_this.el_.setattribute('role', 'region');
if (_this.isaudio()) {
_this.el_.setattribute('aria-label', _this.localize('audio player'));
} else {
_this.el_.setattribute('aria-label', _this.localize('video player'));
}
if (_this.isaudio()) {
_this.addclass('vjs-audio');
}
if (_this.flexnotsupported_()) {
_this.addclass('vjs-no-flex');
} // todo: make this smarter. toggle user state between touching/mousing
// using events, since devices can have both touch and mouse events.
// todo: make this check be performed again when the window switches between monitors
// (see https://github.com/videojs/video.js/issues/5683)
if (touch_enabled) {
_this.addclass('vjs-touch-enabled');
} // ios safari has broken hover handling
if (!is_ios) {
_this.addclass('vjs-workinghover');
} // make player easily findable by id
player.players[_this.id_] = _babel_runtime_helpers_assertthisinitialized__webpack_imported_module_4___default()(_this); // add a major version class to aid css in plugins
var majorversion = version$5.split('.')[0];
_this.addclass("vjs-v" + majorversion); // when the player is first initialized, trigger activity so components
// like the control bar show themselves if needed
_this.useractive(true);
_this.reportuseractivity();
_this.one('play', function (e) {
return _this.listenforuseractivity_(e);
});
_this.on('stageclick', function (e) {
return _this.handlestageclick_(e);
});
_this.on('keydown', function (e) {
return _this.handlekeydown(e);
});
_this.on('languagechange', function (e) {
return _this.handlelanguagechange(e);
});
_this.breakpoints(_this.options_.breakpoints);
_this.responsive(_this.options_.responsive); // calling both the audio mode methods after the player is fully
// setup to be able to listen to the events triggered by them
_this.on('ready', function () {
// calling the audiopostermode method first so that
// the audioonlymode can take precedence when both options are set to true
_this.audiopostermode(_this.options_.audiopostermode);
_this.audioonlymode(_this.options_.audioonlymode);
});
return _this;
}
/**
* destroys the video player and does any necessary cleanup.
*
* this is especially helpful if you are dynamically adding and removing videos
* to/from the dom.
*
* @fires player#dispose
*/
var _proto = player.prototype;
_proto.dispose = function dispose() {
var _this2 = this;
/**
* called when the player is being disposed of.
*
* @event player#dispose
* @type {eventtarget~event}
*/
this.trigger('dispose'); // prevent dispose from being called twice
this.off('dispose'); // make sure all player-specific document listeners are unbound. this is
off(global_document__webpack_imported_module_1___default.a, this.fsapi_.fullscreenchange, this.bounddocumentfullscreenchange_);
off(global_document__webpack_imported_module_1___default.a, 'keydown', this.boundfullwindowonesckey_);
if (this.styleel_ && this.styleel_.parentnode) {
this.styleel_.parentnode.removechild(this.styleel_);
this.styleel_ = null;
} // kill reference to this player
player.players[this.id_] = null;
if (this.tag && this.tag.player) {
this.tag.player = null;
}
if (this.el_ && this.el_.player) {
this.el_.player = null;
}
if (this.tech_) {
this.tech_.dispose();
this.isposterfromtech_ = false;
this.poster_ = '';
}
if (this.playerelingest_) {
this.playerelingest_ = null;
}
if (this.tag) {
this.tag = null;
}
clearcacheforplayer(this); // remove all event handlers for track lists
// all tracks and track listeners are removed on
// tech dispose
all.names.foreach(function (name) {
var props = all[name];
var list = _this2[props.gettername](); // if it is not a native list
// we have to manually remove event listeners
if (list && list.off) {
list.off();
}
}); // the actual .el_ is removed here, or replaced if
_component.prototype.dispose.call(this, {
restoreel: this.options_.restoreel
});
}
/**
* create the `player`'s dom element.
*
* @return {element}
* the dom element that gets created.
*/
;
_proto.createel = function createel() {
var tag = this.tag;
var el;
var playerelingest = this.playerelingest_ = tag.parentnode && tag.parentnode.hasattribute && tag.parentnode.hasattribute('data-vjs-player');
var divembed = this.tag.tagname.tolowercase() === 'video-js';
if (playerelingest) {
el = this.el_ = tag.parentnode;
} else if (!divembed) {
el = this.el_ = _component.prototype.createel.call(this, 'div');
} // copy over all the attributes from the tag, including id and class
// id will now reference player box, not the video tag
var attrs = getattributes(tag);
if (divembed) {
el = this.el_ = tag;
tag = this.tag = global_document__webpack_imported_module_1___default.a.createelement('video');
while (el.children.length) {
tag.appendchild(el.firstchild);
}
if (!hasclass(el, 'video-js')) {
addclass(el, 'video-js');
}
el.appendchild(tag);
playerelingest = this.playerelingest_ = el; // move properties over from our custom `video-js` element
// to our new `video` element. this will move things like
// `src` or `controls` that were set via js before the player
// was initialized.
object.keys(el).foreach(function (k) {
try {
tag[k] = el[k];
} catch (e) {// we got a a property like outerhtml which we can't actually copy, ignore it
}
});
} // set tabindex to -1 to remove the video element from the focus order
tag.setattribute('tabindex', '-1');
attrs.tabindex = '-1'; // workaround for #4583 (jaws+ie doesn't announce bpb or play button), and
// for the same issue with chrome (on windows) with jaws.
// see https://github.com/freedomscientific/vfo-standards-support/issues/78
// note that we can't detect if jaws is being used, but this aria attribute
// doesn't change behavior of ie11 or chrome if jaws is not being used
if (ie_version || is_chrome && is_windows) {
tag.setattribute('role', 'application');
attrs.role = 'application';
} // remove width/height attrs from tag so css can make it 100% width/height
tag.removeattribute('width');
tag.removeattribute('height');
if ('width' in attrs) {
delete attrs.width;
}
if ('height' in attrs) {
delete attrs.height;
}
object.getownpropertynames(attrs).foreach(function (attr) {
// don't copy over the class attribute to the player element when we're in a div embed
// the class is already set up properly in the divembed case
// and we want to make sure that the `video-js` class doesn't get lost
if (!(divembed && attr === 'class')) {
el.setattribute(attr, attrs[attr]);
}
if (divembed) {
tag.setattribute(attr, attrs[attr]);
}
}); // update tag id/class for use as html5 playback tech
// might think we should do this after embedding in container so .vjs-tech class
// doesn't flash 100% width/height, but class only applies with .video-js parent
tag.playerid = tag.id;
tag.id += '_html5_api';
tag.classname = 'vjs-tech'; // make player findable on elements
tag.player = el.player = this; // default state of video is paused
this.addclass('vjs-paused'); // add a style element in the player that we'll use to set the width/height
// of the player in a way that's still overrideable by css, just like the
// video element
if (global_window__webpack_imported_module_0___default.a.videojs_no_dynamic_style !== true) {
this.styleel_ = createstyleelement('vjs-styles-dimensions');
var defaultsstyleel = $('.vjs-styles-defaults');
var head = $('head');
head.insertbefore(this.styleel_, defaultsstyleel ? defaultsstyleel.nextsibling : head.firstchild);
}
this.fill_ = false;
this.fluid_ = false; // pass in the width/height/aspectratio options which will update the style el
this.width(this.options_.width);
this.height(this.options_.height);
this.fill(this.options_.fill);
this.fluid(this.options_.fluid);
this.aspectratio(this.options_.aspectratio); // support both crossorigin and crossorigin to reduce confusion and issues around the name
this.crossorigin(this.options_.crossorigin || this.options_.crossorigin); // hide any links within the video/audio tag,
// because ie doesn't hide them completely from screen readers.
var links = tag.getelementsbytagname('a');
for (var i = 0; i < links.length; i++) {
var linkel = links.item(i);
addclass(linkel, 'vjs-hidden');
linkel.setattribute('hidden', 'hidden');
} // insertelfirst seems to cause the networkstate to flicker from 3 to 2, so
// keep track of the original for later so we can know if the source originally failed
tag.initnetworkstate_ = tag.networkstate; // wrap video tag in div (el/box) container
if (tag.parentnode && !playerelingest) {
tag.parentnode.insertbefore(el, tag);
} // insert the tag as the first child of the player element
// then manually add it to the children array so that this.addchild
// will work properly for other components
//
// breaks iphone, fixed in html5 setup.
prependto(tag, el);
this.children_.unshift(tag); // set lang attr on player to ensure css :lang() in consistent with player
// if it's been set to something different to the doc
this.el_.setattribute('lang', this.language_);
this.el_.setattribute('translate', 'no');
this.el_ = el;
return el;
}
/**
* get or set the `player`'s crossorigin option. for the html5 player, this
* sets the `crossorigin` property on the `` tag to control the cors
* behavior.
*
* @see [video element attributes]{@link https://developer.mozilla.org/en-us/docs/web/html/element/video#attr-crossorigin}
*
* @param {string} [value]
* the value to set the `player`'s crossorigin to. if an argument is
* given, must be one of `anonymous` or `use-credentials`.
*
* @return {string|undefined}
* - the current crossorigin value of the `player` when getting.
* - undefined when setting
*/
;
_proto.crossorigin = function crossorigin(value) {
if (!value) {
return this.techget_('crossorigin');
}
if (value !== 'anonymous' && value !== 'use-credentials') {
log$1.warn("crossorigin must be \"anonymous\" or \"use-credentials\", given \"" + value + "\"");
return;
}
this.techcall_('setcrossorigin', value);
return;
}
/**
* a getter/setter for the `player`'s width. returns the player's configured value.
* to get the current width use `currentwidth()`.
*
* @param {number} [value]
* the value to set the `player`'s width to.
*
* @return {number}
* the current width of the `player` when getting.
*/
;
_proto.width = function width(value) {
return this.dimension('width', value);
}
/**
* a getter/setter for the `player`'s height. returns the player's configured value.
* to get the current height use `currentheight()`.
*
* @param {number} [value]
* the value to set the `player`'s heigth to.
*
* @return {number}
* the current height of the `player` when getting.
*/
;
_proto.height = function height(value) {
return this.dimension('height', value);
}
/**
* a getter/setter for the `player`'s width & height.
*
* @param {string} dimension
* this string can be:
* - 'width'
* - 'height'
*
* @param {number} [value]
* value for dimension specified in the first argument.
*
* @return {number}
* the dimension arguments value when getting (width/height).
*/
;
_proto.dimension = function dimension(_dimension, value) {
var privdimension = _dimension + '_';
if (value === undefined) {
return this[privdimension] || 0;
}
if (value === '' || value === 'auto') {
// if an empty string is given, reset the dimension to be automatic
this[privdimension] = undefined;
this.updatestyleel_();
return;
}
var parsedval = parsefloat(value);
if (isnan(parsedval)) {
log$1.error("improper value \"" + value + "\" supplied for for " + _dimension);
return;
}
this[privdimension] = parsedval;
this.updatestyleel_();
}
/**
* a getter/setter/toggler for the vjs-fluid `classname` on the `player`.
*
* turning this on will turn off fill mode.
*
* @param {boolean} [bool]
* - a value of true adds the class.
* - a value of false removes the class.
* - no value will be a getter.
*
* @return {boolean|undefined}
* - the value of fluid when getting.
* - `undefined` when setting.
*/
;
_proto.fluid = function fluid(bool) {
var _this3 = this;
if (bool === undefined) {
return !!this.fluid_;
}
this.fluid_ = !!bool;
if (isevented(this)) {
this.off(['playerreset', 'resize'], this.boundupdatestyleel_);
}
if (bool) {
this.addclass('vjs-fluid');
this.fill(false);
addeventedcallback(this, function () {
_this3.on(['playerreset', 'resize'], _this3.boundupdatestyleel_);
});
} else {
this.removeclass('vjs-fluid');
}
this.updatestyleel_();
}
/**
* a getter/setter/toggler for the vjs-fill `classname` on the `player`.
*
* turning this on will turn off fluid mode.
*
* @param {boolean} [bool]
* - a value of true adds the class.
* - a value of false removes the class.
* - no value will be a getter.
*
* @return {boolean|undefined}
* - the value of fluid when getting.
* - `undefined` when setting.
*/
;
_proto.fill = function fill(bool) {
if (bool === undefined) {
return !!this.fill_;
}
this.fill_ = !!bool;
if (bool) {
this.addclass('vjs-fill');
this.fluid(false);
} else {
this.removeclass('vjs-fill');
}
}
/**
* get/set the aspect ratio
*
* @param {string} [ratio]
* aspect ratio for player
*
* @return {string|undefined}
* returns the current aspect ratio when getting
*/
/**
* a getter/setter for the `player`'s aspect ratio.
*
* @param {string} [ratio]
* the value to set the `player`'s aspect ratio to.
*
* @return {string|undefined}
* - the current aspect ratio of the `player` when getting.
* - undefined when setting
*/
;
_proto.aspectratio = function aspectratio(ratio) {
if (ratio === undefined) {
return this.aspectratio_;
} // check for width:height format
if (!/^\d+\:\d+$/.test(ratio)) {
throw new error('improper value supplied for aspect ratio. the format should be width:height, for example 16:9.');
}
this.aspectratio_ = ratio; // we're assuming if you set an aspect ratio you want fluid mode,
// because in fixed mode you could calculate width and height yourself.
this.fluid(true);
this.updatestyleel_();
}
/**
* update styles of the `player` element (height, width and aspect ratio).
*
* @private
* @listens tech#loadedmetadata
*/
;
_proto.updatestyleel_ = function updatestyleel_() {
if (global_window__webpack_imported_module_0___default.a.videojs_no_dynamic_style === true) {
var _width = typeof this.width_ === 'number' ? this.width_ : this.options_.width;
var _height = typeof this.height_ === 'number' ? this.height_ : this.options_.height;
var techel = this.tech_ && this.tech_.el();
if (techel) {
if (_width >= 0) {
techel.width = _width;
}
if (_height >= 0) {
techel.height = _height;
}
}
return;
}
var width;
var height;
var aspectratio;
var idclass; // the aspect ratio is either used directly or to calculate width and height.
if (this.aspectratio_ !== undefined && this.aspectratio_ !== 'auto') {
// use any aspectratio that's been specifically set
aspectratio = this.aspectratio_;
} else if (this.videowidth() > 0) {
// otherwise try to get the aspect ratio from the video metadata
aspectratio = this.videowidth() + ':' + this.videoheight();
} else {
// or use a default. the video element's is 2:1, but 16:9 is more common.
aspectratio = '16:9';
} // get the ratio as a decimal we can use to calculate dimensions
var ratioparts = aspectratio.split(':');
var ratiomultiplier = ratioparts[1] / ratioparts[0];
if (this.width_ !== undefined) {
// use any width that's been specifically set
width = this.width_;
} else if (this.height_ !== undefined) {
// or calulate the width from the aspect ratio if a height has been set
width = this.height_ / ratiomultiplier;
} else {
// or use the video's metadata, or use the video el's default of 300
width = this.videowidth() || 300;
}
if (this.height_ !== undefined) {
// use any height that's been specifically set
height = this.height_;
} else {
// otherwise calculate the height from the ratio and the width
height = width * ratiomultiplier;
} // ensure the css class is valid by starting with an alpha character
if (/^[^a-za-z]/.test(this.id())) {
idclass = 'dimensions-' + this.id();
} else {
idclass = this.id() + '-dimensions';
} // ensure the right class is still on the player for the style element
this.addclass(idclass);
settextcontent(this.styleel_, "\n ." + idclass + " {\n width: " + width + "px;\n height: " + height + "px;\n }\n\n ." + idclass + ".vjs-fluid:not(.vjs-audio-only-mode) {\n padding-top: " + ratiomultiplier * 100 + "%;\n }\n ");
}
/**
* load/create an instance of playback {@link tech} including element
* and api methods. then append the `tech` element in `player` as a child.
*
* @param {string} techname
* name of the playback technology
*
* @param {string} source
* video source
*
* @private
*/
;
_proto.loadtech_ = function loadtech_(techname, source) {
var _this4 = this;
// pause and remove current playback technology
if (this.tech_) {
this.unloadtech_();
}
var titletechname = totitlecase$1(techname);
var cameltechname = techname.charat(0).tolowercase() + techname.slice(1); // get rid of the html5 video tag as soon as we are using another tech
if (titletechname !== 'html5' && this.tag) {
tech.gettech('html5').disposemediaelement(this.tag);
this.tag.player = null;
this.tag = null;
}
this.techname_ = titletechname; // turn off api access because we're loading a new tech that might load asynchronously
this.isready_ = false;
var autoplay = this.autoplay(); // if autoplay is a string (or `true` with normalizeautoplay: true) we pass false to the tech
// because the player is going to handle autoplay on `loadstart`
if (typeof this.autoplay() === 'string' || this.autoplay() === true && this.options_.normalizeautoplay) {
autoplay = false;
} // grab tech-specific options from player options and add source and parent element to use.
var techoptions = {
source: source,
autoplay: autoplay,
'nativecontrolsfortouch': this.options_.nativecontrolsfortouch,
'playerid': this.id(),
'techid': this.id() + "_" + cameltechname + "_api",
'playsinline': this.options_.playsinline,
'preload': this.options_.preload,
'loop': this.options_.loop,
'disablepictureinpicture': this.options_.disablepictureinpicture,
'muted': this.options_.muted,
'poster': this.poster(),
'language': this.language(),
'playerelingest': this.playerelingest_ || false,
'vtt.js': this.options_['vtt.js'],
'canoverrideposter': !!this.options_.techcanoverrideposter,
'enablesourceset': this.options_.enablesourceset,
'promise': this.options_.promise
};
all.names.foreach(function (name) {
var props = all[name];
techoptions[props.gettername] = _this4[props.privatename];
});
assign(techoptions, this.options_[titletechname]);
assign(techoptions, this.options_[cameltechname]);
assign(techoptions, this.options_[techname.tolowercase()]);
if (this.tag) {
techoptions.tag = this.tag;
}
if (source && source.src === this.cache_.src && this.cache_.currenttime > 0) {
techoptions.starttime = this.cache_.currenttime;
} // initialize tech instance
var techclass = tech.gettech(techname);
if (!techclass) {
throw new error("no tech named '" + titletechname + "' exists! '" + titletechname + "' should be registered using videojs.registertech()'");
}
this.tech_ = new techclass(techoptions); // player.triggerready is always async, so don't need this to be async
this.tech_.ready(bind(this, this.handletechready_), true);
texttrackconverter.jsontotexttracks(this.texttracksjson_ || [], this.tech_); // listen to all html5-defined events and trigger them on the player
tech_events_retrigger.foreach(function (event) {
_this4.on(_this4.tech_, event, function (e) {
return _this4["handletech" + totitlecase$1(event) + "_"](e);
});
});
object.keys(tech_events_queue).foreach(function (event) {
_this4.on(_this4.tech_, event, function (eventobj) {
if (_this4.tech_.playbackrate() === 0 && _this4.tech_.seeking()) {
_this4.queuedcallbacks_.push({
callback: _this4["handletech" + tech_events_queue[event] + "_"].bind(_this4),
event: eventobj
});
return;
}
_this4["handletech" + tech_events_queue[event] + "_"](eventobj);
});
});
this.on(this.tech_, 'loadstart', function (e) {
return _this4.handletechloadstart_(e);
});
this.on(this.tech_, 'sourceset', function (e) {
return _this4.handletechsourceset_(e);
});
this.on(this.tech_, 'waiting', function (e) {
return _this4.handletechwaiting_(e);
});
this.on(this.tech_, 'ended', function (e) {
return _this4.handletechended_(e);
});
this.on(this.tech_, 'seeking', function (e) {
return _this4.handletechseeking_(e);
});
this.on(this.tech_, 'play', function (e) {
return _this4.handletechplay_(e);
});
this.on(this.tech_, 'firstplay', function (e) {
return _this4.handletechfirstplay_(e);
});
this.on(this.tech_, 'pause', function (e) {
return _this4.handletechpause_(e);
});
this.on(this.tech_, 'durationchange', function (e) {
return _this4.handletechdurationchange_(e);
});
this.on(this.tech_, 'fullscreenchange', function (e, data) {
return _this4.handletechfullscreenchange_(e, data);
});
this.on(this.tech_, 'fullscreenerror', function (e, err) {
return _this4.handletechfullscreenerror_(e, err);
});
this.on(this.tech_, 'enterpictureinpicture', function (e) {
return _this4.handletechenterpictureinpicture_(e);
});
this.on(this.tech_, 'leavepictureinpicture', function (e) {
return _this4.handletechleavepictureinpicture_(e);
});
this.on(this.tech_, 'error', function (e) {
return _this4.handletecherror_(e);
});
this.on(this.tech_, 'posterchange', function (e) {
return _this4.handletechposterchange_(e);
});
this.on(this.tech_, 'textdata', function (e) {
return _this4.handletechtextdata_(e);
});
this.on(this.tech_, 'ratechange', function (e) {
return _this4.handletechratechange_(e);
});
this.on(this.tech_, 'loadedmetadata', this.boundupdatestyleel_);
this.usingnativecontrols(this.techget_('controls'));
if (this.controls() && !this.usingnativecontrols()) {
this.addtechcontrolslisteners_();
} // add the tech element in the dom if it was not already there
// make sure to not insert the original video element if using html5
if (this.tech_.el().parentnode !== this.el() && (titletechname !== 'html5' || !this.tag)) {
prependto(this.tech_.el(), this.el());
} // get rid of the original video tag reference after the first tech is loaded
if (this.tag) {
this.tag.player = null;
this.tag = null;
}
}
/**
* unload and dispose of the current playback {@link tech}.
*
* @private
*/
;
_proto.unloadtech_ = function unloadtech_() {
var _this5 = this;
// save the current text tracks so that we can reuse the same text tracks with the next tech
all.names.foreach(function (name) {
var props = all[name];
_this5[props.privatename] = _this5[props.gettername]();
});
this.texttracksjson_ = texttrackconverter.texttrackstojson(this.tech_);
this.isready_ = false;
this.tech_.dispose();
this.tech_ = false;
if (this.isposterfromtech_) {
this.poster_ = '';
this.trigger('posterchange');
}
this.isposterfromtech_ = false;
}
/**
* return a reference to the current {@link tech}.
* it will print a warning by default about the danger of using the tech directly
* but any argument that is passed in will silence the warning.
*
* @param {*} [safety]
* anything passed in to silence the warning
*
* @return {tech}
* the tech
*/
;
_proto.tech = function tech(safety) {
if (safety === undefined) {
log$1.warn('using the tech directly can be dangerous. i hope you know what you\'re doing.\n' + 'see https://github.com/videojs/video.js/issues/2617 for more info.\n');
}
return this.tech_;
}
/**
* set up click and touch listeners for the playback element
*
* - on desktops: a click on the video itself will toggle playback
* - on mobile devices: a click on the video toggles controls
* which is done by toggling the user state between active and
* inactive
* - a tap can signal that a user has become active or has become inactive
* e.g. a quick tap on an iphone movie should reveal the controls. another
* quick tap should hide them again (signaling the user is in an inactive
* viewing state)
* - in addition to this, we still want the user to be considered inactive after
* a few seconds of inactivity.
*
* > note: the only part of ios interaction we can't mimic with this setup
* is a touch and hold on the video element counting as activity in order to
* keep the controls showing, but that shouldn't be an issue. a touch and hold
* on any controls will still keep the user active
*
* @private
*/
;
_proto.addtechcontrolslisteners_ = function addtechcontrolslisteners_() {
// make sure to remove all the previous listeners in case we are called multiple times.
this.removetechcontrolslisteners_();
this.on(this.tech_, 'click', this.boundhandletechclick_);
this.on(this.tech_, 'dblclick', this.boundhandletechdoubleclick_); // if the controls were hidden we don't want that to change without a tap event
// so we'll check if the controls were already showing before reporting user
// activity
this.on(this.tech_, 'touchstart', this.boundhandletechtouchstart_);
this.on(this.tech_, 'touchmove', this.boundhandletechtouchmove_);
this.on(this.tech_, 'touchend', this.boundhandletechtouchend_); // the tap listener needs to come after the touchend listener because the tap
// listener cancels out any reporteduseractivity when setting useractive(false)
this.on(this.tech_, 'tap', this.boundhandletechtap_);
}
/**
* remove the listeners used for click and tap controls. this is needed for
* toggling to controls disabled, where a tap/touch should do nothing.
*
* @private
*/
;
_proto.removetechcontrolslisteners_ = function removetechcontrolslisteners_() {
// we don't want to just use `this.off()` because there might be other needed
// listeners added by techs that extend this.
this.off(this.tech_, 'tap', this.boundhandletechtap_);
this.off(this.tech_, 'touchstart', this.boundhandletechtouchstart_);
this.off(this.tech_, 'touchmove', this.boundhandletechtouchmove_);
this.off(this.tech_, 'touchend', this.boundhandletechtouchend_);
this.off(this.tech_, 'click', this.boundhandletechclick_);
this.off(this.tech_, 'dblclick', this.boundhandletechdoubleclick_);
}
/**
* player waits for the tech to be ready
*
* @private
*/
;
_proto.handletechready_ = function handletechready_() {
this.triggerready(); // keep the same volume as before
if (this.cache_.volume) {
this.techcall_('setvolume', this.cache_.volume);
} // look if the tech found a higher resolution poster while loading
this.handletechposterchange_(); // update the duration if available
this.handletechdurationchange_();
}
/**
* retrigger the `loadstart` event that was triggered by the {@link tech}. this
* function will also trigger {@link player#firstplay} if it is the first loadstart
* for a video.
*
* @fires player#loadstart
* @fires player#firstplay
* @listens tech#loadstart
* @private
*/
;
_proto.handletechloadstart_ = function handletechloadstart_() {
// todo: update to use `emptied` event instead. see #1277.
this.removeclass('vjs-ended');
this.removeclass('vjs-seeking'); // reset the error state
this.error(null); // update the duration
this.handletechdurationchange_(); // if it's already playing we want to trigger a firstplay event now.
// the firstplay event relies on both the play and loadstart events
// which can happen in any order for a new source
if (!this.paused()) {
/**
* fired when the user agent begins looking for media data
*
* @event player#loadstart
* @type {eventtarget~event}
*/
this.trigger('loadstart');
this.trigger('firstplay');
} else {
// reset the hasstarted state
this.hasstarted(false);
this.trigger('loadstart');
} // autoplay happens after loadstart for the browser,
// so we mimic that behavior
this.manualautoplay_(this.autoplay() === true && this.options_.normalizeautoplay ? 'play' : this.autoplay());
}
/**
* handle autoplay string values, rather than the typical boolean
* values that should be handled by the tech. note that this is not
* part of any specification. valid values and what they do can be
* found on the autoplay getter at player#autoplay()
*/
;
_proto.manualautoplay_ = function manualautoplay_(type) {
var _this6 = this;
if (!this.tech_ || typeof type !== 'string') {
return;
} // save original muted() value, set muted to true, and attempt to play().
// on promise rejection, restore muted from saved value
var resolvemuted = function resolvemuted() {
var previouslymuted = _this6.muted();
_this6.muted(true);
var restoremuted = function restoremuted() {
_this6.muted(previouslymuted);
}; // restore muted on play terminatation
_this6.playterminatedqueue_.push(restoremuted);
var mutedpromise = _this6.play();
if (!ispromise(mutedpromise)) {
return;
}
return mutedpromise["catch"](function (err) {
restoremuted();
throw new error("rejection at manualautoplay. restoring muted value. " + (err ? err : ''));
});
};
var promise; // if muted defaults to true
// the only thing we can do is call play
if (type === 'any' && !this.muted()) {
promise = this.play();
if (ispromise(promise)) {
promise = promise["catch"](resolvemuted);
}
} else if (type === 'muted' && !this.muted()) {
promise = resolvemuted();
} else {
promise = this.play();
}
if (!ispromise(promise)) {
return;
}
return promise.then(function () {
_this6.trigger({
type: 'autoplay-success',
autoplay: type
});
})["catch"](function () {
_this6.trigger({
type: 'autoplay-failure',
autoplay: type
});
});
}
/**
* update the internal source caches so that we return the correct source from
* `src()`, `currentsource()`, and `currentsources()`.
*
* > note: `currentsources` will not be updated if the source that is passed in exists
* in the current `currentsources` cache.
*
*
* @param {tech~sourceobject} srcobj
* a string or object source to update our caches to.
*/
;
_proto.updatesourcecaches_ = function updatesourcecaches_(srcobj) {
if (srcobj === void 0) {
srcobj = '';
}
var src = srcobj;
var type = '';
if (typeof src !== 'string') {
src = srcobj.src;
type = srcobj.type;
} // make sure all the caches are set to default values
// to prevent null checking
this.cache_.source = this.cache_.source || {};
this.cache_.sources = this.cache_.sources || []; // try to get the type of the src that was passed in
if (src && !type) {
type = findmimetype(this, src);
} // update `currentsource` cache always
this.cache_.source = mergeoptions$3({}, srcobj, {
src: src,
type: type
});
var matchingsources = this.cache_.sources.filter(function (s) {
return s.src && s.src === src;
});
var sourceelsources = [];
var sourceels = this.$$('source');
var matchingsourceels = [];
for (var i = 0; i < sourceels.length; i++) {
var sourceobj = getattributes(sourceels[i]);
sourceelsources.push(sourceobj);
if (sourceobj.src && sourceobj.src === src) {
matchingsourceels.push(sourceobj.src);
}
} // if we have matching source els but not matching sources
// the current source cache is not up to date
if (matchingsourceels.length && !matchingsources.length) {
this.cache_.sources = sourceelsources; // if we don't have matching source or source els set the
// sources cache to the `currentsource` cache
} else if (!matchingsources.length) {
this.cache_.sources = [this.cache_.source];
} // update the tech `src` cache
this.cache_.src = src;
}
/**
* *experimental* fired when the source is set or changed on the {@link tech}
* causing the media element to reload.
*
* it will fire for the initial source and each subsequent source.
* this event is a custom event from video.js and is triggered by the {@link tech}.
*
* the event object for this event contains a `src` property that will contain the source
* that was available when the event was triggered. this is generally only necessary if video.js
* is switching techs while the source was being changed.
*
* it is also fired when `load` is called on the player (or media element)
* because the {@link https://html.spec.whatwg.org/multipage/media.html#dom-media-load|specification for `load`}
* says that the resource selection algorithm needs to be aborted and restarted.
* in this case, it is very likely that the `src` property will be set to the
* empty string `""` to indicate we do not know what the source will be but
* that it is changing.
*
* *this event is currently still experimental and may change in minor releases.*
* __to use this, pass `enablesourceset` option to the player.__
*
* @event player#sourceset
* @type {eventtarget~event}
* @prop {string} src
* the source url available when the `sourceset` was triggered.
* it will be an empty string if we cannot know what the source is
* but know that the source will change.
*/
/**
* retrigger the `sourceset` event that was triggered by the {@link tech}.
*
* @fires player#sourceset
* @listens tech#sourceset
* @private
*/
;
_proto.handletechsourceset_ = function handletechsourceset_(event) {
var _this7 = this;
// only update the source cache when the source
// was not updated using the player api
if (!this.changingsrc_) {
var updatesourcecaches = function updatesourcecaches(src) {
return _this7.updatesourcecaches_(src);
};
var playersrc = this.currentsource().src;
var eventsrc = event.src; // if we have a playersrc that is not a blob, and a tech src that is a blob
if (playersrc && !/^blob:/.test(playersrc) && /^blob:/.test(eventsrc)) {
// if both the tech source and the player source were updated we assume
// something like @videojs/http-streaming did the sourceset and skip updating the source cache.
if (!this.lastsource_ || this.lastsource_.tech !== eventsrc && this.lastsource_.player !== playersrc) {
updatesourcecaches = function updatesourcecaches() {};
}
} // update the source to the initial source right away
// in some cases this will be empty string
updatesourcecaches(eventsrc); // if the `sourceset` `src` was an empty string
// wait for a `loadstart` to update the cache to `currentsrc`.
// if a sourceset happens before a `loadstart`, we reset the state
if (!event.src) {
this.tech_.any(['sourceset', 'loadstart'], function (e) {
// if a sourceset happens before a `loadstart` there
// is nothing to do as this `handletechsourceset_`
// will be called again and this will be handled there.
if (e.type === 'sourceset') {
return;
}
var techsrc = _this7.techget('currentsrc');
_this7.lastsource_.tech = techsrc;
_this7.updatesourcecaches_(techsrc);
});
}
}
this.lastsource_ = {
player: this.currentsource().src,
tech: event.src
};
this.trigger({
src: event.src,
type: 'sourceset'
});
}
/**
* add/remove the vjs-has-started class
*
* @fires player#firstplay
*
* @param {boolean} request
* - true: adds the class
* - false: remove the class
*
* @return {boolean}
* the boolean value of hasstarted_
*/
;
_proto.hasstarted = function hasstarted(request) {
if (request === undefined) {
// act as getter, if we have no request to change
return this.hasstarted_;
}
if (request === this.hasstarted_) {
return;
}
this.hasstarted_ = request;
if (this.hasstarted_) {
this.addclass('vjs-has-started');
this.trigger('firstplay');
} else {
this.removeclass('vjs-has-started');
}
}
/**
* fired whenever the media begins or resumes playback
*
* @see [spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-play}
* @fires player#play
* @listens tech#play
* @private
*/
;
_proto.handletechplay_ = function handletechplay_() {
this.removeclass('vjs-ended');
this.removeclass('vjs-paused');
this.addclass('vjs-playing'); // hide the poster when the user hits play
this.hasstarted(true);
/**
* triggered whenever an {@link tech#play} event happens. indicates that
* playback has started or resumed.
*
* @event player#play
* @type {eventtarget~event}
*/
this.trigger('play');
}
/**
* retrigger the `ratechange` event that was triggered by the {@link tech}.
*
* if there were any events queued while the playback rate was zero, fire
* those events now.
*
* @private
* @method player#handletechratechange_
* @fires player#ratechange
* @listens tech#ratechange
*/
;
_proto.handletechratechange_ = function handletechratechange_() {
if (this.tech_.playbackrate() > 0 && this.cache_.lastplaybackrate === 0) {
this.queuedcallbacks_.foreach(function (queued) {
return queued.callback(queued.event);
});
this.queuedcallbacks_ = [];
}
this.cache_.lastplaybackrate = this.tech_.playbackrate();
/**
* fires when the playing speed of the audio/video is changed
*
* @event player#ratechange
* @type {event}
*/
this.trigger('ratechange');
}
/**
* retrigger the `waiting` event that was triggered by the {@link tech}.
*
* @fires player#waiting
* @listens tech#waiting
* @private
*/
;
_proto.handletechwaiting_ = function handletechwaiting_() {
var _this8 = this;
this.addclass('vjs-waiting');
/**
* a readystate change on the dom element has caused playback to stop.
*
* @event player#waiting
* @type {eventtarget~event}
*/
this.trigger('waiting'); // browsers may emit a timeupdate event after a waiting event. in order to prevent
// premature removal of the waiting class, wait for the time to change.
var timewhenwaiting = this.currenttime();
var timeupdatelistener = function timeupdatelistener() {
if (timewhenwaiting !== _this8.currenttime()) {
_this8.removeclass('vjs-waiting');
_this8.off('timeupdate', timeupdatelistener);
}
};
this.on('timeupdate', timeupdatelistener);
}
/**
* retrigger the `canplay` event that was triggered by the {@link tech}.
* > note: this is not consistent between browsers. see #1351
*
* @fires player#canplay
* @listens tech#canplay
* @private
*/
;
_proto.handletechcanplay_ = function handletechcanplay_() {
this.removeclass('vjs-waiting');
/**
* the media has a readystate of have_future_data or greater.
*
* @event player#canplay
* @type {eventtarget~event}
*/
this.trigger('canplay');
}
/**
* retrigger the `canplaythrough` event that was triggered by the {@link tech}.
*
* @fires player#canplaythrough
* @listens tech#canplaythrough
* @private
*/
;
_proto.handletechcanplaythrough_ = function handletechcanplaythrough_() {
this.removeclass('vjs-waiting');
/**
* the media has a readystate of have_enough_data or greater. this means that the
* entire media file can be played without buffering.
*
* @event player#canplaythrough
* @type {eventtarget~event}
*/
this.trigger('canplaythrough');
}
/**
* retrigger the `playing` event that was triggered by the {@link tech}.
*
* @fires player#playing
* @listens tech#playing
* @private
*/
;
_proto.handletechplaying_ = function handletechplaying_() {
this.removeclass('vjs-waiting');
/**
* the media is no longer blocked from playback, and has started playing.
*
* @event player#playing
* @type {eventtarget~event}
*/
this.trigger('playing');
}
/**
* retrigger the `seeking` event that was triggered by the {@link tech}.
*
* @fires player#seeking
* @listens tech#seeking
* @private
*/
;
_proto.handletechseeking_ = function handletechseeking_() {
this.addclass('vjs-seeking');
/**
* fired whenever the player is jumping to a new time
*
* @event player#seeking
* @type {eventtarget~event}
*/
this.trigger('seeking');
}
/**
* retrigger the `seeked` event that was triggered by the {@link tech}.
*
* @fires player#seeked
* @listens tech#seeked
* @private
*/
;
_proto.handletechseeked_ = function handletechseeked_() {
this.removeclass('vjs-seeking');
this.removeclass('vjs-ended');
/**
* fired when the player has finished jumping to a new time
*
* @event player#seeked
* @type {eventtarget~event}
*/
this.trigger('seeked');
}
/**
* retrigger the `firstplay` event that was triggered by the {@link tech}.
*
* @fires player#firstplay
* @listens tech#firstplay
* @deprecated as of 6.0 firstplay event is deprecated.
* as of 6.0 passing the `starttime` option to the player and the firstplay event are deprecated.
* @private
*/
;
_proto.handletechfirstplay_ = function handletechfirstplay_() {
// if the first starttime attribute is specified
// then we will start at the given offset in seconds
if (this.options_.starttime) {
log$1.warn('passing the `starttime` option to the player will be deprecated in 6.0');
this.currenttime(this.options_.starttime);
}
this.addclass('vjs-has-started');
/**
* fired the first time a video is played. not part of the hls spec, and this is
* probably not the best implementation yet, so use sparingly. if you don't have a
* reason to prevent playback, use `myplayer.one('play');` instead.
*
* @event player#firstplay
* @deprecated as of 6.0 firstplay event is deprecated.
* @type {eventtarget~event}
*/
this.trigger('firstplay');
}
/**
* retrigger the `pause` event that was triggered by the {@link tech}.
*
* @fires player#pause
* @listens tech#pause
* @private
*/
;
_proto.handletechpause_ = function handletechpause_() {
this.removeclass('vjs-playing');
this.addclass('vjs-paused');
/**
* fired whenever the media has been paused
*
* @event player#pause
* @type {eventtarget~event}
*/
this.trigger('pause');
}
/**
* retrigger the `ended` event that was triggered by the {@link tech}.
*
* @fires player#ended
* @listens tech#ended
* @private
*/
;
_proto.handletechended_ = function handletechended_() {
this.addclass('vjs-ended');
this.removeclass('vjs-waiting');
if (this.options_.loop) {
this.currenttime(0);
this.play();
} else if (!this.paused()) {
this.pause();
}
/**
* fired when the end of the media resource is reached (currenttime == duration)
*
* @event player#ended
* @type {eventtarget~event}
*/
this.trigger('ended');
}
/**
* fired when the duration of the media resource is first known or changed
*
* @listens tech#durationchange
* @private
*/
;
_proto.handletechdurationchange_ = function handletechdurationchange_() {
this.duration(this.techget_('duration'));
}
/**
* handle a click on the media element to play/pause
*
* @param {eventtarget~event} event
* the event that caused this function to trigger
*
* @listens tech#click
* @private
*/
;
_proto.handletechclick_ = function handletechclick_(event) {
// when controls are disabled a click should not toggle playback because
// the click is considered a control
if (!this.controls_) {
return;
}
if (this.options_ === undefined || this.options_.useractions === undefined || this.options_.useractions.click === undefined || this.options_.useractions.click !== false) {
if (this.options_ !== undefined && this.options_.useractions !== undefined && typeof this.options_.useractions.click === 'function') {
this.options_.useractions.click.call(this, event);
} else if (this.paused()) {
silencepromise(this.play());
} else {
this.pause();
}
}
}
/**
* handle a double-click on the media element to enter/exit fullscreen
*
* @param {eventtarget~event} event
* the event that caused this function to trigger
*
* @listens tech#dblclick
* @private
*/
;
_proto.handletechdoubleclick_ = function handletechdoubleclick_(event) {
if (!this.controls_) {
return;
} // we do not want to toggle fullscreen state
// when double-clicking inside a control bar or a modal
var inallowedels = array.prototype.some.call(this.$$('.vjs-control-bar, .vjs-modal-dialog'), function (el) {
return el.contains(event.target);
});
if (!inallowedels) {
/*
* options.useractions.doubleclick
*
* if `undefined` or `true`, double-click toggles fullscreen if controls are present
* set to `false` to disable double-click handling
* set to a function to substitute an external double-click handler
*/
if (this.options_ === undefined || this.options_.useractions === undefined || this.options_.useractions.doubleclick === undefined || this.options_.useractions.doubleclick !== false) {
if (this.options_ !== undefined && this.options_.useractions !== undefined && typeof this.options_.useractions.doubleclick === 'function') {
this.options_.useractions.doubleclick.call(this, event);
} else if (this.isfullscreen()) {
this.exitfullscreen();
} else {
this.requestfullscreen();
}
}
}
}
/**
* handle a tap on the media element. it will toggle the user
* activity state, which hides and shows the controls.
*
* @listens tech#tap
* @private
*/
;
_proto.handletechtap_ = function handletechtap_() {
this.useractive(!this.useractive());
}
/**
* handle touch to start
*
* @listens tech#touchstart
* @private
*/
;
_proto.handletechtouchstart_ = function handletechtouchstart_() {
this.userwasactive = this.useractive();
}
/**
* handle touch to move
*
* @listens tech#touchmove
* @private
*/
;
_proto.handletechtouchmove_ = function handletechtouchmove_() {
if (this.userwasactive) {
this.reportuseractivity();
}
}
/**
* handle touch to end
*
* @param {eventtarget~event} event
* the touchend event that triggered
* this function
*
* @listens tech#touchend
* @private
*/
;
_proto.handletechtouchend_ = function handletechtouchend_(event) {
// stop the mouse events from also happening
if (event.cancelable) {
event.preventdefault();
}
}
/**
* native click events on the swf aren't triggered on ie11, win8.1rt
* use stageclick events triggered from inside the swf instead
*
* @private
* @listens stageclick
*/
;
_proto.handlestageclick_ = function handlestageclick_() {
this.reportuseractivity();
}
/**
* @private
*/
;
_proto.togglefullscreenclass_ = function togglefullscreenclass_() {
if (this.isfullscreen()) {
this.addclass('vjs-fullscreen');
} else {
this.removeclass('vjs-fullscreen');
}
}
/**
* when the document fschange event triggers it calls this
*/
;
_proto.documentfullscreenchange_ = function documentfullscreenchange_(e) {
var targetplayer = e.target.player; // if another player was fullscreen
// do a null check for targetplayer because older firefox's would put document as e.target
if (targetplayer && targetplayer !== this) {
return;
}
var el = this.el();
var isfs = global_document__webpack_imported_module_1___default.a[this.fsapi_.fullscreenelement] === el;
if (!isfs && el.matches) {
isfs = el.matches(':' + this.fsapi_.fullscreen);
} else if (!isfs && el.msmatchesselector) {
isfs = el.msmatchesselector(':' + this.fsapi_.fullscreen);
}
this.isfullscreen(isfs);
}
/**
* handle tech fullscreen change
*
* @param {eventtarget~event} event
* the fullscreenchange event that triggered this function
*
* @param {object} data
* the data that was sent with the event
*
* @private
* @listens tech#fullscreenchange
* @fires player#fullscreenchange
*/
;
_proto.handletechfullscreenchange_ = function handletechfullscreenchange_(event, data) {
var _this9 = this;
if (data) {
if (data.nativeiosfullscreen) {
this.addclass('vjs-ios-native-fs');
this.tech_.one('webkitendfullscreen', function () {
_this9.removeclass('vjs-ios-native-fs');
});
}
this.isfullscreen(data.isfullscreen);
}
};
_proto.handletechfullscreenerror_ = function handletechfullscreenerror_(event, err) {
this.trigger('fullscreenerror', err);
}
/**
* @private
*/
;
_proto.togglepictureinpictureclass_ = function togglepictureinpictureclass_() {
if (this.isinpictureinpicture()) {
this.addclass('vjs-picture-in-picture');
} else {
this.removeclass('vjs-picture-in-picture');
}
}
/**
* handle tech enter picture-in-picture.
*
* @param {eventtarget~event} event
* the enterpictureinpicture event that triggered this function
*
* @private
* @listens tech#enterpictureinpicture
*/
;
_proto.handletechenterpictureinpicture_ = function handletechenterpictureinpicture_(event) {
this.isinpictureinpicture(true);
}
/**
* handle tech leave picture-in-picture.
*
* @param {eventtarget~event} event
* the leavepictureinpicture event that triggered this function
*
* @private
* @listens tech#leavepictureinpicture
*/
;
_proto.handletechleavepictureinpicture_ = function handletechleavepictureinpicture_(event) {
this.isinpictureinpicture(false);
}
/**
* fires when an error occurred during the loading of an audio/video.
*
* @private
* @listens tech#error
*/
;
_proto.handletecherror_ = function handletecherror_() {
var error = this.tech_.error();
this.error(error);
}
/**
* retrigger the `textdata` event that was triggered by the {@link tech}.
*
* @fires player#textdata
* @listens tech#textdata
* @private
*/
;
_proto.handletechtextdata_ = function handletechtextdata_() {
var data = null;
if (arguments.length > 1) {
data = arguments[1];
}
/**
* fires when we get a textdata event from tech
*
* @event player#textdata
* @type {eventtarget~event}
*/
this.trigger('textdata', data);
}
/**
* get object for cached values.
*
* @return {object}
* get the current object cache
*/
;
_proto.getcache = function getcache() {
return this.cache_;
}
/**
* resets the internal cache object.
*
* using this function outside the player constructor or reset method may
* have unintended side-effects.
*
* @private
*/
;
_proto.resetcache_ = function resetcache_() {
this.cache_ = {
// right now, the currenttime is not _really_ cached because it is always
// retrieved from the tech (see: currenttime). however, for completeness,
// we set it to zero here to ensure that if we do start actually caching
// it, we reset it along with everything else.
currenttime: 0,
inittime: 0,
inactivitytimeout: this.options_.inactivitytimeout,
duration: nan,
lastvolume: 1,
lastplaybackrate: this.defaultplaybackrate(),
media: null,
src: '',
source: {},
sources: [],
playbackrates: [],
volume: 1
};
}
/**
* pass values to the playback tech
*
* @param {string} [method]
* the method to call
*
* @param {object} arg
* the argument to pass
*
* @private
*/
;
_proto.techcall_ = function techcall_(method, arg) {
// if it's not ready yet, call method when it is
this.ready(function () {
if (method in allowedsetters) {
return set(this.middleware_, this.tech_, method, arg);
} else if (method in allowedmediators) {
return mediate(this.middleware_, this.tech_, method, arg);
}
try {
if (this.tech_) {
this.tech_[method](arg);
}
} catch (e) {
log$1(e);
throw e;
}
}, true);
}
/**
* get calls can't wait for the tech, and sometimes don't need to.
*
* @param {string} method
* tech method
*
* @return {function|undefined}
* the method or undefined
*
* @private
*/
;
_proto.techget_ = function techget_(method) {
if (!this.tech_ || !this.tech_.isready_) {
return;
}
if (method in allowedgetters) {
return get(this.middleware_, this.tech_, method);
} else if (method in allowedmediators) {
return mediate(this.middleware_, this.tech_, method);
} // flash likes to die and reload when you hide or reposition it.
// in these cases the object methods go away and we get errors.
// todo: is this needed for techs other than flash?
// when that happens we'll catch the errors and inform tech that it's not ready any more.
try {
return this.tech_[method]();
} catch (e) {
// when building additional tech libs, an expected method may not be defined yet
if (this.tech_[method] === undefined) {
log$1("video.js: " + method + " method not defined for " + this.techname_ + " playback technology.", e);
throw e;
} // when a method isn't available on the object it throws a typeerror
if (e.name === 'typeerror') {
log$1("video.js: " + method + " unavailable on " + this.techname_ + " playback technology element.", e);
this.tech_.isready_ = false;
throw e;
} // if error unknown, just log and throw
log$1(e);
throw e;
}
}
/**
* attempt to begin playback at the first opportunity.
*
* @return {promise|undefined}
* returns a promise if the browser supports promises (or one
* was passed in as an option). this promise will be resolved on
* the return value of play. if this is undefined it will fulfill the
* promise chain otherwise the promise chain will be fulfilled when
* the promise from play is fulfilled.
*/
;
_proto.play = function play() {
var _this10 = this;
var promiseclass = this.options_.promise || global_window__webpack_imported_module_0___default.a.promise;
if (promiseclass) {
return new promiseclass(function (resolve) {
_this10.play_(resolve);
});
}
return this.play_();
}
/**
* the actual logic for play, takes a callback that will be resolved on the
* return value of play. this allows us to resolve to the play promise if there
* is one on modern browsers.
*
* @private
* @param {function} [callback]
* the callback that should be called when the techs play is actually called
*/
;
_proto.play_ = function play_(callback) {
var _this11 = this;
if (callback === void 0) {
callback = silencepromise;
}
this.playcallbacks_.push(callback);
var issrcready = boolean(!this.changingsrc_ && (this.src() || this.currentsrc()));
var issafariorios = boolean(is_any_safari || is_ios); // treat calls to play_ somewhat like the `one` event function
if (this.waittoplay_) {
this.off(['ready', 'loadstart'], this.waittoplay_);
this.waittoplay_ = null;
} // if the player/tech is not ready or the src itself is not ready
// queue up a call to play on `ready` or `loadstart`
if (!this.isready_ || !issrcready) {
this.waittoplay_ = function (e) {
_this11.play_();
};
this.one(['ready', 'loadstart'], this.waittoplay_); // if we are in safari, there is a high chance that loadstart will trigger after the gesture timeperiod
// in that case, we need to prime the video element by calling load so it'll be ready in time
if (!issrcready && issafariorios) {
this.load();
}
return;
} // if the player/tech is ready and we have a source, we can attempt playback.
var val = this.techget_('play'); // for native playback, reset the progress bar if we get a play call from a replay.
var isnativereplay = issafariorios && this.hasclass('vjs-ended');
if (isnativereplay) {
this.resetprogressbar_();
} // play was terminated if the returned value is null
if (val === null) {
this.runplayterminatedqueue_();
} else {
this.runplaycallbacks_(val);
}
}
/**
* these functions will be run when if play is terminated. if play
* runplaycallbacks_ is run these function will not be run. this allows us
* to differenciate between a terminated play and an actual call to play.
*/
;
_proto.runplayterminatedqueue_ = function runplayterminatedqueue_() {
var queue = this.playterminatedqueue_.slice(0);
this.playterminatedqueue_ = [];
queue.foreach(function (q) {
q();
});
}
/**
* when a callback to play is delayed we have to run these
* callbacks when play is actually called on the tech. this function
* runs the callbacks that were delayed and accepts the return value
* from the tech.
*
* @param {undefined|promise} val
* the return value from the tech.
*/
;
_proto.runplaycallbacks_ = function runplaycallbacks_(val) {
var callbacks = this.playcallbacks_.slice(0);
this.playcallbacks_ = []; // clear play terminatedqueue since we finished a real play
this.playterminatedqueue_ = [];
callbacks.foreach(function (cb) {
cb(val);
});
}
/**
* pause the video playback
*
* @return {player}
* a reference to the player object this function was called on
*/
;
_proto.pause = function pause() {
this.techcall_('pause');
}
/**
* check if the player is paused or has yet to play
*
* @return {boolean}
* - false: if the media is currently playing
* - true: if media is not currently playing
*/
;
_proto.paused = function paused() {
// the initial state of paused should be true (in safari it's actually false)
return this.techget_('paused') === false ? false : true;
}
/**
* get a timerange object representing the current ranges of time that the user
* has played.
*
* @return {timerange}
* a time range object that represents all the increments of time that have
* been played.
*/
;
_proto.played = function played() {
return this.techget_('played') || createtimeranges(0, 0);
}
/**
* returns whether or not the user is "scrubbing". scrubbing is
* when the user has clicked the progress bar handle and is
* dragging it along the progress bar.
*
* @param {boolean} [isscrubbing]
* whether the user is or is not scrubbing
*
* @return {boolean}
* the value of scrubbing when getting
*/
;
_proto.scrubbing = function scrubbing(isscrubbing) {
if (typeof isscrubbing === 'undefined') {
return this.scrubbing_;
}
this.scrubbing_ = !!isscrubbing;
this.techcall_('setscrubbing', this.scrubbing_);
if (isscrubbing) {
this.addclass('vjs-scrubbing');
} else {
this.removeclass('vjs-scrubbing');
}
}
/**
* get or set the current time (in seconds)
*
* @param {number|string} [seconds]
* the time to seek to in seconds
*
* @return {number}
* - the current time in seconds when getting
*/
;
_proto.currenttime = function currenttime(seconds) {
if (typeof seconds !== 'undefined') {
if (seconds < 0) {
seconds = 0;
}
if (!this.isready_ || this.changingsrc_ || !this.tech_ || !this.tech_.isready_) {
this.cache_.inittime = seconds;
this.off('canplay', this.boundapplyinittime_);
this.one('canplay', this.boundapplyinittime_);
return;
}
this.techcall_('setcurrenttime', seconds);
this.cache_.inittime = 0;
return;
} // cache last currenttime and return. default to 0 seconds
//
// caching the currenttime is meant to prevent a massive amount of reads on the tech's
// currenttime when scrubbing, but may not provide much performance benefit afterall.
// should be tested. also something has to read the actual current time or the cache will
// never get updated.
this.cache_.currenttime = this.techget_('currenttime') || 0;
return this.cache_.currenttime;
}
/**
* apply the value of inittime stored in cache as currenttime.
*
* @private
*/
;
_proto.applyinittime_ = function applyinittime_() {
this.currenttime(this.cache_.inittime);
}
/**
* normally gets the length in time of the video in seconds;
* in all but the rarest use cases an argument will not be passed to the method
*
* > **note**: the video must have started loading before the duration can be
* known, and depending on preload behaviour may not be known until the video starts
* playing.
*
* @fires player#durationchange
*
* @param {number} [seconds]
* the duration of the video to set in seconds
*
* @return {number}
* - the duration of the video in seconds when getting
*/
;
_proto.duration = function duration(seconds) {
if (seconds === undefined) {
// return nan if the duration is not known
return this.cache_.duration !== undefined ? this.cache_.duration : nan;
}
seconds = parsefloat(seconds); // standardize on infinity for signaling video is live
if (seconds < 0) {
seconds = infinity;
}
if (seconds !== this.cache_.duration) {
// cache the last set value for optimized scrubbing (esp. flash)
// todo: required for techs other than flash?
this.cache_.duration = seconds;
if (seconds === infinity) {
this.addclass('vjs-live');
} else {
this.removeclass('vjs-live');
}
if (!isnan(seconds)) {
// do not fire durationchange unless the duration value is known.
// @see [spec]{@link https://www.w3.org/tr/2011/wd-html5-20110113/video.html#media-element-load-algorithm}
/**
* @event player#durationchange
* @type {eventtarget~event}
*/
this.trigger('durationchange');
}
}
}
/**
* calculates how much time is left in the video. not part
* of the native video api.
*
* @return {number}
* the time remaining in seconds
*/
;
_proto.remainingtime = function remainingtime() {
return this.duration() - this.currenttime();
}
/**
* a remaining time function that is intented to be used when
* the time is to be displayed directly to the user.
*
* @return {number}
* the rounded time remaining in seconds
*/
;
_proto.remainingtimedisplay = function remainingtimedisplay() {
return math.floor(this.duration()) - math.floor(this.currenttime());
} //
// kind of like an array of portions of the video that have been downloaded.
/**
* get a timerange object with an array of the times of the video
* that have been downloaded. if you just want the percent of the
* video that's been downloaded, use bufferedpercent.
*
* @see [buffered spec]{@link http://dev.w3.org/html5/spec/video.html#dom-media-buffered}
*
* @return {timerange}
* a mock timerange object (following html spec)
*/
;
_proto.buffered = function buffered() {
var buffered = this.techget_('buffered');
if (!buffered || !buffered.length) {
buffered = createtimeranges(0, 0);
}
return buffered;
}
/**
* get the percent (as a decimal) of the video that's been downloaded.
* this method is not a part of the native html video api.
*
* @return {number}
* a decimal between 0 and 1 representing the percent
* that is buffered 0 being 0% and 1 being 100%
*/
;
_proto.bufferedpercent = function bufferedpercent$1() {
return bufferedpercent(this.buffered(), this.duration());
}
/**
* get the ending time of the last buffered time range
* this is used in the progress bar to encapsulate all time ranges.
*
* @return {number}
* the end of the last buffered time range
*/
;
_proto.bufferedend = function bufferedend() {
var buffered = this.buffered();
var duration = this.duration();
var end = buffered.end(buffered.length - 1);
if (end > duration) {
end = duration;
}
return end;
}
/**
* get or set the current volume of the media
*
* @param {number} [percentasdecimal]
* the new volume as a decimal percent:
* - 0 is muted/0%/off
* - 1.0 is 100%/full
* - 0.5 is half volume or 50%
*
* @return {number}
* the current volume as a percent when getting
*/
;
_proto.volume = function volume(percentasdecimal) {
var vol;
if (percentasdecimal !== undefined) {
// force value to between 0 and 1
vol = math.max(0, math.min(1, parsefloat(percentasdecimal)));
this.cache_.volume = vol;
this.techcall_('setvolume', vol);
if (vol > 0) {
this.lastvolume_(vol);
}
return;
} // default to 1 when returning current volume.
vol = parsefloat(this.techget_('volume'));
return isnan(vol) ? 1 : vol;
}
/**
* get the current muted state, or turn mute on or off
*
* @param {boolean} [muted]
* - true to mute
* - false to unmute
*
* @return {boolean}
* - true if mute is on and getting
* - false if mute is off and getting
*/
;
_proto.muted = function muted(_muted) {
if (_muted !== undefined) {
this.techcall_('setmuted', _muted);
return;
}
return this.techget_('muted') || false;
}
/**
* get the current defaultmuted state, or turn defaultmuted on or off. defaultmuted
* indicates the state of muted on initial playback.
*
* ```js
* var myplayer = videojs('some-player-id');
*
* myplayer.src("http://www.example.com/path/to/video.mp4");
*
* // get, should be false
* console.log(myplayer.defaultmuted());
* // set to true
* myplayer.defaultmuted(true);
* // get should be true
* console.log(myplayer.defaultmuted());
* ```
*
* @param {boolean} [defaultmuted]
* - true to mute
* - false to unmute
*
* @return {boolean|player}
* - true if defaultmuted is on and getting
* - false if defaultmuted is off and getting
* - a reference to the current player when setting
*/
;
_proto.defaultmuted = function defaultmuted(_defaultmuted) {
if (_defaultmuted !== undefined) {
return this.techcall_('setdefaultmuted', _defaultmuted);
}
return this.techget_('defaultmuted') || false;
}
/**
* get the last volume, or set it
*
* @param {number} [percentasdecimal]
* the new last volume as a decimal percent:
* - 0 is muted/0%/off
* - 1.0 is 100%/full
* - 0.5 is half volume or 50%
*
* @return {number}
* the current value of lastvolume as a percent when getting
*
* @private
*/
;
_proto.lastvolume_ = function lastvolume_(percentasdecimal) {
if (percentasdecimal !== undefined && percentasdecimal !== 0) {
this.cache_.lastvolume = percentasdecimal;
return;
}
return this.cache_.lastvolume;
}
/**
* check if current tech can support native fullscreen
* (e.g. with built in controls like ios)
*
* @return {boolean}
* if native fullscreen is supported
*/
;
_proto.supportsfullscreen = function supportsfullscreen() {
return this.techget_('supportsfullscreen') || false;
}
/**
* check if the player is in fullscreen mode or tell the player that it
* is or is not in fullscreen mode.
*
* > note: as of the latest html5 spec, isfullscreen is no longer an official
* property and instead document.fullscreenelement is used. but isfullscreen is
* still a valuable property for internal player workings.
*
* @param {boolean} [isfs]
* set the players current fullscreen state
*
* @return {boolean}
* - true if fullscreen is on and getting
* - false if fullscreen is off and getting
*/
;
_proto.isfullscreen = function isfullscreen(isfs) {
if (isfs !== undefined) {
var oldvalue = this.isfullscreen_;
this.isfullscreen_ = boolean(isfs); // if we changed fullscreen state and we're in prefixed mode, trigger fullscreenchange
// this is the only place where we trigger fullscreenchange events for older browsers
// fullwindow mode is treated as a prefixed event and will get a fullscreenchange event as well
if (this.isfullscreen_ !== oldvalue && this.fsapi_.prefixed) {
/**
* @event player#fullscreenchange
* @type {eventtarget~event}
*/
this.trigger('fullscreenchange');
}
this.togglefullscreenclass_();
return;
}
return this.isfullscreen_;
}
/**
* increase the size of the video to full screen
* in some browsers, full screen is not supported natively, so it enters
* "full window mode", where the video fills the browser window.
* in browsers and devices that support native full screen, sometimes the
* browser's default controls will be shown, and not the video.js custom skin.
* this includes most mobile devices (ios, android) and older versions of
* safari.
*
* @param {object} [fullscreenoptions]
* override the player fullscreen options
*
* @fires player#fullscreenchange
*/
;
_proto.requestfullscreen = function requestfullscreen(fullscreenoptions) {
var promiseclass = this.options_.promise || global_window__webpack_imported_module_0___default.a.promise;
if (promiseclass) {
var self = this;
return new promiseclass(function (resolve, reject) {
function offhandler() {
self.off('fullscreenerror', errorhandler);
self.off('fullscreenchange', changehandler);
}
function changehandler() {
offhandler();
resolve();
}
function errorhandler(e, err) {
offhandler();
reject(err);
}
self.one('fullscreenchange', changehandler);
self.one('fullscreenerror', errorhandler);
var promise = self.requestfullscreenhelper_(fullscreenoptions);
if (promise) {
promise.then(offhandler, offhandler);
promise.then(resolve, reject);
}
});
}
return this.requestfullscreenhelper_();
};
_proto.requestfullscreenhelper_ = function requestfullscreenhelper_(fullscreenoptions) {
var _this12 = this;
var fsoptions; // only pass fullscreen options to requestfullscreen in spec-compliant browsers.
// use defaults or player configured option unless passed directly to this method.
if (!this.fsapi_.prefixed) {
fsoptions = this.options_.fullscreen && this.options_.fullscreen.options || {};
if (fullscreenoptions !== undefined) {
fsoptions = fullscreenoptions;
}
} // this method works as follows:
// 1. if a fullscreen api is available, use it
// 1. call requestfullscreen with potential options
// 2. if we got a promise from above, use it to update isfullscreen()
// 2. otherwise, if the tech supports fullscreen, call `enterfullscreen` on it.
// this is particularly used for iphone, older ipads, and non-safari browser on ios.
// 3. otherwise, use "fullwindow" mode
if (this.fsapi_.requestfullscreen) {
var promise = this.el_[this.fsapi_.requestfullscreen](fsoptions);
if (promise) {
promise.then(function () {
return _this12.isfullscreen(true);
}, function () {
return _this12.isfullscreen(false);
});
}
return promise;
} else if (this.tech_.supportsfullscreen() && !this.options_.preferfullwindow === true) {
// we can't take the video.js controls fullscreen but we can go fullscreen
// with native controls
this.techcall_('enterfullscreen');
} else {
// fullscreen isn't supported so we'll just stretch the video element to
// fill the viewport
this.enterfullwindow();
}
}
/**
* return the video to its normal size after having been in full screen mode
*
* @fires player#fullscreenchange
*/
;
_proto.exitfullscreen = function exitfullscreen() {
var promiseclass = this.options_.promise || global_window__webpack_imported_module_0___default.a.promise;
if (promiseclass) {
var self = this;
return new promiseclass(function (resolve, reject) {
function offhandler() {
self.off('fullscreenerror', errorhandler);
self.off('fullscreenchange', changehandler);
}
function changehandler() {
offhandler();
resolve();
}
function errorhandler(e, err) {
offhandler();
reject(err);
}
self.one('fullscreenchange', changehandler);
self.one('fullscreenerror', errorhandler);
var promise = self.exitfullscreenhelper_();
if (promise) {
promise.then(offhandler, offhandler); // map the promise to our resolve/reject methods
promise.then(resolve, reject);
}
});
}
return this.exitfullscreenhelper_();
};
_proto.exitfullscreenhelper_ = function exitfullscreenhelper_() {
var _this13 = this;
if (this.fsapi_.requestfullscreen) {
var promise = global_document__webpack_imported_module_1___default.a[this.fsapi_.exitfullscreen]();
if (promise) {
// we're splitting the promise here, so, we want to catch the
// potential error so that this chain doesn't have unhandled errors
silencepromise(promise.then(function () {
return _this13.isfullscreen(false);
}));
}
return promise;
} else if (this.tech_.supportsfullscreen() && !this.options_.preferfullwindow === true) {
this.techcall_('exitfullscreen');
} else {
this.exitfullwindow();
}
}
/**
* when fullscreen isn't supported we can stretch the
* video container to as wide as the browser will let us.
*
* @fires player#enterfullwindow
*/
;
_proto.enterfullwindow = function enterfullwindow() {
this.isfullscreen(true);
this.isfullwindow = true; // storing original doc overflow value to return to when fullscreen is off
this.docorigoverflow = global_document__webpack_imported_module_1___default.a.documentelement.style.overflow; // add listener for esc key to exit fullscreen
on(global_document__webpack_imported_module_1___default.a, 'keydown', this.boundfullwindowonesckey_); // hide any scroll bars
global_document__webpack_imported_module_1___default.a.documentelement.style.overflow = 'hidden'; // apply fullscreen styles
addclass(global_document__webpack_imported_module_1___default.a.body, 'vjs-full-window');
/**
* @event player#enterfullwindow
* @type {eventtarget~event}
*/
this.trigger('enterfullwindow');
}
/**
* check for call to either exit full window or
* full screen on esc key
*
* @param {string} event
* event to check for key press
*/
;
_proto.fullwindowonesckey = function fullwindowonesckey(event) {
if (keycode__webpack_imported_module_3___default.a.iseventkey(event, 'esc')) {
if (this.isfullscreen() === true) {
if (!this.isfullwindow) {
this.exitfullscreen();
} else {
this.exitfullwindow();
}
}
}
}
/**
* exit full window
*
* @fires player#exitfullwindow
*/
;
_proto.exitfullwindow = function exitfullwindow() {
this.isfullscreen(false);
this.isfullwindow = false;
off(global_document__webpack_imported_module_1___default.a, 'keydown', this.boundfullwindowonesckey_); // unhide scroll bars.
global_document__webpack_imported_module_1___default.a.documentelement.style.overflow = this.docorigoverflow; // remove fullscreen styles
removeclass(global_document__webpack_imported_module_1___default.a.body, 'vjs-full-window'); // resize the box, controller, and poster to original sizes
// this.positionall();
/**
* @event player#exitfullwindow
* @type {eventtarget~event}
*/
this.trigger('exitfullwindow');
}
/**
* disable picture-in-picture mode.
*
* @param {boolean} value
* - true will disable picture-in-picture mode
* - false will enable picture-in-picture mode
*/
;
_proto.disablepictureinpicture = function disablepictureinpicture(value) {
if (value === undefined) {
return this.techget_('disablepictureinpicture');
}
this.techcall_('setdisablepictureinpicture', value);
this.options_.disablepictureinpicture = value;
this.trigger('disablepictureinpicturechanged');
}
/**
* check if the player is in picture-in-picture mode or tell the player that it
* is or is not in picture-in-picture mode.
*
* @param {boolean} [ispip]
* set the players current picture-in-picture state
*
* @return {boolean}
* - true if picture-in-picture is on and getting
* - false if picture-in-picture is off and getting
*/
;
_proto.isinpictureinpicture = function isinpictureinpicture(ispip) {
if (ispip !== undefined) {
this.isinpictureinpicture_ = !!ispip;
this.togglepictureinpictureclass_();
return;
}
return !!this.isinpictureinpicture_;
}
/**
* create a floating video window always on top of other windows so that users may
* continue consuming media while they interact with other content sites, or
* applications on their device.
*
* @see [spec]{@link https://wicg.github.io/picture-in-picture}
*
* @fires player#enterpictureinpicture
*
* @return {promise}
* a promise with a picture-in-picture window.
*/
;
_proto.requestpictureinpicture = function requestpictureinpicture() {
if ('pictureinpictureenabled' in global_document__webpack_imported_module_1___default.a && this.disablepictureinpicture() === false) {
/**
* this event fires when the player enters picture in picture mode
*
* @event player#enterpictureinpicture
* @type {eventtarget~event}
*/
return this.techget_('requestpictureinpicture');
}
}
/**
* exit picture-in-picture mode.
*
* @see [spec]{@link https://wicg.github.io/picture-in-picture}
*
* @fires player#leavepictureinpicture
*
* @return {promise}
* a promise.
*/
;
_proto.exitpictureinpicture = function exitpictureinpicture() {
if ('pictureinpictureenabled' in global_document__webpack_imported_module_1___default.a) {
/**
* this event fires when the player leaves picture in picture mode
*
* @event player#leavepictureinpicture
* @type {eventtarget~event}
*/
return global_document__webpack_imported_module_1___default.a.exitpictureinpicture();
}
}
/**
* called when this player has focus and a key gets pressed down, or when
* any component of this player receives a key press that it doesn't handle.
* this allows player-wide hotkeys (either as defined below, or optionally
* by an external function).
*
* @param {eventtarget~event} event
* the `keydown` event that caused this function to be called.
*
* @listens keydown
*/
;
_proto.handlekeydown = function handlekeydown(event) {
var useractions = this.options_.useractions; // bail out if hotkeys are not configured.
if (!useractions || !useractions.hotkeys) {
return;
} // function that determines whether or not to exclude an element from
// hotkeys handling.
var excludeelement = function excludeelement(el) {
var tagname = el.tagname.tolowercase(); // the first and easiest test is for `contenteditable` elements.
if (el.iscontenteditable) {
return true;
} // inputs matching these types will still trigger hotkey handling as
// they are not text inputs.
var allowedinputtypes = ['button', 'checkbox', 'hidden', 'radio', 'reset', 'submit'];
if (tagname === 'input') {
return allowedinputtypes.indexof(el.type) === -1;
} // the final test is by tag name. these tags will be excluded entirely.
var excludedtags = ['textarea'];
return excludedtags.indexof(tagname) !== -1;
}; // bail out if the user is focused on an interactive form element.
if (excludeelement(this.el_.ownerdocument.activeelement)) {
return;
}
if (typeof useractions.hotkeys === 'function') {
useractions.hotkeys.call(this, event);
} else {
this.handlehotkeys(event);
}
}
/**
* called when this player receives a hotkey keydown event.
* supported player-wide hotkeys are:
*
* f - toggle fullscreen
* m - toggle mute
* k or space - toggle play/pause
*
* @param {eventtarget~event} event
* the `keydown` event that caused this function to be called.
*/
;
_proto.handlehotkeys = function handlehotkeys(event) {
var hotkeys = this.options_.useractions ? this.options_.useractions.hotkeys : {}; // set fullscreenkey, mutekey, playpausekey from `hotkeys`, use defaults if not set
var _hotkeys$fullscreenke = hotkeys.fullscreenkey,
fullscreenkey = _hotkeys$fullscreenke === void 0 ? function (keydownevent) {
return keycode__webpack_imported_module_3___default.a.iseventkey(keydownevent, 'f');
} : _hotkeys$fullscreenke,
_hotkeys$mutekey = hotkeys.mutekey,
mutekey = _hotkeys$mutekey === void 0 ? function (keydownevent) {
return keycode__webpack_imported_module_3___default.a.iseventkey(keydownevent, 'm');
} : _hotkeys$mutekey,
_hotkeys$playpausekey = hotkeys.playpausekey,
playpausekey = _hotkeys$playpausekey === void 0 ? function (keydownevent) {
return keycode__webpack_imported_module_3___default.a.iseventkey(keydownevent, 'k') || keycode__webpack_imported_module_3___default.a.iseventkey(keydownevent, 'space');
} : _hotkeys$playpausekey;
if (fullscreenkey.call(this, event)) {
event.preventdefault();
event.stoppropagation();
var fstoggle = component$1.getcomponent('fullscreentoggle');
if (global_document__webpack_imported_module_1___default.a[this.fsapi_.fullscreenenabled] !== false) {
fstoggle.prototype.handleclick.call(this, event);
}
} else if (mutekey.call(this, event)) {
event.preventdefault();
event.stoppropagation();
var mutetoggle = component$1.getcomponent('mutetoggle');
mutetoggle.prototype.handleclick.call(this, event);
} else if (playpausekey.call(this, event)) {
event.preventdefault();
event.stoppropagation();
var playtoggle = component$1.getcomponent('playtoggle');
playtoggle.prototype.handleclick.call(this, event);
}
}
/**
* check whether the player can play a given mimetype
*
* @see https://www.w3.org/tr/2011/wd-html5-20110113/video.html#dom-navigator-canplaytype
*
* @param {string} type
* the mimetype to check
*
* @return {string}
* 'probably', 'maybe', or '' (empty string)
*/
;
_proto.canplaytype = function canplaytype(type) {
var can; // loop through each playback technology in the options order
for (var i = 0, j = this.options_.techorder; i < j.length; i++) {
var techname = j[i];
var tech = tech.gettech(techname); // support old behavior of techs being registered as components.
// remove once that deprecated behavior is removed.
if (!tech) {
tech = component$1.getcomponent(techname);
} // check if the current tech is defined before continuing
if (!tech) {
log$1.error("the \"" + techname + "\" tech is undefined. skipped browser support check for that tech.");
continue;
} // check if the browser supports this technology
if (tech.issupported()) {
can = tech.canplaytype(type);
if (can) {
return can;
}
}
}
return '';
}
/**
* select source based on tech-order or source-order
* uses source-order selection if `options.sourceorder` is truthy. otherwise,
* defaults to tech-order selection
*
* @param {array} sources
* the sources for a media asset
*
* @return {object|boolean}
* object of source and tech order or false
*/
;
_proto.selectsource = function selectsource(sources) {
var _this14 = this;
// get only the techs specified in `techorder` that exist and are supported by the
// current platform
var techs = this.options_.techorder.map(function (techname) {
return [techname, tech.gettech(techname)];
}).filter(function (_ref) {
var techname = _ref[0],
tech = _ref[1];
// check if the current tech is defined before continuing
if (tech) {
// check if the browser supports this technology
return tech.issupported();
}
log$1.error("the \"" + techname + "\" tech is undefined. skipped browser support check for that tech.");
return false;
}); // iterate over each `innerarray` element once per `outerarray` element and execute
// `tester` with both. if `tester` returns a non-falsy value, exit early and return
// that value.
var findfirstpassingtechsourcepair = function findfirstpassingtechsourcepair(outerarray, innerarray, tester) {
var found;
outerarray.some(function (outerchoice) {
return innerarray.some(function (innerchoice) {
found = tester(outerchoice, innerchoice);
if (found) {
return true;
}
});
});
return found;
};
var foundsourceandtech;
var flip = function flip(fn) {
return function (a, b) {
return fn(b, a);
};
};
var finder = function finder(_ref2, source) {
var techname = _ref2[0],
tech = _ref2[1];
if (tech.canplaysource(source, _this14.options_[techname.tolowercase()])) {
return {
source: source,
tech: techname
};
}
}; // depending on the truthiness of `options.sourceorder`, we swap the order of techs and sources
// to select from them based on their priority.
if (this.options_.sourceorder) {
// source-first ordering
foundsourceandtech = findfirstpassingtechsourcepair(sources, techs, flip(finder));
} else {
// tech-first ordering
foundsourceandtech = findfirstpassingtechsourcepair(techs, sources, finder);
}
return foundsourceandtech || false;
}
/**
* executes source setting and getting logic
*
* @param {tech~sourceobject|tech~sourceobject[]|string} [source]
* a sourceobject, an array of sourceobjects, or a string referencing
* a url to a media source. it is _highly recommended_ that an object
* or array of objects is used here, so that source selection
* algorithms can take the `type` into account.
*
* if not provided, this method acts as a getter.
* @param {boolean} isretry
* indicates whether this is being called internally as a result of a retry
*
* @return {string|undefined}
* if the `source` argument is missing, returns the current source
* url. otherwise, returns nothing/undefined.
*/
;
_proto.handlesrc_ = function handlesrc_(source, isretry) {
var _this15 = this;
// getter usage
if (typeof source === 'undefined') {
return this.cache_.src || '';
} // reset retry behavior for new source
if (this.resetretryonerror_) {
this.resetretryonerror_();
} // filter out invalid sources and turn our source into
// an array of source objects
var sources = filtersource(source); // if a source was passed in then it is invalid because
// it was filtered to a zero length array. so we have to
// show an error
if (!sources.length) {
this.settimeout(function () {
this.error({
code: 4,
message: this.options_.notsupportedmessage
});
}, 0);
return;
} // initial sources
this.changingsrc_ = true; // only update the cached source list if we are not retrying a new source after error,
// since in that case we want to include the failed source(s) in the cache
if (!isretry) {
this.cache_.sources = sources;
}
this.updatesourcecaches_(sources[0]); // middlewaresource is the source after it has been changed by middleware
setsource(this, sources[0], function (middlewaresource, mws) {
_this15.middleware_ = mws; // since sourceset is async we have to update the cache again after we select a source since
// the source that is selected could be out of order from the cache update above this callback.
if (!isretry) {
_this15.cache_.sources = sources;
}
_this15.updatesourcecaches_(middlewaresource);
var err = _this15.src_(middlewaresource);
if (err) {
if (sources.length > 1) {
return _this15.handlesrc_(sources.slice(1));
}
_this15.changingsrc_ = false; // we need to wrap this in a timeout to give folks a chance to add error event handlers
_this15.settimeout(function () {
this.error({
code: 4,
message: this.options_.notsupportedmessage
});
}, 0); // we could not find an appropriate tech, but let's still notify the delegate that this is it
// this needs a better comment about why this is needed
_this15.triggerready();
return;
}
settech(mws, _this15.tech_);
}); // try another available source if this one fails before playback.
if (this.options_.retryonerror && sources.length > 1) {
var retry = function retry() {
// remove the error modal
_this15.error(null);
_this15.handlesrc_(sources.slice(1), true);
};
var stoplisteningforerrors = function stoplisteningforerrors() {
_this15.off('error', retry);
};
this.one('error', retry);
this.one('playing', stoplisteningforerrors);
this.resetretryonerror_ = function () {
_this15.off('error', retry);
_this15.off('playing', stoplisteningforerrors);
};
}
}
/**
* get or set the video source.
*
* @param {tech~sourceobject|tech~sourceobject[]|string} [source]
* a sourceobject, an array of sourceobjects, or a string referencing
* a url to a media source. it is _highly recommended_ that an object
* or array of objects is used here, so that source selection
* algorithms can take the `type` into account.
*
* if not provided, this method acts as a getter.
*
* @return {string|undefined}
* if the `source` argument is missing, returns the current source
* url. otherwise, returns nothing/undefined.
*/
;
_proto.src = function src(source) {
return this.handlesrc_(source, false);
}
/**
* set the source object on the tech, returns a boolean that indicates whether
* there is a tech that can play the source or not
*
* @param {tech~sourceobject} source
* the source object to set on the tech
*
* @return {boolean}
* - true if there is no tech to playback this source
* - false otherwise
*
* @private
*/
;
_proto.src_ = function src_(source) {
var _this16 = this;
var sourcetech = this.selectsource([source]);
if (!sourcetech) {
return true;
}
if (!titlecaseequals(sourcetech.tech, this.techname_)) {
this.changingsrc_ = true; // load this technology with the chosen source
this.loadtech_(sourcetech.tech, sourcetech.source);
this.tech_.ready(function () {
_this16.changingsrc_ = false;
});
return false;
} // wait until the tech is ready to set the source
// and set it synchronously if possible (#2326)
this.ready(function () {
// the setsource tech method was added with source handlers
// so older techs won't support it
// we need to check the direct prototype for the case where subclasses
// of the tech do not support source handlers
if (this.tech_.constructor.prototype.hasownproperty('setsource')) {
this.techcall_('setsource', source);
} else {
this.techcall_('src', source.src);
}
this.changingsrc_ = false;
}, true);
return false;
}
/**
* begin loading the src data.
*/
;
_proto.load = function load() {
this.techcall_('load');
}
/**
* reset the player. loads the first tech in the techorder,
* removes all the text tracks in the existing `tech`,
* and calls `reset` on the `tech`.
*/
;
_proto.reset = function reset() {
var _this17 = this;
var promiseclass = this.options_.promise || global_window__webpack_imported_module_0___default.a.promise;
if (this.paused() || !promiseclass) {
this.doreset_();
} else {
var playpromise = this.play();
silencepromise(playpromise.then(function () {
return _this17.doreset_();
}));
}
};
_proto.doreset_ = function doreset_() {
if (this.tech_) {
this.tech_.cleartracks('text');
}
this.resetcache_();
this.poster('');
this.loadtech_(this.options_.techorder[0], null);
this.techcall_('reset');
this.resetcontrolbarui_();
if (isevented(this)) {
this.trigger('playerreset');
}
}
/**
* reset control bar's ui by calling sub-methods that reset
* all of control bar's components
*/
;
_proto.resetcontrolbarui_ = function resetcontrolbarui_() {
this.resetprogressbar_();
this.resetplaybackrate_();
this.resetvolumebar_();
}
/**
* reset tech's progress so progress bar is reset in the ui
*/
;
_proto.resetprogressbar_ = function resetprogressbar_() {
this.currenttime(0);
var _ref3 = this.controlbar || {},
durationdisplay = _ref3.durationdisplay,
remainingtimedisplay = _ref3.remainingtimedisplay;
if (durationdisplay) {
durationdisplay.updatecontent();
}
if (remainingtimedisplay) {
remainingtimedisplay.updatecontent();
}
}
/**
* reset playback ratio
*/
;
_proto.resetplaybackrate_ = function resetplaybackrate_() {
this.playbackrate(this.defaultplaybackrate());
this.handletechratechange_();
}
/**
* reset volume bar
*/
;
_proto.resetvolumebar_ = function resetvolumebar_() {
this.volume(1.0);
this.trigger('volumechange');
}
/**
* returns all of the current source objects.
*
* @return {tech~sourceobject[]}
* the current source objects
*/
;
_proto.currentsources = function currentsources() {
var source = this.currentsource();
var sources = []; // assume `{}` or `{ src }`
if (object.keys(source).length !== 0) {
sources.push(source);
}
return this.cache_.sources || sources;
}
/**
* returns the current source object.
*
* @return {tech~sourceobject}
* the current source object
*/
;
_proto.currentsource = function currentsource() {
return this.cache_.source || {};
}
/**
* returns the fully qualified url of the current source value e.g. http://mysite.com/video.mp4
* can be used in conjunction with `currenttype` to assist in rebuilding the current source object.
*
* @return {string}
* the current source
*/
;
_proto.currentsrc = function currentsrc() {
return this.currentsource() && this.currentsource().src || '';
}
/**
* get the current source type e.g. video/mp4
* this can allow you rebuild the current source object so that you could load the same
* source and tech later
*
* @return {string}
* the source mime type
*/
;
_proto.currenttype = function currenttype() {
return this.currentsource() && this.currentsource().type || '';
}
/**
* get or set the preload attribute
*
* @param {boolean} [value]
* - true means that we should preload
* - false means that we should not preload
*
* @return {string}
* the preload attribute value when getting
*/
;
_proto.preload = function preload(value) {
if (value !== undefined) {
this.techcall_('setpreload', value);
this.options_.preload = value;
return;
}
return this.techget_('preload');
}
/**
* get or set the autoplay option. when this is a boolean it will
* modify the attribute on the tech. when this is a string the attribute on
* the tech will be removed and `player` will handle autoplay on loadstarts.
*
* @param {boolean|string} [value]
* - true: autoplay using the browser behavior
* - false: do not autoplay
* - 'play': call play() on every loadstart
* - 'muted': call muted() then play() on every loadstart
* - 'any': call play() on every loadstart. if that fails call muted() then play().
* - *: values other than those listed here will be set `autoplay` to true
*
* @return {boolean|string}
* the current value of autoplay when getting
*/
;
_proto.autoplay = function autoplay(value) {
// getter usage
if (value === undefined) {
return this.options_.autoplay || false;
}
var techautoplay; // if the value is a valid string set it to that, or normalize `true` to 'play', if need be
if (typeof value === 'string' && /(any|play|muted)/.test(value) || value === true && this.options_.normalizeautoplay) {
this.options_.autoplay = value;
this.manualautoplay_(typeof value === 'string' ? value : 'play');
techautoplay = false; // any falsy value sets autoplay to false in the browser,
// lets do the same
} else if (!value) {
this.options_.autoplay = false; // any other value (ie truthy) sets autoplay to true
} else {
this.options_.autoplay = true;
}
techautoplay = typeof techautoplay === 'undefined' ? this.options_.autoplay : techautoplay; // if we don't have a tech then we do not queue up
// a setautoplay call on tech ready. we do this because the
// autoplay option will be passed in the constructor and we
// do not need to set it twice
if (this.tech_) {
this.techcall_('setautoplay', techautoplay);
}
}
/**
* set or unset the playsinline attribute.
* playsinline tells the browser that non-fullscreen playback is preferred.
*
* @param {boolean} [value]
* - true means that we should try to play inline by default
* - false means that we should use the browser's default playback mode,
* which in most cases is inline. ios safari is a notable exception
* and plays fullscreen by default.
*
* @return {string|player}
* - the current value of playsinline
* - the player when setting
*
* @see [spec]{@link https://html.spec.whatwg.org/#attr-video-playsinline}
*/
;
_proto.playsinline = function playsinline(value) {
if (value !== undefined) {
this.techcall_('setplaysinline', value);
this.options_.playsinline = value;
return this;
}
return this.techget_('playsinline');
}
/**
* get or set the loop attribute on the video element.
*
* @param {boolean} [value]
* - true means that we should loop the video
* - false means that we should not loop the video
*
* @return {boolean}
* the current value of loop when getting
*/
;
_proto.loop = function loop(value) {
if (value !== undefined) {
this.techcall_('setloop', value);
this.options_.loop = value;
return;
}
return this.techget_('loop');
}
/**
* get or set the poster image source url
*
* @fires player#posterchange
*
* @param {string} [src]
* poster image source url
*
* @return {string}
* the current value of poster when getting
*/
;
_proto.poster = function poster(src) {
if (src === undefined) {
return this.poster_;
} // the correct way to remove a poster is to set as an empty string
// other falsey values will throw errors
if (!src) {
src = '';
}
if (src === this.poster_) {
return;
} // update the internal poster variable
this.poster_ = src; // update the tech's poster
this.techcall_('setposter', src);
this.isposterfromtech_ = false; // alert components that the poster has been set
/**
* this event fires when the poster image is changed on the player.
*
* @event player#posterchange
* @type {eventtarget~event}
*/
this.trigger('posterchange');
}
/**
* some techs (e.g. youtube) can provide a poster source in an
* asynchronous way. we want the poster component to use this
* poster source so that it covers up the tech's controls.
* (youtube's play button). however we only want to use this
* source if the player user hasn't set a poster through
* the normal apis.
*
* @fires player#posterchange
* @listens tech#posterchange
* @private
*/
;
_proto.handletechposterchange_ = function handletechposterchange_() {
if ((!this.poster_ || this.options_.techcanoverrideposter) && this.tech_ && this.tech_.poster) {
var newposter = this.tech_.poster() || '';
if (newposter !== this.poster_) {
this.poster_ = newposter;
this.isposterfromtech_ = true; // let components know the poster has changed
this.trigger('posterchange');
}
}
}
/**
* get or set whether or not the controls are showing.
*
* @fires player#controlsenabled
*
* @param {boolean} [bool]
* - true to turn controls on
* - false to turn controls off
*
* @return {boolean}
* the current value of controls when getting
*/
;
_proto.controls = function controls(bool) {
if (bool === undefined) {
return !!this.controls_;
}
bool = !!bool; // don't trigger a change event unless it actually changed
if (this.controls_ === bool) {
return;
}
this.controls_ = bool;
if (this.usingnativecontrols()) {
this.techcall_('setcontrols', bool);
}
if (this.controls_) {
this.removeclass('vjs-controls-disabled');
this.addclass('vjs-controls-enabled');
/**
* @event player#controlsenabled
* @type {eventtarget~event}
*/
this.trigger('controlsenabled');
if (!this.usingnativecontrols()) {
this.addtechcontrolslisteners_();
}
} else {
this.removeclass('vjs-controls-enabled');
this.addclass('vjs-controls-disabled');
/**
* @event player#controlsdisabled
* @type {eventtarget~event}
*/
this.trigger('controlsdisabled');
if (!this.usingnativecontrols()) {
this.removetechcontrolslisteners_();
}
}
}
/**
* toggle native controls on/off. native controls are the controls built into
* devices (e.g. default iphone controls) or other techs
* (e.g. vimeo controls)
* **this should only be set by the current tech, because only the tech knows
* if it can support native controls**
*
* @fires player#usingnativecontrols
* @fires player#usingcustomcontrols
*
* @param {boolean} [bool]
* - true to turn native controls on
* - false to turn native controls off
*
* @return {boolean}
* the current value of native controls when getting
*/
;
_proto.usingnativecontrols = function usingnativecontrols(bool) {
if (bool === undefined) {
return !!this.usingnativecontrols_;
}
bool = !!bool; // don't trigger a change event unless it actually changed
if (this.usingnativecontrols_ === bool) {
return;
}
this.usingnativecontrols_ = bool;
if (this.usingnativecontrols_) {
this.addclass('vjs-using-native-controls');
/**
* player is using the native device controls
*
* @event player#usingnativecontrols
* @type {eventtarget~event}
*/
this.trigger('usingnativecontrols');
} else {
this.removeclass('vjs-using-native-controls');
/**
* player is using the custom html controls
*
* @event player#usingcustomcontrols
* @type {eventtarget~event}
*/
this.trigger('usingcustomcontrols');
}
}
/**
* set or get the current mediaerror
*
* @fires player#error
*
* @param {mediaerror|string|number} [err]
* a mediaerror or a string/number to be turned
* into a mediaerror
*
* @return {mediaerror|null}
* the current mediaerror when getting (or null)
*/
;
_proto.error = function error(err) {
var _this18 = this;
if (err === undefined) {
return this.error_ || null;
} // allow hooks to modify error object
hooks('beforeerror').foreach(function (hookfunction) {
var newerr = hookfunction(_this18, err);
if (!(isobject(newerr) && !array.isarray(newerr) || typeof newerr === 'string' || typeof newerr === 'number' || newerr === null)) {
_this18.log.error('please return a value that mediaerror expects in beforeerror hooks');
return;
}
err = newerr;
}); // suppress the first error message for no compatible source until
// user interaction
if (this.options_.suppressnotsupportederror && err && err.code === 4) {
var triggersuppressederror = function triggersuppressederror() {
this.error(err);
};
this.options_.suppressnotsupportederror = false;
this.any(['click', 'touchstart'], triggersuppressederror);
this.one('loadstart', function () {
this.off(['click', 'touchstart'], triggersuppressederror);
});
return;
} // restoring to default
if (err === null) {
this.error_ = err;
this.removeclass('vjs-error');
if (this.errordisplay) {
this.errordisplay.close();
}
return;
}
this.error_ = new mediaerror(err); // add the vjs-error classname to the player
this.addclass('vjs-error'); // log the name of the error type and any message
// ie11 logs "[object object]" and required you to expand message to see error object
log$1.error("(code:" + this.error_.code + " " + mediaerror.errortypes[this.error_.code] + ")", this.error_.message, this.error_);
/**
* @event player#error
* @type {eventtarget~event}
*/
this.trigger('error'); // notify hooks of the per player error
hooks('error').foreach(function (hookfunction) {
return hookfunction(_this18, _this18.error_);
});
return;
}
/**
* report user activity
*
* @param {object} event
* event object
*/
;
_proto.reportuseractivity = function reportuseractivity(event) {
this.useractivity_ = true;
}
/**
* get/set if user is active
*
* @fires player#useractive
* @fires player#userinactive
*
* @param {boolean} [bool]
* - true if the user is active
* - false if the user is inactive
*
* @return {boolean}
* the current value of useractive when getting
*/
;
_proto.useractive = function useractive(bool) {
if (bool === undefined) {
return this.useractive_;
}
bool = !!bool;
if (bool === this.useractive_) {
return;
}
this.useractive_ = bool;
if (this.useractive_) {
this.useractivity_ = true;
this.removeclass('vjs-user-inactive');
this.addclass('vjs-user-active');
/**
* @event player#useractive
* @type {eventtarget~event}
*/
this.trigger('useractive');
return;
} // chrome/safari/ie have bugs where when you change the cursor it can
// trigger a mousemove event. this causes an issue when you're hiding
// the cursor when the user is inactive, and a mousemove signals user
// activity. making it impossible to go into inactive mode. specifically
// this happens in fullscreen when we really need to hide the cursor.
//
// when this gets resolved in all browsers it can be removed
// https://code.google.com/p/chromium/issues/detail?id=103041
if (this.tech_) {
this.tech_.one('mousemove', function (e) {
e.stoppropagation();
e.preventdefault();
});
}
this.useractivity_ = false;
this.removeclass('vjs-user-active');
this.addclass('vjs-user-inactive');
/**
* @event player#userinactive
* @type {eventtarget~event}
*/
this.trigger('userinactive');
}
/**
* listen for user activity based on timeout value
*
* @private
*/
;
_proto.listenforuseractivity_ = function listenforuseractivity_() {
var mouseinprogress;
var lastmovex;
var lastmovey;
var handleactivity = bind(this, this.reportuseractivity);
var handlemousemove = function handlemousemove(e) {
// #1068 - prevent mousemove spamming
// chrome bug: https://code.google.com/p/chromium/issues/detail?id=366970
if (e.screenx !== lastmovex || e.screeny !== lastmovey) {
lastmovex = e.screenx;
lastmovey = e.screeny;
handleactivity();
}
};
var handlemousedown = function handlemousedown() {
handleactivity(); // for as long as the they are touching the device or have their mouse down,
// we consider them active even if they're not moving their finger or mouse.
// so we want to continue to update that they are active
this.clearinterval(mouseinprogress); // setting useractivity=true now and setting the interval to the same time
// as the activitycheck interval (250) should ensure we never miss the
// next activitycheck
mouseinprogress = this.setinterval(handleactivity, 250);
};
var handlemouseupandmouseleave = function handlemouseupandmouseleave(event) {
handleactivity(); // stop the interval that maintains activity if the mouse/touch is down
this.clearinterval(mouseinprogress);
}; // any mouse movement will be considered user activity
this.on('mousedown', handlemousedown);
this.on('mousemove', handlemousemove);
this.on('mouseup', handlemouseupandmouseleave);
this.on('mouseleave', handlemouseupandmouseleave);
var controlbar = this.getchild('controlbar'); // fixes bug on android & ios where when tapping progressbar (when control bar is displayed)
// controlbar would no longer be hidden by default timeout.
if (controlbar && !is_ios && !is_android) {
controlbar.on('mouseenter', function (event) {
if (this.player().options_.inactivitytimeout !== 0) {
this.player().cache_.inactivitytimeout = this.player().options_.inactivitytimeout;
}
this.player().options_.inactivitytimeout = 0;
});
controlbar.on('mouseleave', function (event) {
this.player().options_.inactivitytimeout = this.player().cache_.inactivitytimeout;
});
} // listen for keyboard navigation
// shouldn't need to use inprogress interval because of key repeat
this.on('keydown', handleactivity);
this.on('keyup', handleactivity); // run an interval every 250 milliseconds instead of stuffing everything into
// the mousemove/touchmove function itself, to prevent performance degradation.
// `this.reportuseractivity` simply sets this.useractivity_ to true, which
// then gets picked up by this loop
// http://ejohn.org/blog/learning-from-twitter/
var inactivitytimeout;
this.setinterval(function () {
// check to see if mouse/touch activity has happened
if (!this.useractivity_) {
return;
} // reset the activity tracker
this.useractivity_ = false; // if the user state was inactive, set the state to active
this.useractive(true); // clear any existing inactivity timeout to start the timer over
this.cleartimeout(inactivitytimeout);
var timeout = this.options_.inactivitytimeout;
if (timeout <= 0) {
return;
} // in milliseconds, if no more activity has occurred the
// user will be considered inactive
inactivitytimeout = this.settimeout(function () {
// protect against the case where the inactivitytimeout can trigger just
// before the next user activity is picked up by the activity check loop
// causing a flicker
if (!this.useractivity_) {
this.useractive(false);
}
}, timeout);
}, 250);
}
/**
* gets or sets the current playback rate. a playback rate of
* 1.0 represents normal speed and 0.5 would indicate half-speed
* playback, for instance.
*
* @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-playbackrate
*
* @param {number} [rate]
* new playback rate to set.
*
* @return {number}
* the current playback rate when getting or 1.0
*/
;
_proto.playbackrate = function playbackrate(rate) {
if (rate !== undefined) {
// note: this.cache_.lastplaybackrate is set from the tech handler
// that is registered above
this.techcall_('setplaybackrate', rate);
return;
}
if (this.tech_ && this.tech_.featuresplaybackrate) {
return this.cache_.lastplaybackrate || this.techget_('playbackrate');
}
return 1.0;
}
/**
* gets or sets the current default playback rate. a default playback rate of
* 1.0 represents normal speed and 0.5 would indicate half-speed playback, for instance.
* defaultplaybackrate will only represent what the initial playbackrate of a video was, not
* not the current playbackrate.
*
* @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-defaultplaybackrate
*
* @param {number} [rate]
* new default playback rate to set.
*
* @return {number|player}
* - the default playback rate when getting or 1.0
* - the player when setting
*/
;
_proto.defaultplaybackrate = function defaultplaybackrate(rate) {
if (rate !== undefined) {
return this.techcall_('setdefaultplaybackrate', rate);
}
if (this.tech_ && this.tech_.featuresplaybackrate) {
return this.techget_('defaultplaybackrate');
}
return 1.0;
}
/**
* gets or sets the audio flag
*
* @param {boolean} bool
* - true signals that this is an audio player
* - false signals that this is not an audio player
*
* @return {boolean}
* the current value of isaudio when getting
*/
;
_proto.isaudio = function isaudio(bool) {
if (bool !== undefined) {
this.isaudio_ = !!bool;
return;
}
return !!this.isaudio_;
};
_proto.enableaudioonlyui_ = function enableaudioonlyui_() {
var _this19 = this;
// update styling immediately to show the control bar so we can get its height
this.addclass('vjs-audio-only-mode');
var playerchildren = this.children();
var controlbar = this.getchild('controlbar');
var controlbarheight = controlbar && controlbar.currentheight(); // hide all player components except the control bar. control bar components
// needed only for video are hidden with css
playerchildren.foreach(function (child) {
if (child === controlbar) {
return;
}
if (child.el_ && !child.hasclass('vjs-hidden')) {
child.hide();
_this19.audioonlycache_.hiddenchildren.push(child);
}
});
this.audioonlycache_.playerheight = this.currentheight(); // set the player height the same as the control bar
this.height(controlbarheight);
this.trigger('audioonlymodechange');
};
_proto.disableaudioonlyui_ = function disableaudioonlyui_() {
this.removeclass('vjs-audio-only-mode'); // show player components that were previously hidden
this.audioonlycache_.hiddenchildren.foreach(function (child) {
return child.show();
}); // reset player height
this.height(this.audioonlycache_.playerheight);
this.trigger('audioonlymodechange');
}
/**
* get the current audioonlymode state or set audioonlymode to true or false.
*
* setting this to `true` will hide all player components except the control bar,
* as well as control bar components needed only for video.
*
* @param {boolean} [value]
* the value to set audioonlymode to.
*
* @return {promise|boolean}
* a promise is returned when setting the state, and a boolean when getting
* the present state
*/
;
_proto.audioonlymode = function audioonlymode(value) {
var _this20 = this;
if (typeof value !== 'boolean' || value === this.audioonlymode_) {
return this.audioonlymode_;
}
this.audioonlymode_ = value;
var promiseclass = this.options_.promise || global_window__webpack_imported_module_0___default.a.promise;
if (promiseclass) {
// enable audio only mode
if (value) {
var exitpromises = []; // fullscreen and pip are not supported in audioonlymode, so exit if we need to.
if (this.isinpictureinpicture()) {
exitpromises.push(this.exitpictureinpicture());
}
if (this.isfullscreen()) {
exitpromises.push(this.exitfullscreen());
}
if (this.audiopostermode()) {
exitpromises.push(this.audiopostermode(false));
}
return promiseclass.all(exitpromises).then(function () {
return _this20.enableaudioonlyui_();
});
} // disable audio only mode
return promiseclass.resolve().then(function () {
return _this20.disableaudioonlyui_();
});
}
if (value) {
if (this.isinpictureinpicture()) {
this.exitpictureinpicture();
}
if (this.isfullscreen()) {
this.exitfullscreen();
}
this.enableaudioonlyui_();
} else {
this.disableaudioonlyui_();
}
};
_proto.enablepostermodeui_ = function enablepostermodeui_() {
// hide the video element and show the poster image to enable postermodeui
var tech = this.tech_ && this.tech_;
tech.hide();
this.addclass('vjs-audio-poster-mode');
this.trigger('audiopostermodechange');
};
_proto.disablepostermodeui_ = function disablepostermodeui_() {
// show the video element and hide the poster image to disable postermodeui
var tech = this.tech_ && this.tech_;
tech.show();
this.removeclass('vjs-audio-poster-mode');
this.trigger('audiopostermodechange');
}
/**
* get the current audiopostermode state or set audiopostermode to true or false
*
* @param {boolean} [value]
* the value to set audiopostermode to.
*
* @return {promise|boolean}
* a promise is returned when setting the state, and a boolean when getting
* the present state
*/
;
_proto.audiopostermode = function audiopostermode(value) {
var _this21 = this;
if (typeof value !== 'boolean' || value === this.audiopostermode_) {
return this.audiopostermode_;
}
this.audiopostermode_ = value;
var promiseclass = this.options_.promise || global_window__webpack_imported_module_0___default.a.promise;
if (promiseclass) {
if (value) {
if (this.audioonlymode()) {
var audioonlymodepromise = this.audioonlymode(false);
return audioonlymodepromise.then(function () {
// enable audio poster mode after audio only mode is disabled
_this21.enablepostermodeui_();
});
}
return promiseclass.resolve().then(function () {
// enable audio poster mode
_this21.enablepostermodeui_();
});
}
return promiseclass.resolve().then(function () {
// disable audio poster mode
_this21.disablepostermodeui_();
});
}
if (value) {
if (this.audioonlymode()) {
this.audioonlymode(false);
}
this.enablepostermodeui_();
return;
}
this.disablepostermodeui_();
}
/**
* a helper method for adding a {@link texttrack} to our
* {@link texttracklist}.
*
* in addition to the w3c settings we allow adding additional info through options.
*
* @see http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#dom-media-addtexttrack
*
* @param {string} [kind]
* the kind of texttrack you are adding
*
* @param {string} [label]
* the label to give the texttrack label
*
* @param {string} [language]
* the language to set on the texttrack
*
* @return {texttrack|undefined}
* the texttrack that was added or undefined
* if there is no tech
*/
;
_proto.addtexttrack = function addtexttrack(kind, label, language) {
if (this.tech_) {
return this.tech_.addtexttrack(kind, label, language);
}
}
/**
* create a remote {@link texttrack} and an {@link htmltrackelement}.
* when manualcleanup is set to false, the track will be automatically removed
* on source changes.
*
* @param {object} options
* options to pass to {@link htmltrackelement} during creation. see
* {@link htmltrackelement} for object properties that you should use.
*
* @param {boolean} [manualcleanup=true] if set to false, the texttrack will be
* removed on a source change
*
* @return {htmltrackelement}
* the htmltrackelement that was created and added
* to the htmltrackelementlist and the remote
* texttracklist
*
* @deprecated the default value of the "manualcleanup" parameter will default
* to "false" in upcoming versions of video.js
*/
;
_proto.addremotetexttrack = function addremotetexttrack(options, manualcleanup) {
if (this.tech_) {
return this.tech_.addremotetexttrack(options, manualcleanup);
}
}
/**
* remove a remote {@link texttrack} from the respective
* {@link texttracklist} and {@link htmltrackelementlist}.
*
* @param {object} track
* remote {@link texttrack} to remove
*
* @return {undefined}
* does not return anything
*/
;
_proto.removeremotetexttrack = function removeremotetexttrack(obj) {
if (obj === void 0) {
obj = {};
}
var _obj = obj,
track = _obj.track;
if (!track) {
track = obj;
} // destructure the input into an object with a track argument, defaulting to arguments[0]
// default the whole argument to an empty object if nothing was passed in
if (this.tech_) {
return this.tech_.removeremotetexttrack(track);
}
}
/**
* gets available media playback quality metrics as specified by the w3c's media
* playback quality api.
*
* @see [spec]{@link https://wicg.github.io/media-playback-quality}
*
* @return {object|undefined}
* an object with supported media playback quality metrics or undefined if there
* is no tech or the tech does not support it.
*/
;
_proto.getvideoplaybackquality = function getvideoplaybackquality() {
return this.techget_('getvideoplaybackquality');
}
/**
* get video width
*
* @return {number}
* current video width
*/
;
_proto.videowidth = function videowidth() {
return this.tech_ && this.tech_.videowidth && this.tech_.videowidth() || 0;
}
/**
* get video height
*
* @return {number}
* current video height
*/
;
_proto.videoheight = function videoheight() {
return this.tech_ && this.tech_.videoheight && this.tech_.videoheight() || 0;
}
/**
* the player's language code.
*
* changing the language will trigger
* [languagechange]{@link player#event:languagechange}
* which components can use to update control text.
* clickablecomponent will update its control text by default on
* [languagechange]{@link player#event:languagechange}.
*
* @fires player#languagechange
*
* @param {string} [code]
* the language code to set the player to
*
* @return {string}
* the current language code when getting
*/
;
_proto.language = function language(code) {
if (code === undefined) {
return this.language_;
}
if (this.language_ !== string(code).tolowercase()) {
this.language_ = string(code).tolowercase(); // during first init, it's possible some things won't be evented
if (isevented(this)) {
/**
* fires when the player language change
*
* @event player#languagechange
* @type {eventtarget~event}
*/
this.trigger('languagechange');
}
}
}
/**
* get the player's language dictionary
* merge every time, because a newly added plugin might call videojs.addlanguage() at any time
* languages specified directly in the player options have precedence
*
* @return {array}
* an array of of supported languages
*/
;
_proto.languages = function languages() {
return mergeoptions$3(player.prototype.options_.languages, this.languages_);
}
/**
* returns a javascript object reperesenting the current track
* information. **does not return it as json**
*
* @return {object}
* object representing the current of track info
*/
;
_proto.tojson = function tojson() {
var options = mergeoptions$3(this.options_);
var tracks = options.tracks;
options.tracks = [];
for (var i = 0; i < tracks.length; i++) {
var track = tracks[i]; // deep merge tracks and null out player so no circular references
track = mergeoptions$3(track);
track.player = undefined;
options.tracks[i] = track;
}
return options;
}
/**
* creates a simple modal dialog (an instance of the {@link modaldialog}
* component) that immediately overlays the player with arbitrary
* content and removes itself when closed.
*
* @param {string|function|element|array|null} content
* same as {@link modaldialog#content}'s param of the same name.
* the most straight-forward usage is to provide a string or dom
* element.
*
* @param {object} [options]
* extra options which will be passed on to the {@link modaldialog}.
*
* @return {modaldialog}
* the {@link modaldialog} that was created
*/
;
_proto.createmodal = function createmodal(content, options) {
var _this22 = this;
options = options || {};
options.content = content || '';
var modal = new modaldialog(this, options);
this.addchild(modal);
modal.on('dispose', function () {
_this22.removechild(modal);
});
modal.open();
return modal;
}
/**
* change breakpoint classes when the player resizes.
*
* @private
*/
;
_proto.updatecurrentbreakpoint_ = function updatecurrentbreakpoint_() {
if (!this.responsive()) {
return;
}
var currentbreakpoint = this.currentbreakpoint();
var currentwidth = this.currentwidth();
for (var i = 0; i < breakpoint_order.length; i++) {
var candidatebreakpoint = breakpoint_order[i];
var maxwidth = this.breakpoints_[candidatebreakpoint];
if (currentwidth <= maxwidth) {
// the current breakpoint did not change, nothing to do.
if (currentbreakpoint === candidatebreakpoint) {
return;
} // only remove a class if there is a current breakpoint.
if (currentbreakpoint) {
this.removeclass(breakpoint_classes[currentbreakpoint]);
}
this.addclass(breakpoint_classes[candidatebreakpoint]);
this.breakpoint_ = candidatebreakpoint;
break;
}
}
}
/**
* removes the current breakpoint.
*
* @private
*/
;
_proto.removecurrentbreakpoint_ = function removecurrentbreakpoint_() {
var classname = this.currentbreakpointclass();
this.breakpoint_ = '';
if (classname) {
this.removeclass(classname);
}
}
/**
* get or set breakpoints on the player.
*
* calling this method with an object or `true` will remove any previous
* custom breakpoints and start from the defaults again.
*
* @param {object|boolean} [breakpoints]
* if an object is given, it can be used to provide custom
* breakpoints. if `true` is given, will set default breakpoints.
* if this argument is not given, will simply return the current
* breakpoints.
*
* @param {number} [breakpoints.tiny]
* the maximum width for the "vjs-layout-tiny" class.
*
* @param {number} [breakpoints.xsmall]
* the maximum width for the "vjs-layout-x-small" class.
*
* @param {number} [breakpoints.small]
* the maximum width for the "vjs-layout-small" class.
*
* @param {number} [breakpoints.medium]
* the maximum width for the "vjs-layout-medium" class.
*
* @param {number} [breakpoints.large]
* the maximum width for the "vjs-layout-large" class.
*
* @param {number} [breakpoints.xlarge]
* the maximum width for the "vjs-layout-x-large" class.
*
* @param {number} [breakpoints.huge]
* the maximum width for the "vjs-layout-huge" class.
*
* @return {object}
* an object mapping breakpoint names to maximum width values.
*/
;
_proto.breakpoints = function breakpoints(_breakpoints) {
// used as a getter.
if (_breakpoints === undefined) {
return assign(this.breakpoints_);
}
this.breakpoint_ = '';
this.breakpoints_ = assign({}, default_breakpoints, _breakpoints); // when breakpoint definitions change, we need to update the currently
// selected breakpoint.
this.updatecurrentbreakpoint_(); // clone the breakpoints before returning.
return assign(this.breakpoints_);
}
/**
* get or set a flag indicating whether or not this player should adjust
* its ui based on its dimensions.
*
* @param {boolean} value
* should be `true` if the player should adjust its ui based on its
* dimensions; otherwise, should be `false`.
*
* @return {boolean}
* will be `true` if this player should adjust its ui based on its
* dimensions; otherwise, will be `false`.
*/
;
_proto.responsive = function responsive(value) {
// used as a getter.
if (value === undefined) {
return this.responsive_;
}
value = boolean(value);
var current = this.responsive_; // nothing changed.
if (value === current) {
return;
} // the value actually changed, set it.
this.responsive_ = value; // start listening for breakpoints and set the initial breakpoint if the
// player is now responsive.
if (value) {
this.on('playerresize', this.boundupdatecurrentbreakpoint_);
this.updatecurrentbreakpoint_(); // stop listening for breakpoints if the player is no longer responsive.
} else {
this.off('playerresize', this.boundupdatecurrentbreakpoint_);
this.removecurrentbreakpoint_();
}
return value;
}
/**
* get current breakpoint name, if any.
*
* @return {string}
* if there is currently a breakpoint set, returns a the key from the
* breakpoints object matching it. otherwise, returns an empty string.
*/
;
_proto.currentbreakpoint = function currentbreakpoint() {
return this.breakpoint_;
}
/**
* get the current breakpoint class name.
*
* @return {string}
* the matching class name (e.g. `"vjs-layout-tiny"` or
* `"vjs-layout-large"`) for the current breakpoint. empty string if
* there is no current breakpoint.
*/
;
_proto.currentbreakpointclass = function currentbreakpointclass() {
return breakpoint_classes[this.breakpoint_] || '';
}
/**
* an object that describes a single piece of media.
*
* properties that are not part of this type description will be retained; so,
* this can be viewed as a generic metadata storage mechanism as well.
*
* @see {@link https://wicg.github.io/mediasession/#the-mediametadata-interface}
* @typedef {object} player~mediaobject
*
* @property {string} [album]
* unused, except if this object is passed to the `mediasession`
* api.
*
* @property {string} [artist]
* unused, except if this object is passed to the `mediasession`
* api.
*
* @property {object[]} [artwork]
* unused, except if this object is passed to the `mediasession`
* api. if not specified, will be populated via the `poster`, if
* available.
*
* @property {string} [poster]
* url to an image that will display before playback.
*
* @property {tech~sourceobject|tech~sourceobject[]|string} [src]
* a single source object, an array of source objects, or a string
* referencing a url to a media source. it is _highly recommended_
* that an object or array of objects is used here, so that source
* selection algorithms can take the `type` into account.
*
* @property {string} [title]
* unused, except if this object is passed to the `mediasession`
* api.
*
* @property {object[]} [texttracks]
* an array of objects to be used to create text tracks, following
* the {@link https://www.w3.org/tr/html50/embedded-content-0.html#the-track-element|native track element format}.
* for ease of removal, these will be created as "remote" text
* tracks and set to automatically clean up on source changes.
*
* these objects may have properties like `src`, `kind`, `label`,
* and `language`, see {@link tech#createremotetexttrack}.
*/
/**
* populate the player using a {@link player~mediaobject|mediaobject}.
*
* @param {player~mediaobject} media
* a media object.
*
* @param {function} ready
* a callback to be called when the player is ready.
*/
;
_proto.loadmedia = function loadmedia(media, ready) {
var _this23 = this;
if (!media || typeof media !== 'object') {
return;
}
this.reset(); // clone the media object so it cannot be mutated from outside.
this.cache_.media = mergeoptions$3(media);
var _this$cache_$media = this.cache_.media,
artwork = _this$cache_$media.artwork,
poster = _this$cache_$media.poster,
src = _this$cache_$media.src,
texttracks = _this$cache_$media.texttracks; // if `artwork` is not given, create it using `poster`.
if (!artwork && poster) {
this.cache_.media.artwork = [{
src: poster,
type: getmimetype(poster)
}];
}
if (src) {
this.src(src);
}
if (poster) {
this.poster(poster);
}
if (array.isarray(texttracks)) {
texttracks.foreach(function (tt) {
return _this23.addremotetexttrack(tt, false);
});
}
this.ready(ready);
}
/**
* get a clone of the current {@link player~mediaobject} for this player.
*
* if the `loadmedia` method has not been used, will attempt to return a
* {@link player~mediaobject} based on the current state of the player.
*
* @return {player~mediaobject}
*/
;
_proto.getmedia = function getmedia() {
if (!this.cache_.media) {
var poster = this.poster();
var src = this.currentsources();
var texttracks = array.prototype.map.call(this.remotetexttracks(), function (tt) {
return {
kind: tt.kind,
label: tt.label,
language: tt.language,
src: tt.src
};
});
var media = {
src: src,
texttracks: texttracks
};
if (poster) {
media.poster = poster;
media.artwork = [{
src: media.poster,
type: getmimetype(media.poster)
}];
}
return media;
}
return mergeoptions$3(this.cache_.media);
}
/**
* gets tag settings
*
* @param {element} tag
* the player tag
*
* @return {object}
* an object containing all of the settings
* for a player tag
*/
;
player.gettagsettings = function gettagsettings(tag) {
var baseoptions = {
sources: [],
tracks: []
};
var tagoptions = getattributes(tag);
var datasetup = tagoptions['data-setup'];
if (hasclass(tag, 'vjs-fill')) {
tagoptions.fill = true;
}
if (hasclass(tag, 'vjs-fluid')) {
tagoptions.fluid = true;
} // check if data-setup attr exists.
if (datasetup !== null) {
// parse options json
// if empty string, make it a parsable json object.
var _safeparsetuple = safe_json_parse_tuple__webpack_imported_module_6___default()(datasetup || '{}'),
err = _safeparsetuple[0],
data = _safeparsetuple[1];
if (err) {
log$1.error(err);
}
assign(tagoptions, data);
}
assign(baseoptions, tagoptions); // get tag children settings
if (tag.haschildnodes()) {
var children = tag.childnodes;
for (var i = 0, j = children.length; i < j; i++) {
var child = children[i]; // change case needed: http://ejohn.org/blog/nodename-case-sensitivity/
var childname = child.nodename.tolowercase();
if (childname === 'source') {
baseoptions.sources.push(getattributes(child));
} else if (childname === 'track') {
baseoptions.tracks.push(getattributes(child));
}
}
}
return baseoptions;
}
/**
* determine whether or not flexbox is supported
*
* @return {boolean}
* - true if flexbox is supported
* - false if flexbox is not supported
*/
;
_proto.flexnotsupported_ = function flexnotsupported_() {
var elem = global_document__webpack_imported_module_1___default.a.createelement('i'); // note: we don't actually use flexbasis (or flexorder), but it's one of the more
// common flex features that we can rely on when checking for flex support.
return !('flexbasis' in elem.style || 'webkitflexbasis' in elem.style || 'mozflexbasis' in elem.style || 'msflexbasis' in elem.style || // ie10-specific (2012 flex spec), available for completeness
'msflexorder' in elem.style);
}
/**
* set debug mode to enable/disable logs at info level.
*
* @param {boolean} enabled
* @fires player#debugon
* @fires player#debugoff
*/
;
_proto.debug = function debug(enabled) {
if (enabled === undefined) {
return this.debugenabled_;
}
if (enabled) {
this.trigger('debugon');
this.previousloglevel_ = this.log.level;
this.log.level('debug');
this.debugenabled_ = true;
} else {
this.trigger('debugoff');
this.log.level(this.previousloglevel_);
this.previousloglevel_ = undefined;
this.debugenabled_ = false;
}
}
/**
* set or get current playback rates.
* takes an array and updates the playback rates menu with the new items.
* pass in an empty array to hide the menu.
* values other than arrays are ignored.
*
* @fires player#playbackrateschange
* @param {number[]} newrates
* the new rates that the playback rates menu should update to.
* an empty array will hide the menu
* @return {number[]} when used as a getter will return the current playback rates
*/
;
_proto.playbackrates = function playbackrates(newrates) {
if (newrates === undefined) {
return this.cache_.playbackrates;
} // ignore any value that isn't an array
if (!array.isarray(newrates)) {
return;
} // ignore any arrays that don't only contain numbers
if (!newrates.every(function (rate) {
return typeof rate === 'number';
})) {
return;
}
this.cache_.playbackrates = newrates;
/**
* fires when the playback rates in a player are changed
*
* @event player#playbackrateschange
* @type {eventtarget~event}
*/
this.trigger('playbackrateschange');
};
return player;
}(component$1);
/**
* get the {@link videotracklist}
* @link https://html.spec.whatwg.org/multipage/embedded-content.html#videotracklist
*
* @return {videotracklist}
* the current video track list
*
* @method player.prototype.videotracks
*/
/**
* get the {@link audiotracklist}
* @link https://html.spec.whatwg.org/multipage/embedded-content.html#audiotracklist
*
* @return {audiotracklist}
* the current audio track list
*
* @method player.prototype.audiotracks
*/
/**
* get the {@link texttracklist}
*
* @link http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#dom-media-texttracks
*
* @return {texttracklist}
* the current text track list
*
* @method player.prototype.texttracks
*/
/**
* get the remote {@link texttracklist}
*
* @return {texttracklist}
* the current remote text track list
*
* @method player.prototype.remotetexttracks
*/
/**
* get the remote {@link htmltrackelementlist} tracks.
*
* @return {htmltrackelementlist}
* the current remote text track element list
*
* @method player.prototype.remotetexttrackels
*/
all.names.foreach(function (name) {
var props = all[name];
player.prototype[props.gettername] = function () {
if (this.tech_) {
return this.tech_[props.gettername]();
} // if we have not yet loadtech_, we create {video,audio,text}tracks_
// these will be passed to the tech during loading
this[props.privatename] = this[props.privatename] || new props.listclass();
return this[props.privatename];
};
});
/**
* get or set the `player`'s crossorigin option. for the html5 player, this
* sets the `crossorigin` property on the `` tag to control the cors
* behavior.
*
* @see [video element attributes]{@link https://developer.mozilla.org/en-us/docs/web/html/element/video#attr-crossorigin}
*
* @param {string} [value]
* the value to set the `player`'s crossorigin to. if an argument is
* given, must be one of `anonymous` or `use-credentials`.
*
* @return {string|undefined}
* - the current crossorigin value of the `player` when getting.
* - undefined when setting
*/
player.prototype.crossorigin = player.prototype.crossorigin;
/**
* global enumeration of players.
*
* the keys are the player ids and the values are either the {@link player}
* instance or `null` for disposed players.
*
* @type {object}
*/
player.players = {};
var navigator = global_window__webpack_imported_module_0___default.a.navigator;
/*
* player instance options, surfaced using options
* options = player.prototype.options_
* make changes in options, not here.
*
* @type {object}
* @private
*/
player.prototype.options_ = {
// default order of fallback technology
techorder: tech.defaulttechorder_,
html5: {},
// default inactivity timeout
inactivitytimeout: 2000,
// default playback rates
playbackrates: [],
// add playback rate selection by adding rates
// 'playbackrates': [0.5, 1, 1.5, 2],
liveui: false,
// included control sets
children: ['medialoader', 'posterimage', 'texttrackdisplay', 'loadingspinner', 'bigplaybutton', 'livetracker', 'controlbar', 'errordisplay', 'texttracksettings', 'resizemanager'],
language: navigator && (navigator.languages && navigator.languages[0] || navigator.userlanguage || navigator.language) || 'en',
// locales and their language translations
languages: {},
// default message to show when a video cannot be played.
notsupportedmessage: 'no compatible source was found for this media.',
normalizeautoplay: false,
fullscreen: {
options: {
navigationui: 'hide'
}
},
breakpoints: {},
responsive: false,
audioonlymode: false,
audiopostermode: false
};
[
/**
* returns whether or not the player is in the "ended" state.
*
* @return {boolean} true if the player is in the ended state, false if not.
* @method player#ended
*/
'ended',
/**
* returns whether or not the player is in the "seeking" state.
*
* @return {boolean} true if the player is in the seeking state, false if not.
* @method player#seeking
*/
'seeking',
/**
* returns the timeranges of the media that are currently available
* for seeking to.
*
* @return {timeranges} the seekable intervals of the media timeline
* @method player#seekable
*/
'seekable',
/**
* returns the current state of network activity for the element, from
* the codes in the list below.
* - network_empty (numeric value 0)
* the element has not yet been initialised. all attributes are in
* their initial states.
* - network_idle (numeric value 1)
* the element's resource selection algorithm is active and has
* selected a resource, but it is not actually using the network at
* this time.
* - network_loading (numeric value 2)
* the user agent is actively trying to download data.
* - network_no_source (numeric value 3)
* the element's resource selection algorithm is active, but it has
* not yet found a resource to use.
*
* @see https://html.spec.whatwg.org/multipage/embedded-content.html#network-states
* @return {number} the current network activity state
* @method player#networkstate
*/
'networkstate',
/**
* returns a value that expresses the current state of the element
* with respect to rendering the current playback position, from the
* codes in the list below.
* - have_nothing (numeric value 0)
* no information regarding the media resource is available.
* - have_metadata (numeric value 1)
* enough of the resource has been obtained that the duration of the
* resource is available.
* - have_current_data (numeric value 2)
* data for the immediate current playback position is available.
* - have_future_data (numeric value 3)
* data for the immediate current playback position is available, as
* well as enough data for the user agent to advance the current
* playback position in the direction of playback.
* - have_enough_data (numeric value 4)
* the user agent estimates that enough data is available for
* playback to proceed uninterrupted.
*
* @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-readystate
* @return {number} the current playback rendering state
* @method player#readystate
*/
'readystate'].foreach(function (fn) {
player.prototype[fn] = function () {
return this.techget_(fn);
};
});
tech_events_retrigger.foreach(function (event) {
player.prototype["handletech" + totitlecase$1(event) + "_"] = function () {
return this.trigger(event);
};
});
/**
* fired when the player has initial duration and dimension information
*
* @event player#loadedmetadata
* @type {eventtarget~event}
*/
/**
* fired when the player has downloaded data at the current playback position
*
* @event player#loadeddata
* @type {eventtarget~event}
*/
/**
* fired when the current playback position has changed *
* during playback this is fired every 15-250 milliseconds, depending on the
* playback technology in use.
*
* @event player#timeupdate
* @type {eventtarget~event}
*/
/**
* fired when the volume changes
*
* @event player#volumechange
* @type {eventtarget~event}
*/
/**
* reports whether or not a player has a plugin available.
*
* this does not report whether or not the plugin has ever been initialized
* on this player. for that, [usingplugin]{@link player#usingplugin}.
*
* @method player#hasplugin
* @param {string} name
* the name of a plugin.
*
* @return {boolean}
* whether or not this player has the requested plugin available.
*/
/**
* reports whether or not a player is using a plugin by name.
*
* for basic plugins, this only reports whether the plugin has _ever_ been
* initialized on this player.
*
* @method player#usingplugin
* @param {string} name
* the name of a plugin.
*
* @return {boolean}
* whether or not this player is using the requested plugin.
*/
component$1.registercomponent('player', player);
/**
* the base plugin name.
*
* @private
* @constant
* @type {string}
*/
var base_plugin_name = 'plugin';
/**
* the key on which a player's active plugins cache is stored.
*
* @private
* @constant
* @type {string}
*/
var plugin_cache_key = 'activeplugins_';
/**
* stores registered plugins in a private space.
*
* @private
* @type {object}
*/
var pluginstorage = {};
/**
* reports whether or not a plugin has been registered.
*
* @private
* @param {string} name
* the name of a plugin.
*
* @return {boolean}
* whether or not the plugin has been registered.
*/
var pluginexists = function pluginexists(name) {
return pluginstorage.hasownproperty(name);
};
/**
* get a single registered plugin by name.
*
* @private
* @param {string} name
* the name of a plugin.
*
* @return {function|undefined}
* the plugin (or undefined).
*/
var getplugin = function getplugin(name) {
return pluginexists(name) ? pluginstorage[name] : undefined;
};
/**
* marks a plugin as "active" on a player.
*
* also, ensures that the player has an object for tracking active plugins.
*
* @private
* @param {player} player
* a video.js player instance.
*
* @param {string} name
* the name of a plugin.
*/
var markpluginasactive = function markpluginasactive(player, name) {
player[plugin_cache_key] = player[plugin_cache_key] || {};
player[plugin_cache_key][name] = true;
};
/**
* triggers a pair of plugin setup events.
*
* @private
* @param {player} player
* a video.js player instance.
*
* @param {plugin~plugineventhash} hash
* a plugin event hash.
*
* @param {boolean} [before]
* if true, prefixes the event name with "before". in other words,
* use this to trigger "beforepluginsetup" instead of "pluginsetup".
*/
var triggersetupevent = function triggersetupevent(player, hash, before) {
var eventname = (before ? 'before' : '') + 'pluginsetup';
player.trigger(eventname, hash);
player.trigger(eventname + ':' + hash.name, hash);
};
/**
* takes a basic plugin function and returns a wrapper function which marks
* on the player that the plugin has been activated.
*
* @private
* @param {string} name
* the name of the plugin.
*
* @param {function} plugin
* the basic plugin.
*
* @return {function}
* a wrapper function for the given plugin.
*/
var createbasicplugin = function createbasicplugin(name, plugin) {
var basicpluginwrapper = function basicpluginwrapper() {
// we trigger the "beforepluginsetup" and "pluginsetup" events on the player
// regardless, but we want the hash to be consistent with the hash provided
// for advanced plugins.
//
// the only potentially counter-intuitive thing here is the `instance` in
// the "pluginsetup" event is the value returned by the `plugin` function.
triggersetupevent(this, {
name: name,
plugin: plugin,
instance: null
}, true);
var instance = plugin.apply(this, arguments);
markpluginasactive(this, name);
triggersetupevent(this, {
name: name,
plugin: plugin,
instance: instance
});
return instance;
};
object.keys(plugin).foreach(function (prop) {
basicpluginwrapper[prop] = plugin[prop];
});
return basicpluginwrapper;
};
/**
* takes a plugin sub-class and returns a factory function for generating
* instances of it.
*
* this factory function will replace itself with an instance of the requested
* sub-class of plugin.
*
* @private
* @param {string} name
* the name of the plugin.
*
* @param {plugin} pluginsubclass
* the advanced plugin.
*
* @return {function}
*/
var createpluginfactory = function createpluginfactory(name, pluginsubclass) {
// add a `name` property to the plugin prototype so that each plugin can
// refer to itself by name.
pluginsubclass.prototype.name = name;
return function () {
triggersetupevent(this, {
name: name,
plugin: pluginsubclass,
instance: null
}, true);
for (var _len = arguments.length, args = new array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
var instance = _babel_runtime_helpers_construct__webpack_imported_module_9___default()(pluginsubclass, [this].concat(args)); // the plugin is replaced by a function that returns the current instance.
this[name] = function () {
return instance;
};
triggersetupevent(this, instance.geteventhash());
return instance;
};
};
/**
* parent class for all advanced plugins.
*
* @mixes module:evented~eventedmixin
* @mixes module:stateful~statefulmixin
* @fires player#beforepluginsetup
* @fires player#beforepluginsetup:$name
* @fires player#pluginsetup
* @fires player#pluginsetup:$name
* @listens player#dispose
* @throws {error}
* if attempting to instantiate the base {@link plugin} class
* directly instead of via a sub-class.
*/
var plugin = /*#__pure__*/function () {
/**
* creates an instance of this class.
*
* sub-classes should call `super` to ensure plugins are properly initialized.
*
* @param {player} player
* a video.js player instance.
*/
function plugin(player) {
if (this.constructor === plugin) {
throw new error('plugin must be sub-classed; not directly instantiated.');
}
this.player = player;
if (!this.log) {
this.log = this.player.log.createlogger(this.name);
} // make this object evented, but remove the added `trigger` method so we
// use the prototype version instead.
evented(this);
delete this.trigger;
stateful(this, this.constructor.defaultstate);
markpluginasactive(player, this.name); // auto-bind the dispose method so we can use it as a listener and unbind
// it later easily.
this.dispose = this.dispose.bind(this); // if the player is disposed, dispose the plugin.
player.on('dispose', this.dispose);
}
/**
* get the version of the plugin that was set on .version
*/
var _proto = plugin.prototype;
_proto.version = function version() {
return this.constructor.version;
}
/**
* each event triggered by plugins includes a hash of additional data with
* conventional properties.
*
* this returns that object or mutates an existing hash.
*
* @param {object} [hash={}]
* an object to be used as event an event hash.
*
* @return {plugin~plugineventhash}
* an event hash object with provided properties mixed-in.
*/
;
_proto.geteventhash = function geteventhash(hash) {
if (hash === void 0) {
hash = {};
}
hash.name = this.name;
hash.plugin = this.constructor;
hash.instance = this;
return hash;
}
/**
* triggers an event on the plugin object and overrides
* {@link module:evented~eventedmixin.trigger|eventedmixin.trigger}.
*
* @param {string|object} event
* an event type or an object with a type property.
*
* @param {object} [hash={}]
* additional data hash to merge with a
* {@link plugin~plugineventhash|plugineventhash}.
*
* @return {boolean}
* whether or not default was prevented.
*/
;
_proto.trigger = function trigger$1(event, hash) {
if (hash === void 0) {
hash = {};
}
return trigger(this.eventbusel_, event, this.geteventhash(hash));
}
/**
* handles "statechanged" events on the plugin. no-op by default, override by
* subclassing.
*
* @abstract
* @param {event} e
* an event object provided by a "statechanged" event.
*
* @param {object} e.changes
* an object describing changes that occurred with the "statechanged"
* event.
*/
;
_proto.handlestatechanged = function handlestatechanged(e) {}
/**
* disposes a plugin.
*
* subclasses can override this if they want, but for the sake of safety,
* it's probably best to subscribe the "dispose" event.
*
* @fires plugin#dispose
*/
;
_proto.dispose = function dispose() {
var name = this.name,
player = this.player;
/**
* signals that a advanced plugin is about to be disposed.
*
* @event plugin#dispose
* @type {eventtarget~event}
*/
this.trigger('dispose');
this.off();
player.off('dispose', this.dispose); // eliminate any possible sources of leaking memory by clearing up
// references between the player and the plugin instance and nulling out
// the plugin's state and replacing methods with a function that throws.
player[plugin_cache_key][name] = false;
this.player = this.state = null; // finally, replace the plugin name on the player with a new factory
// function, so that the plugin is ready to be set up again.
player[name] = createpluginfactory(name, pluginstorage[name]);
}
/**
* determines if a plugin is a basic plugin (i.e. not a sub-class of `plugin`).
*
* @param {string|function} plugin
* if a string, matches the name of a plugin. if a function, will be
* tested directly.
*
* @return {boolean}
* whether or not a plugin is a basic plugin.
*/
;
plugin.isbasic = function isbasic(plugin) {
var p = typeof plugin === 'string' ? getplugin(plugin) : plugin;
return typeof p === 'function' && !plugin.prototype.isprototypeof(p.prototype);
}
/**
* register a video.js plugin.
*
* @param {string} name
* the name of the plugin to be registered. must be a string and
* must not match an existing plugin or a method on the `player`
* prototype.
*
* @param {function} plugin
* a sub-class of `plugin` or a function for basic plugins.
*
* @return {function}
* for advanced plugins, a factory function for that plugin. for
* basic plugins, a wrapper function that initializes the plugin.
*/
;
plugin.registerplugin = function registerplugin(name, plugin) {
if (typeof name !== 'string') {
throw new error("illegal plugin name, \"" + name + "\", must be a string, was " + typeof name + ".");
}
if (pluginexists(name)) {
log$1.warn("a plugin named \"" + name + "\" already exists. you may want to avoid re-registering plugins!");
} else if (player.prototype.hasownproperty(name)) {
throw new error("illegal plugin name, \"" + name + "\", cannot share a name with an existing player method!");
}
if (typeof plugin !== 'function') {
throw new error("illegal plugin for \"" + name + "\", must be a function, was " + typeof plugin + ".");
}
pluginstorage[name] = plugin; // add a player prototype method for all sub-classed plugins (but not for
// the base plugin class).
if (name !== base_plugin_name) {
if (plugin.isbasic(plugin)) {
player.prototype[name] = createbasicplugin(name, plugin);
} else {
player.prototype[name] = createpluginfactory(name, plugin);
}
}
return plugin;
}
/**
* de-register a video.js plugin.
*
* @param {string} name
* the name of the plugin to be de-registered. must be a string that
* matches an existing plugin.
*
* @throws {error}
* if an attempt is made to de-register the base plugin.
*/
;
plugin.deregisterplugin = function deregisterplugin(name) {
if (name === base_plugin_name) {
throw new error('cannot de-register base plugin.');
}
if (pluginexists(name)) {
delete pluginstorage[name];
delete player.prototype[name];
}
}
/**
* gets an object containing multiple video.js plugins.
*
* @param {array} [names]
* if provided, should be an array of plugin names. defaults to _all_
* plugin names.
*
* @return {object|undefined}
* an object containing plugin(s) associated with their name(s) or
* `undefined` if no matching plugins exist).
*/
;
plugin.getplugins = function getplugins(names) {
if (names === void 0) {
names = object.keys(pluginstorage);
}
var result;
names.foreach(function (name) {
var plugin = getplugin(name);
if (plugin) {
result = result || {};
result[name] = plugin;
}
});
return result;
}
/**
* gets a plugin's version, if available
*
* @param {string} name
* the name of a plugin.
*
* @return {string}
* the plugin's version or an empty string.
*/
;
plugin.getpluginversion = function getpluginversion(name) {
var plugin = getplugin(name);
return plugin && plugin.version || '';
};
return plugin;
}();
/**
* gets a plugin by name if it exists.
*
* @static
* @method getplugin
* @memberof plugin
* @param {string} name
* the name of a plugin.
*
* @returns {function|undefined}
* the plugin (or `undefined`).
*/
plugin.getplugin = getplugin;
/**
* the name of the base plugin class as it is registered.
*
* @type {string}
*/
plugin.base_plugin_name = base_plugin_name;
plugin.registerplugin(base_plugin_name, plugin);
/**
* documented in player.js
*
* @ignore
*/
player.prototype.usingplugin = function (name) {
return !!this[plugin_cache_key] && this[plugin_cache_key][name] === true;
};
/**
* documented in player.js
*
* @ignore
*/
player.prototype.hasplugin = function (name) {
return !!pluginexists(name);
};
/**
* signals that a plugin is about to be set up on a player.
*
* @event player#beforepluginsetup
* @type {plugin~plugineventhash}
*/
/**
* signals that a plugin is about to be set up on a player - by name. the name
* is the name of the plugin.
*
* @event player#beforepluginsetup:$name
* @type {plugin~plugineventhash}
*/
/**
* signals that a plugin has just been set up on a player.
*
* @event player#pluginsetup
* @type {plugin~plugineventhash}
*/
/**
* signals that a plugin has just been set up on a player - by name. the name
* is the name of the plugin.
*
* @event player#pluginsetup:$name
* @type {plugin~plugineventhash}
*/
/**
* @typedef {object} plugin~plugineventhash
*
* @property {string} instance
* for basic plugins, the return value of the plugin function. for
* advanced plugins, the plugin instance on which the event is fired.
*
* @property {string} name
* the name of the plugin.
*
* @property {string} plugin
* for basic plugins, the plugin function. for advanced plugins, the
* plugin class/constructor.
*/
/**
* @file extend.js
* @module extend
*/
var haslogged = false;
/**
* used to subclass an existing class by emulating es subclassing using the
* `extends` keyword.
*
* @function
* @deprecated
* @example
* var mycomponent = videojs.extend(videojs.getcomponent('component'), {
* mycustommethod: function() {
* // do things in my method.
* }
* });
*
* @param {function} superclass
* the class to inherit from
*
* @param {object} [subclassmethods={}]
* methods of the new class
*
* @return {function}
* the new class with subclassmethods that inherited superclass.
*/
var extend = function extend(superclass, subclassmethods) {
if (subclassmethods === void 0) {
subclassmethods = {};
}
// log a warning the first time extend is called to note that it is deprecated
// it was previously deprecated in our documentation (guides, specifically),
// but was never formally deprecated in code.
if (!haslogged) {
log$1.warn('videojs.extend is deprecated as of video.js 7.22.0 and will be removed in video.js 8.0.0');
haslogged = true;
}
var subclass = function subclass() {
superclass.apply(this, arguments);
};
var methods = {};
if (typeof subclassmethods === 'object') {
if (subclassmethods.constructor !== object.prototype.constructor) {
subclass = subclassmethods.constructor;
}
methods = subclassmethods;
} else if (typeof subclassmethods === 'function') {
subclass = subclassmethods;
}
_babel_runtime_helpers_inherits__webpack_imported_module_10___default()(subclass, superclass); // this is needed for backward-compatibility and node compatibility.
if (superclass) {
subclass.super_ = superclass;
} // extend subobj's prototype with functions and other properties from props
for (var name in methods) {
if (methods.hasownproperty(name)) {
subclass.prototype[name] = methods[name];
}
}
return subclass;
};
/**
* @file video.js
* @module videojs
*/
/**
* normalize an `id` value by trimming off a leading `#`
*
* @private
* @param {string} id
* a string, maybe with a leading `#`.
*
* @return {string}
* the string, without any leading `#`.
*/
var normalizeid = function normalizeid(id) {
return id.indexof('#') === 0 ? id.slice(1) : id;
};
/**
* the `videojs()` function doubles as the main function for users to create a
* {@link player} instance as well as the main library namespace.
*
* it can also be used as a getter for a pre-existing {@link player} instance.
* however, we _strongly_ recommend using `videojs.getplayer()` for this
* purpose because it avoids any potential for unintended initialization.
*
* due to [limitations](https://github.com/jsdoc3/jsdoc/issues/955#issuecomment-313829149)
* of our jsdoc template, we cannot properly document this as both a function
* and a namespace, so its function signature is documented here.
*
* #### arguments
* ##### id
* string|element, **required**
*
* video element or video element id.
*
* ##### options
* object, optional
*
* options object for providing settings.
* see: [options guide](https://docs.videojs.com/tutorial-options.html).
*
* ##### ready
* {@link component~readycallback}, optional
*
* a function to be called when the {@link player} and {@link tech} are ready.
*
* #### return value
*
* the `videojs()` function returns a {@link player} instance.
*
* @namespace
*
* @borrows audiotrack as audiotrack
* @borrows component.getcomponent as getcomponent
* @borrows module:computed-style~computedstyle as computedstyle
* @borrows module:events.on as on
* @borrows module:events.one as one
* @borrows module:events.off as off
* @borrows module:events.trigger as trigger
* @borrows eventtarget as eventtarget
* @borrows module:extend~extend as extend
* @borrows module:fn.bind as bind
* @borrows module:format-time.formattime as formattime
* @borrows module:format-time.resetformattime as resetformattime
* @borrows module:format-time.setformattime as setformattime
* @borrows module:merge-options.mergeoptions as mergeoptions
* @borrows module:middleware.use as use
* @borrows player.players as players
* @borrows plugin.registerplugin as registerplugin
* @borrows plugin.deregisterplugin as deregisterplugin
* @borrows plugin.getplugins as getplugins
* @borrows plugin.getplugin as getplugin
* @borrows plugin.getpluginversion as getpluginversion
* @borrows tech.gettech as gettech
* @borrows tech.registertech as registertech
* @borrows texttrack as texttrack
* @borrows module:time-ranges.createtimeranges as createtimerange
* @borrows module:time-ranges.createtimeranges as createtimeranges
* @borrows module:url.iscrossorigin as iscrossorigin
* @borrows module:url.parseurl as parseurl
* @borrows videotrack as videotrack
*
* @param {string|element} id
* video element or video element id.
*
* @param {object} [options]
* options object for providing settings.
* see: [options guide](https://docs.videojs.com/tutorial-options.html).
*
* @param {component~readycallback} [ready]
* a function to be called when the {@link player} and {@link tech} are
* ready.
*
* @return {player}
* the `videojs()` function returns a {@link player|player} instance.
*/
function videojs(id, options, ready) {
var player = videojs.getplayer(id);
if (player) {
if (options) {
log$1.warn("player \"" + id + "\" is already initialised. options will not be applied.");
}
if (ready) {
player.ready(ready);
}
return player;
}
var el = typeof id === 'string' ? $('#' + normalizeid(id)) : id;
if (!isel(el)) {
throw new typeerror('the element or id supplied is not valid. (videojs)');
} // document.body.contains(el) will only check if el is contained within that one document.
// this causes problems for elements in iframes.
// instead, use the element's ownerdocument instead of the global document.
// this will make sure that the element is indeed in the dom of that document.
// additionally, check that the document in question has a default view.
// if the document is no longer attached to the dom, the defaultview of the document will be null.
if (!el.ownerdocument.defaultview || !el.ownerdocument.body.contains(el)) {
log$1.warn('the element supplied is not included in the dom');
}
options = options || {}; // store a copy of the el before modification, if it is to be restored in destroy()
// if div ingest, store the parent div
if (options.restoreel === true) {
options.restoreel = (el.parentnode && el.parentnode.hasattribute('data-vjs-player') ? el.parentnode : el).clonenode(true);
}
hooks('beforesetup').foreach(function (hookfunction) {
var opts = hookfunction(el, mergeoptions$3(options));
if (!isobject(opts) || array.isarray(opts)) {
log$1.error('please return an object in beforesetup hooks');
return;
}
options = mergeoptions$3(options, opts);
}); // we get the current "player" component here in case an integration has
// replaced it with a custom player.
var playercomponent = component$1.getcomponent('player');
player = new playercomponent(el, options, ready);
hooks('setup').foreach(function (hookfunction) {
return hookfunction(player);
});
return player;
}
videojs.hooks_ = hooks_;
videojs.hooks = hooks;
videojs.hook = hook;
videojs.hookonce = hookonce;
videojs.removehook = removehook; // add default styles
if (global_window__webpack_imported_module_0___default.a.videojs_no_dynamic_style !== true && isreal()) {
var style = $('.vjs-styles-defaults');
if (!style) {
style = createstyleelement('vjs-styles-defaults');
var head = $('head');
if (head) {
head.insertbefore(style, head.firstchild);
}
settextcontent(style, "\n .video-js {\n width: 300px;\n height: 150px;\n }\n\n .vjs-fluid:not(.vjs-audio-only-mode) {\n padding-top: 56.25%\n }\n ");
}
} // run auto-load players
// you have to wait at least once in case this script is loaded after your
// video in the dom (weird behavior only with minified version)
autosetuptimeout(1, videojs);
/**
* current video.js version. follows [semantic versioning](https://semver.org/).
*
* @type {string}
*/
videojs.version = version$5;
/**
* the global options object. these are the settings that take effect
* if no overrides are specified when the player is created.
*
* @type {object}
*/
videojs.options = player.prototype.options_;
/**
* get an object with the currently created players, keyed by player id
*
* @return {object}
* the created players
*/
videojs.getplayers = function () {
return player.players;
};
/**
* get a single player based on an id or dom element.
*
* this is useful if you want to check if an element or id has an associated
* video.js player, but not create one if it doesn't.
*
* @param {string|element} id
* an html element - ``, ``, or `` -
* or a string matching the `id` of such an element.
*
* @return {player|undefined}
* a player instance or `undefined` if there is no player instance
* matching the argument.
*/
videojs.getplayer = function (id) {
var players = player.players;
var tag;
if (typeof id === 'string') {
var nid = normalizeid(id);
var player = players[nid];
if (player) {
return player;
}
tag = $('#' + nid);
} else {
tag = id;
}
if (isel(tag)) {
var _tag = tag,
_player = _tag.player,
playerid = _tag.playerid; // element may have a `player` property referring to an already created
// player instance. if so, return that.
if (_player || players[playerid]) {
return _player || players[playerid];
}
}
};
/**
* returns an array of all current players.
*
* @return {array}
* an array of all players. the array will be in the order that
* `object.keys` provides, which could potentially vary between
* javascript engines.
*
*/
videojs.getallplayers = function () {
return (// disposed players leave a key with a `null` value, so we need to make sure
// we filter those out.
object.keys(player.players).map(function (k) {
return player.players[k];
}).filter(boolean)
);
};
videojs.players = player.players;
videojs.getcomponent = component$1.getcomponent;
/**
* register a component so it can referred to by name. used when adding to other
* components, either through addchild `component.addchild('mycomponent')` or through
* default children options `{ children: ['mycomponent'] }`.
*
* > note: you could also just initialize the component before adding.
* `component.addchild(new mycomponent());`
*
* @param {string} name
* the class name of the component
*
* @param {component} comp
* the component class
*
* @return {component}
* the newly registered component
*/
videojs.registercomponent = function (name, comp) {
if (tech.istech(comp)) {
log$1.warn("the " + name + " tech was registered as a component. it should instead be registered using videojs.registertech(name, tech)");
}
component$1.registercomponent.call(component$1, name, comp);
};
videojs.gettech = tech.gettech;
videojs.registertech = tech.registertech;
videojs.use = use;
/**
* an object that can be returned by a middleware to signify
* that the middleware is being terminated.
*
* @type {object}
* @property {object} middleware.terminator
*/
object.defineproperty(videojs, 'middleware', {
value: {},
writeable: false,
enumerable: true
});
object.defineproperty(videojs.middleware, 'terminator', {
value: terminator,
writeable: false,
enumerable: true
});
/**
* a reference to the {@link module:browser|browser utility module} as an object.
*
* @type {object}
* @see {@link module:browser|browser}
*/
videojs.browser = browser;
/**
* use {@link module:browser.touch_enabled|browser.touch_enabled} instead; only
* included for backward-compatibility with 4.x.
*
* @deprecated since version 5.0, use {@link module:browser.touch_enabled|browser.touch_enabled instead.
* @type {boolean}
*/
videojs.touch_enabled = touch_enabled;
videojs.extend = extend;
videojs.mergeoptions = mergeoptions$3;
videojs.bind = bind;
videojs.registerplugin = plugin.registerplugin;
videojs.deregisterplugin = plugin.deregisterplugin;
/**
* deprecated method to register a plugin with video.js
*
* @deprecated videojs.plugin() is deprecated; use videojs.registerplugin() instead
*
* @param {string} name
* the plugin name
*
* @param {plugin|function} plugin
* the plugin sub-class or function
*/
videojs.plugin = function (name, plugin) {
log$1.warn('videojs.plugin() is deprecated; use videojs.registerplugin() instead');
return plugin.registerplugin(name, plugin);
};
videojs.getplugins = plugin.getplugins;
videojs.getplugin = plugin.getplugin;
videojs.getpluginversion = plugin.getpluginversion;
/**
* adding languages so that they're available to all players.
* example: `videojs.addlanguage('es', { 'hello': 'hola' });`
*
* @param {string} code
* the language code or dictionary property
*
* @param {object} data
* the data values to be translated
*
* @return {object}
* the resulting language dictionary object
*/
videojs.addlanguage = function (code, data) {
var _mergeoptions;
code = ('' + code).tolowercase();
videojs.options.languages = mergeoptions$3(videojs.options.languages, (_mergeoptions = {}, _mergeoptions[code] = data, _mergeoptions));
return videojs.options.languages[code];
};
/**
* a reference to the {@link module:log|log utility module} as an object.
*
* @type {function}
* @see {@link module:log|log}
*/
videojs.log = log$1;
videojs.createlogger = createlogger;
videojs.createtimerange = videojs.createtimeranges = createtimeranges;
videojs.formattime = formattime;
videojs.setformattime = setformattime;
videojs.resetformattime = resetformattime;
videojs.parseurl = parseurl;
videojs.iscrossorigin = iscrossorigin;
videojs.eventtarget = eventtarget$2;
videojs.on = on;
videojs.one = one;
videojs.off = off;
videojs.trigger = trigger;
/**
* a cross-browser xmlhttprequest wrapper.
*
* @function
* @param {object} options
* settings for the request.
*
* @return {xmlhttprequest|xdomainrequest}
* the request object.
*
* @see https://github.com/raynos/xhr
*/
videojs.xhr = _videojs_xhr__webpack_imported_module_7___default.a;
videojs.texttrack = texttrack;
videojs.audiotrack = audiotrack;
videojs.videotrack = videotrack;
['isel', 'istextnode', 'createel', 'hasclass', 'addclass', 'removeclass', 'toggleclass', 'setattributes', 'getattributes', 'emptyel', 'appendcontent', 'insertcontent'].foreach(function (k) {
videojs[k] = function () {
log$1.warn("videojs." + k + "() is deprecated; use videojs.dom." + k + "() instead");
return dom[k].apply(null, arguments);
};
});
videojs.computedstyle = computedstyle;
/**
* a reference to the {@link module:dom|dom utility module} as an object.
*
* @type {object}
* @see {@link module:dom|dom}
*/
videojs.dom = dom;
/**
* a reference to the {@link module:url|url utility module} as an object.
*
* @type {object}
* @see {@link module:url|url}
*/
videojs.url = url;
videojs.definelazyproperty = definelazyproperty; // adding less ambiguous text for fullscreen button.
// in a major update this could become the default text and key.
videojs.addlanguage('en', {
'non-fullscreen': 'exit fullscreen'
});
/*! @name @videojs/http-streaming @version 2.16.3 @license apache-2.0 */
/**
* @file resolve-url.js - handling how urls are resolved and manipulated
*/
var resolveurl = _videojs_vhs_utils_es_resolve_url_js__webpack_imported_module_11__[/* default */ "a"];
/**
* checks whether xhr request was redirected and returns correct url depending
* on `handlemanifestredirects` option
*
* @api private
*
* @param {string} url - an url being requested
* @param {xmlhttprequest} req - xhr request result
*
* @return {string}
*/
var resolvemanifestredirect = function resolvemanifestredirect(handlemanifestredirect, url, req) {
// to understand how the responseurl below is set and generated:
// - https://fetch.spec.whatwg.org/#concept-response-url
// - https://fetch.spec.whatwg.org/#atomic-http-redirect-handling
if (handlemanifestredirect && req && req.responseurl && url !== req.responseurl) {
return req.responseurl;
}
return url;
};
var logger = function logger(source) {
if (videojs.log.debug) {
return videojs.log.debug.bind(videojs, 'vhs:', source + " >");
}
return function () {};
};
/**
* ranges
*
* utilities for working with timeranges.
*
*/
var time_fudge_factor = 1 / 30; // comparisons between time values such as current time and the end of the buffered range
// can be misleading because of precision differences or when the current media has poorly
// aligned audio and video, which can cause values to be slightly off from what you would
// expect. this value is what we consider to be safe to use in such comparisons to account
// for these scenarios.
var safe_time_delta = time_fudge_factor * 3;
var filterranges = function filterranges(timeranges, predicate) {
var results = [];
var i;
if (timeranges && timeranges.length) {
// search for ranges that match the predicate
for (i = 0; i < timeranges.length; i++) {
if (predicate(timeranges.start(i), timeranges.end(i))) {
results.push([timeranges.start(i), timeranges.end(i)]);
}
}
}
return videojs.createtimeranges(results);
};
/**
* attempts to find the buffered timerange that contains the specified
* time.
*
* @param {timeranges} buffered - the timeranges object to query
* @param {number} time - the time to filter on.
* @return {timeranges} a new timeranges object
*/
var findrange = function findrange(buffered, time) {
return filterranges(buffered, function (start, end) {
return start - safe_time_delta <= time && end + safe_time_delta >= time;
});
};
/**
* returns the timeranges that begin later than the specified time.
*
* @param {timeranges} timeranges - the timeranges object to query
* @param {number} time - the time to filter on.
* @return {timeranges} a new timeranges object.
*/
var findnextrange = function findnextrange(timeranges, time) {
return filterranges(timeranges, function (start) {
return start - time_fudge_factor >= time;
});
};
/**
* returns gaps within a list of timeranges
*
* @param {timeranges} buffered - the timeranges object
* @return {timeranges} a timeranges object of gaps
*/
var findgaps = function findgaps(buffered) {
if (buffered.length < 2) {
return videojs.createtimeranges();
}
var ranges = [];
for (var i = 1; i < buffered.length; i++) {
var start = buffered.end(i - 1);
var end = buffered.start(i);
ranges.push([start, end]);
}
return videojs.createtimeranges(ranges);
};
/**
* calculate the intersection of two timeranges
*
* @param {timeranges} buffera
* @param {timeranges} bufferb
* @return {timeranges} the interesection of `buffera` with `bufferb`
*/
var bufferintersection = function bufferintersection(buffera, bufferb) {
var start = null;
var end = null;
var arity = 0;
var extents = [];
var ranges = [];
if (!buffera || !buffera.length || !bufferb || !bufferb.length) {
return videojs.createtimerange();
} // handle the case where we have both buffers and create an
// intersection of the two
var count = buffera.length; // a) gather up all start and end times
while (count--) {
extents.push({
time: buffera.start(count),
type: 'start'
});
extents.push({
time: buffera.end(count),
type: 'end'
});
}
count = bufferb.length;
while (count--) {
extents.push({
time: bufferb.start(count),
type: 'start'
});
extents.push({
time: bufferb.end(count),
type: 'end'
});
} // b) sort them by time
extents.sort(function (a, b) {
return a.time - b.time;
}); // c) go along one by one incrementing arity for start and decrementing
// arity for ends
for (count = 0; count < extents.length; count++) {
if (extents[count].type === 'start') {
arity++; // d) if arity is ever incremented to 2 we are entering an
// overlapping range
if (arity === 2) {
start = extents[count].time;
}
} else if (extents[count].type === 'end') {
arity--; // e) if arity is ever decremented to 1 we leaving an
// overlapping range
if (arity === 1) {
end = extents[count].time;
}
} // f) record overlapping ranges
if (start !== null && end !== null) {
ranges.push([start, end]);
start = null;
end = null;
}
}
return videojs.createtimeranges(ranges);
};
/**
* gets a human readable string for a timerange
*
* @param {timerange} range
* @return {string} a human readable string
*/
var printablerange = function printablerange(range) {
var strarr = [];
if (!range || !range.length) {
return '';
}
for (var i = 0; i < range.length; i++) {
strarr.push(range.start(i) + ' => ' + range.end(i));
}
return strarr.join(', ');
};
/**
* calculates the amount of time left in seconds until the player hits the end of the
* buffer and causes a rebuffer
*
* @param {timerange} buffered
* the state of the buffer
* @param {numnber} currenttime
* the current time of the player
* @param {number} playbackrate
* the current playback rate of the player. defaults to 1.
* @return {number}
* time until the player has to start rebuffering in seconds.
* @function timeuntilrebuffer
*/
var timeuntilrebuffer = function timeuntilrebuffer(buffered, currenttime, playbackrate) {
if (playbackrate === void 0) {
playbackrate = 1;
}
var bufferedend = buffered.length ? buffered.end(buffered.length - 1) : 0;
return (bufferedend - currenttime) / playbackrate;
};
/**
* converts a timeranges object into an array representation
*
* @param {timeranges} timeranges
* @return {array}
*/
var timerangestoarray = function timerangestoarray(timeranges) {
var timerangeslist = [];
for (var i = 0; i < timeranges.length; i++) {
timerangeslist.push({
start: timeranges.start(i),
end: timeranges.end(i)
});
}
return timerangeslist;
};
/**
* determines if two time range objects are different.
*
* @param {timerange} a
* the first time range object to check
*
* @param {timerange} b
* the second time range object to check
*
* @return {boolean}
* whether the time range objects differ
*/
var israngedifferent = function israngedifferent(a, b) {
// same object
if (a === b) {
return false;
} // one or the other is undefined
if (!a && b || !b && a) {
return true;
} // length is different
if (a.length !== b.length) {
return true;
} // see if any start/end pair is different
for (var i = 0; i < a.length; i++) {
if (a.start(i) !== b.start(i) || a.end(i) !== b.end(i)) {
return true;
}
} // if the length and every pair is the same
// this is the same time range
return false;
};
var lastbufferedend = function lastbufferedend(a) {
if (!a || !a.length || !a.end) {
return;
}
return a.end(a.length - 1);
};
/**
* a utility function to add up the amount of time in a timerange
* after a specified starttime.
* ie:[[0, 10], [20, 40], [50, 60]] with a starttime 0
* would return 40 as there are 40s seconds after 0 in the timerange
*
* @param {timerange} range
* the range to check against
* @param {number} starttime
* the time in the time range that you should start counting from
*
* @return {number}
* the number of seconds in the buffer passed the specified time.
*/
var timeaheadof = function timeaheadof(range, starttime) {
var time = 0;
if (!range || !range.length) {
return time;
}
for (var i = 0; i < range.length; i++) {
var start = range.start(i);
var end = range.end(i); // starttime is after this range entirely
if (starttime > end) {
continue;
} // starttime is within this range
if (starttime > start && starttime <= end) {
time += end - starttime;
continue;
} // starttime is before this range.
time += end - start;
}
return time;
};
/**
* @file playlist.js
*
* playlist related utilities.
*/
var createtimerange = videojs.createtimerange;
/**
* get the duration of a segment, with special cases for
* llhls segments that do not have a duration yet.
*
* @param {object} playlist
* the playlist that the segment belongs to.
* @param {object} segment
* the segment to get a duration for.
*
* @return {number}
* the segment duration
*/
var segmentdurationwithparts = function segmentdurationwithparts(playlist, segment) {
// if this isn't a preload segment
// then we will have a segment duration that is accurate.
if (!segment.preload) {
return segment.duration;
} // otherwise we have to add up parts and preload hints
// to get an up to date duration.
var result = 0;
(segment.parts || []).foreach(function (p) {
result += p.duration;
}); // for preload hints we have to use parttargetduration
// as they won't even have a duration yet.
(segment.preloadhints || []).foreach(function (p) {
if (p.type === 'part') {
result += playlist.parttargetduration;
}
});
return result;
};
/**
* a function to get a combined list of parts and segments with durations
* and indexes.
*
* @param {playlist} playlist the playlist to get the list for.
*
* @return {array} the part/segment list.
*/
var getpartsandsegments = function getpartsandsegments(playlist) {
return (playlist.segments || []).reduce(function (acc, segment, si) {
if (segment.parts) {
segment.parts.foreach(function (part, pi) {
acc.push({
duration: part.duration,
segmentindex: si,
partindex: pi,
part: part,
segment: segment
});
});
} else {
acc.push({
duration: segment.duration,
segmentindex: si,
partindex: null,
segment: segment,
part: null
});
}
return acc;
}, []);
};
var getlastparts = function getlastparts(media) {
var lastsegment = media.segments && media.segments.length && media.segments[media.segments.length - 1];
return lastsegment && lastsegment.parts || [];
};
var getknownpartcount = function getknownpartcount(_ref) {
var preloadsegment = _ref.preloadsegment;
if (!preloadsegment) {
return;
}
var parts = preloadsegment.parts,
preloadhints = preloadsegment.preloadhints;
var partcount = (preloadhints || []).reduce(function (count, hint) {
return count + (hint.type === 'part' ? 1 : 0);
}, 0);
partcount += parts && parts.length ? parts.length : 0;
return partcount;
};
/**
* get the number of seconds to delay from the end of a
* live playlist.
*
* @param {playlist} master the master playlist
* @param {playlist} media the media playlist
* @return {number} the hold back in seconds.
*/
var liveedgedelay = function liveedgedelay(master, media) {
if (media.endlist) {
return 0;
} // dash suggestedpresentationdelay trumps everything
if (master && master.suggestedpresentationdelay) {
return master.suggestedpresentationdelay;
}
var hasparts = getlastparts(media).length > 0; // look for "part" delays from ll-hls first
if (hasparts && media.servercontrol && media.servercontrol.partholdback) {
return media.servercontrol.partholdback;
} else if (hasparts && media.parttargetduration) {
return media.parttargetduration * 3; // finally look for full segment delays
} else if (media.servercontrol && media.servercontrol.holdback) {
return media.servercontrol.holdback;
} else if (media.targetduration) {
return media.targetduration * 3;
}
return 0;
};
/**
* walk backward until we find a duration we can use
* or return a failure
*
* @param {playlist} playlist the playlist to walk through
* @param {number} endsequence the mediasequence to stop walking on
*/
var backwardduration = function backwardduration(playlist, endsequence) {
var result = 0;
var i = endsequence - playlist.mediasequence; // if a start time is available for segment immediately following
// the interval, use it
var segment = playlist.segments[i]; // walk backward until we find the latest segment with timeline
// information that is earlier than endsequence
if (segment) {
if (typeof segment.start !== 'undefined') {
return {
result: segment.start,
precise: true
};
}
if (typeof segment.end !== 'undefined') {
return {
result: segment.end - segment.duration,
precise: true
};
}
}
while (i--) {
segment = playlist.segments[i];
if (typeof segment.end !== 'undefined') {
return {
result: result + segment.end,
precise: true
};
}
result += segmentdurationwithparts(playlist, segment);
if (typeof segment.start !== 'undefined') {
return {
result: result + segment.start,
precise: true
};
}
}
return {
result: result,
precise: false
};
};
/**
* walk forward until we find a duration we can use
* or return a failure
*
* @param {playlist} playlist the playlist to walk through
* @param {number} endsequence the mediasequence to stop walking on
*/
var forwardduration = function forwardduration(playlist, endsequence) {
var result = 0;
var segment;
var i = endsequence - playlist.mediasequence; // walk forward until we find the earliest segment with timeline
// information
for (; i < playlist.segments.length; i++) {
segment = playlist.segments[i];
if (typeof segment.start !== 'undefined') {
return {
result: segment.start - result,
precise: true
};
}
result += segmentdurationwithparts(playlist, segment);
if (typeof segment.end !== 'undefined') {
return {
result: segment.end - result,
precise: true
};
}
} // indicate we didn't find a useful duration estimate
return {
result: -1,
precise: false
};
};
/**
* calculate the media duration from the segments associated with a
* playlist. the duration of a subinterval of the available segments
* may be calculated by specifying an end index.
*
* @param {object} playlist a media playlist object
* @param {number=} endsequence an exclusive upper boundary
* for the playlist. defaults to playlist length.
* @param {number} expired the amount of time that has dropped
* off the front of the playlist in a live scenario
* @return {number} the duration between the first available segment
* and end index.
*/
var intervalduration = function intervalduration(playlist, endsequence, expired) {
if (typeof endsequence === 'undefined') {
endsequence = playlist.mediasequence + playlist.segments.length;
}
if (endsequence < playlist.mediasequence) {
return 0;
} // do a backward walk to estimate the duration
var backward = backwardduration(playlist, endsequence);
if (backward.precise) {
// if we were able to base our duration estimate on timing
// information provided directly from the media source, return
// it
return backward.result;
} // walk forward to see if a precise duration estimate can be made
// that way
var forward = forwardduration(playlist, endsequence);
if (forward.precise) {
// we found a segment that has been buffered and so it's
// position is known precisely
return forward.result;
} // return the less-precise, playlist-based duration estimate
return backward.result + expired;
};
/**
* calculates the duration of a playlist. if a start and end index
* are specified, the duration will be for the subset of the media
* timeline between those two indices. the total duration for live
* playlists is always infinity.
*
* @param {object} playlist a media playlist object
* @param {number=} endsequence an exclusive upper
* boundary for the playlist. defaults to the playlist media
* sequence number plus its length.
* @param {number=} expired the amount of time that has
* dropped off the front of the playlist in a live scenario
* @return {number} the duration between the start index and end
* index.
*/
var duration = function duration(playlist, endsequence, expired) {
if (!playlist) {
return 0;
}
if (typeof expired !== 'number') {
expired = 0;
} // if a slice of the total duration is not requested, use
// playlist-level duration indicators when they're present
if (typeof endsequence === 'undefined') {
// if present, use the duration specified in the playlist
if (playlist.totalduration) {
return playlist.totalduration;
} // duration should be infinity for live playlists
if (!playlist.endlist) {
return global_window__webpack_imported_module_0___default.a.infinity;
}
} // calculate the total duration based on the segment durations
return intervalduration(playlist, endsequence, expired);
};
/**
* calculate the time between two indexes in the current playlist
* neight the start- nor the end-index need to be within the current
* playlist in which case, the targetduration of the playlist is used
* to approximate the durations of the segments
*
* @param {array} options.durationlist list to iterate over for durations.
* @param {number} options.defaultduration duration to use for elements before or after the durationlist
* @param {number} options.startindex partsandsegments index to start
* @param {number} options.endindex partsandsegments index to end.
* @return {number} the number of seconds between startindex and endindex
*/
var sumdurations = function sumdurations(_ref2) {
var defaultduration = _ref2.defaultduration,
durationlist = _ref2.durationlist,
startindex = _ref2.startindex,
endindex = _ref2.endindex;
var durations = 0;
if (startindex > endindex) {
var _ref3 = [endindex, startindex];
startindex = _ref3[0];
endindex = _ref3[1];
}
if (startindex < 0) {
for (var i = startindex; i < math.min(0, endindex); i++) {
durations += defaultduration;
}
startindex = 0;
}
for (var _i = startindex; _i < endindex; _i++) {
durations += durationlist[_i].duration;
}
return durations;
};
/**
* calculates the playlist end time
*
* @param {object} playlist a media playlist object
* @param {number=} expired the amount of time that has
* dropped off the front of the playlist in a live scenario
* @param {boolean|false} usesafeliveend a boolean value indicating whether or not the
* playlist end calculation should consider the safe live end
* (truncate the playlist end by three segments). this is normally
* used for calculating the end of the playlist's seekable range.
* this takes into account the value of liveedgepadding.
* setting liveedgepadding to 0 is equivalent to setting this to false.
* @param {number} liveedgepadding a number indicating how far from the end of the playlist we should be in seconds.
* if this is provided, it is used in the safe live end calculation.
* setting usesafeliveend=false or liveedgepadding=0 are equivalent.
* corresponds to suggestedpresentationdelay in dash manifests.
* @return {number} the end time of playlist
* @function playlistend
*/
var playlistend = function playlistend(playlist, expired, usesafeliveend, liveedgepadding) {
if (!playlist || !playlist.segments) {
return null;
}
if (playlist.endlist) {
return duration(playlist);
}
if (expired === null) {
return null;
}
expired = expired || 0;
var lastsegmentendtime = intervalduration(playlist, playlist.mediasequence + playlist.segments.length, expired);
if (usesafeliveend) {
liveedgepadding = typeof liveedgepadding === 'number' ? liveedgepadding : liveedgedelay(null, playlist);
lastsegmentendtime -= liveedgepadding;
} // don't return a time less than zero
return math.max(0, lastsegmentendtime);
};
/**
* calculates the interval of time that is currently seekable in a
* playlist. the returned time ranges are relative to the earliest
* moment in the specified playlist that is still available. a full
* seekable implementation for live streams would need to offset
* these values by the duration of content that has expired from the
* stream.
*
* @param {object} playlist a media playlist object
* dropped off the front of the playlist in a live scenario
* @param {number=} expired the amount of time that has
* dropped off the front of the playlist in a live scenario
* @param {number} liveedgepadding how far from the end of the playlist we should be in seconds.
* corresponds to suggestedpresentationdelay in dash manifests.
* @return {timeranges} the periods of time that are valid targets
* for seeking
*/
var seekable = function seekable(playlist, expired, liveedgepadding) {
var usesafeliveend = true;
var seekablestart = expired || 0;
var seekableend = playlistend(playlist, expired, usesafeliveend, liveedgepadding);
if (seekableend === null) {
return createtimerange();
}
return createtimerange(seekablestart, seekableend);
};
/**
* determine the index and estimated starting time of the segment that
* contains a specified playback position in a media playlist.
*
* @param {object} options.playlist the media playlist to query
* @param {number} options.currenttime the number of seconds since the earliest
* possible position to determine the containing segment for
* @param {number} options.starttime the time when the segment/part starts
* @param {number} options.startingsegmentindex the segment index to start looking at.
* @param {number?} [options.startingpartindex] the part index to look at within the segment.
*
* @return {object} an object with partindex, segmentindex, and starttime.
*/
var getmediainfofortime = function getmediainfofortime(_ref4) {
var playlist = _ref4.playlist,
currenttime = _ref4.currenttime,
startingsegmentindex = _ref4.startingsegmentindex,
startingpartindex = _ref4.startingpartindex,
starttime = _ref4.starttime,
experimentalexactmanifesttimings = _ref4.experimentalexactmanifesttimings;
var time = currenttime - starttime;
var partsandsegments = getpartsandsegments(playlist);
var startindex = 0;
for (var i = 0; i < partsandsegments.length; i++) {
var partandsegment = partsandsegments[i];
if (startingsegmentindex !== partandsegment.segmentindex) {
continue;
} // skip this if part index does not match.
if (typeof startingpartindex === 'number' && typeof partandsegment.partindex === 'number' && startingpartindex !== partandsegment.partindex) {
continue;
}
startindex = i;
break;
}
if (time < 0) {
// walk backward from startindex in the playlist, adding durations
// until we find a segment that contains `time` and return it
if (startindex > 0) {
for (var _i2 = startindex - 1; _i2 >= 0; _i2--) {
var _partandsegment = partsandsegments[_i2];
time += _partandsegment.duration;
if (experimentalexactmanifesttimings) {
if (time < 0) {
continue;
}
} else if (time + time_fudge_factor <= 0) {
continue;
}
return {
partindex: _partandsegment.partindex,
segmentindex: _partandsegment.segmentindex,
starttime: starttime - sumdurations({
defaultduration: playlist.targetduration,
durationlist: partsandsegments,
startindex: startindex,
endindex: _i2
})
};
}
} // we were unable to find a good segment within the playlist
// so select the first segment
return {
partindex: partsandsegments[0] && partsandsegments[0].partindex || null,
segmentindex: partsandsegments[0] && partsandsegments[0].segmentindex || 0,
starttime: currenttime
};
} // when startindex is negative, we first walk forward to first segment
// adding target durations. if we "run out of time" before getting to
// the first segment, return the first segment
if (startindex < 0) {
for (var _i3 = startindex; _i3 < 0; _i3++) {
time -= playlist.targetduration;
if (time < 0) {
return {
partindex: partsandsegments[0] && partsandsegments[0].partindex || null,
segmentindex: partsandsegments[0] && partsandsegments[0].segmentindex || 0,
starttime: currenttime
};
}
}
startindex = 0;
} // walk forward from startindex in the playlist, subtracting durations
// until we find a segment that contains `time` and return it
for (var _i4 = startindex; _i4 < partsandsegments.length; _i4++) {
var _partandsegment2 = partsandsegments[_i4];
time -= _partandsegment2.duration;
if (experimentalexactmanifesttimings) {
if (time > 0) {
continue;
}
} else if (time - time_fudge_factor >= 0) {
continue;
}
return {
partindex: _partandsegment2.partindex,
segmentindex: _partandsegment2.segmentindex,
starttime: starttime + sumdurations({
defaultduration: playlist.targetduration,
durationlist: partsandsegments,
startindex: startindex,
endindex: _i4
})
};
} // we are out of possible candidates so load the last one...
return {
segmentindex: partsandsegments[partsandsegments.length - 1].segmentindex,
partindex: partsandsegments[partsandsegments.length - 1].partindex,
starttime: currenttime
};
};
/**
* check whether the playlist is blacklisted or not.
*
* @param {object} playlist the media playlist object
* @return {boolean} whether the playlist is blacklisted or not
* @function isblacklisted
*/
var isblacklisted = function isblacklisted(playlist) {
return playlist.excludeuntil && playlist.excludeuntil > date.now();
};
/**
* check whether the playlist is compatible with current playback configuration or has
* been blacklisted permanently for being incompatible.
*
* @param {object} playlist the media playlist object
* @return {boolean} whether the playlist is incompatible or not
* @function isincompatible
*/
var isincompatible = function isincompatible(playlist) {
return playlist.excludeuntil && playlist.excludeuntil === infinity;
};
/**
* check whether the playlist is enabled or not.
*
* @param {object} playlist the media playlist object
* @return {boolean} whether the playlist is enabled or not
* @function isenabled
*/
var isenabled = function isenabled(playlist) {
var blacklisted = isblacklisted(playlist);
return !playlist.disabled && !blacklisted;
};
/**
* check whether the playlist has been manually disabled through the representations api.
*
* @param {object} playlist the media playlist object
* @return {boolean} whether the playlist is disabled manually or not
* @function isdisabled
*/
var isdisabled = function isdisabled(playlist) {
return playlist.disabled;
};
/**
* returns whether the current playlist is an aes encrypted hls stream
*
* @return {boolean} true if it's an aes encrypted hls stream
*/
var isaes = function isaes(media) {
for (var i = 0; i < media.segments.length; i++) {
if (media.segments[i].key) {
return true;
}
}
return false;
};
/**
* checks if the playlist has a value for the specified attribute
*
* @param {string} attr
* attribute to check for
* @param {object} playlist
* the media playlist object
* @return {boolean}
* whether the playlist contains a value for the attribute or not
* @function hasattribute
*/
var hasattribute = function hasattribute(attr, playlist) {
return playlist.attributes && playlist.attributes[attr];
};
/**
* estimates the time required to complete a segment download from the specified playlist
*
* @param {number} segmentduration
* duration of requested segment
* @param {number} bandwidth
* current measured bandwidth of the player
* @param {object} playlist
* the media playlist object
* @param {number=} bytesreceived
* number of bytes already received for the request. defaults to 0
* @return {number|nan}
* the estimated time to request the segment. nan if bandwidth information for
* the given playlist is unavailable
* @function estimatesegmentrequesttime
*/
var estimatesegmentrequesttime = function estimatesegmentrequesttime(segmentduration, bandwidth, playlist, bytesreceived) {
if (bytesreceived === void 0) {
bytesreceived = 0;
}
if (!hasattribute('bandwidth', playlist)) {
return nan;
}
var size = segmentduration * playlist.attributes.bandwidth;
return (size - bytesreceived * 8) / bandwidth;
};
/*
* returns whether the current playlist is the lowest rendition
*
* @return {boolean} true if on lowest rendition
*/
var islowestenabledrendition = function islowestenabledrendition(master, media) {
if (master.playlists.length === 1) {
return true;
}
var currentbandwidth = media.attributes.bandwidth || number.max_value;
return master.playlists.filter(function (playlist) {
if (!isenabled(playlist)) {
return false;
}
return (playlist.attributes.bandwidth || 0) < currentbandwidth;
}).length === 0;
};
var playlistmatch = function playlistmatch(a, b) {
// both playlits are null
// or only one playlist is non-null
// no match
if (!a && !b || !a && b || a && !b) {
return false;
} // playlist objects are the same, match
if (a === b) {
return true;
} // first try to use id as it should be the most
// accurate
if (a.id && b.id && a.id === b.id) {
return true;
} // next try to use resloveduri as it should be the
// second most accurate.
if (a.resolveduri && b.resolveduri && a.resolveduri === b.resolveduri) {
return true;
} // finally try to use uri as it should be accurate
// but might miss a few cases for relative uris
if (a.uri && b.uri && a.uri === b.uri) {
return true;
}
return false;
};
var someaudiovariant = function someaudiovariant(master, callback) {
var audio = master && master.mediagroups && master.mediagroups.audio || {};
var found = false;
for (var groupname in audio) {
for (var label in audio[groupname]) {
found = callback(audio[groupname][label]);
if (found) {
break;
}
}
if (found) {
break;
}
}
return !!found;
};
var isaudioonly = function isaudioonly(master) {
// we are audio only if we have no main playlists but do
// have media group playlists.
if (!master || !master.playlists || !master.playlists.length) {
// without audio variants or playlists this
// is not an audio only master.
var found = someaudiovariant(master, function (variant) {
return variant.playlists && variant.playlists.length || variant.uri;
});
return found;
} // if every playlist has only an audio codec it is audio only
var _loop = function _loop(i) {
var playlist = master.playlists[i];
var codecs = playlist.attributes && playlist.attributes.codecs; // all codecs are audio, this is an audio playlist.
if (codecs && codecs.split(',').every(function (c) {
return object(_videojs_vhs_utils_es_codecs_js__webpack_imported_module_13__[/* isaudiocodec */ "f"])(c);
})) {
return "continue";
} // playlist is in an audio group it is audio only
var found = someaudiovariant(master, function (variant) {
return playlistmatch(playlist, variant);
});
if (found) {
return "continue";
} // if we make it here this playlist isn't audio and we
// are not audio only
return {
v: false
};
};
for (var i = 0; i < master.playlists.length; i++) {
var _ret = _loop(i);
if (_ret === "continue") continue;
if (typeof _ret === "object") return _ret.v;
} // if we make it past every playlist without returning, then
// this is an audio only playlist.
return true;
}; // exports
var playlist = {
liveedgedelay: liveedgedelay,
duration: duration,
seekable: seekable,
getmediainfofortime: getmediainfofortime,
isenabled: isenabled,
isdisabled: isdisabled,
isblacklisted: isblacklisted,
isincompatible: isincompatible,
playlistend: playlistend,
isaes: isaes,
hasattribute: hasattribute,
estimatesegmentrequesttime: estimatesegmentrequesttime,
islowestenabledrendition: islowestenabledrendition,
isaudioonly: isaudioonly,
playlistmatch: playlistmatch,
segmentdurationwithparts: segmentdurationwithparts
};
var log = videojs.log;
var createplaylistid = function createplaylistid(index, uri) {
return index + "-" + uri;
}; // default function for creating a group id
var groupid = function groupid(type, group, label) {
return "placeholder-uri-" + type + "-" + group + "-" + label;
};
/**
* parses a given m3u8 playlist
*
* @param {function} [onwarn]
* a function to call when the parser triggers a warning event.
* @param {function} [oninfo]
* a function to call when the parser triggers an info event.
* @param {string} manifeststring
* the downloaded manifest string
* @param {object[]} [customtagparsers]
* an array of custom tag parsers for the m3u8-parser instance
* @param {object[]} [customtagmappers]
* an array of custom tag mappers for the m3u8-parser instance
* @param {boolean} [experimentalllhls=false]
* whether to keep ll-hls features in the manifest after parsing.
* @return {object}
* the manifest object
*/
var parsemanifest = function parsemanifest(_ref) {
var onwarn = _ref.onwarn,
oninfo = _ref.oninfo,
manifeststring = _ref.manifeststring,
_ref$customtagparsers = _ref.customtagparsers,
customtagparsers = _ref$customtagparsers === void 0 ? [] : _ref$customtagparsers,
_ref$customtagmappers = _ref.customtagmappers,
customtagmappers = _ref$customtagmappers === void 0 ? [] : _ref$customtagmappers,
experimentalllhls = _ref.experimentalllhls;
var parser = new m3u8_parser__webpack_imported_module_12__[/* parser */ "a"]();
if (onwarn) {
parser.on('warn', onwarn);
}
if (oninfo) {
parser.on('info', oninfo);
}
customtagparsers.foreach(function (customparser) {
return parser.addparser(customparser);
});
customtagmappers.foreach(function (mapper) {
return parser.addtagmapper(mapper);
});
parser.push(manifeststring);
parser.end();
var manifest = parser.manifest; // remove llhls features from the parsed manifest
// if we don't want llhls support.
if (!experimentalllhls) {
['preloadsegment', 'skip', 'servercontrol', 'renditionreports', 'partinf', 'parttargetduration'].foreach(function (k) {
if (manifest.hasownproperty(k)) {
delete manifest[k];
}
});
if (manifest.segments) {
manifest.segments.foreach(function (segment) {
['parts', 'preloadhints'].foreach(function (k) {
if (segment.hasownproperty(k)) {
delete segment[k];
}
});
});
}
}
if (!manifest.targetduration) {
var targetduration = 10;
if (manifest.segments && manifest.segments.length) {
targetduration = manifest.segments.reduce(function (acc, s) {
return math.max(acc, s.duration);
}, 0);
}
if (onwarn) {
onwarn("manifest has no targetduration defaulting to " + targetduration);
}
manifest.targetduration = targetduration;
}
var parts = getlastparts(manifest);
if (parts.length && !manifest.parttargetduration) {
var parttargetduration = parts.reduce(function (acc, p) {
return math.max(acc, p.duration);
}, 0);
if (onwarn) {
onwarn("manifest has no parttargetduration defaulting to " + parttargetduration);
log.error('ll-hls manifest has parts but lacks required #ext-x-part-inf:part-target value. see https://datatracker.ietf.org/doc/html/draft-pantos-hls-rfc8216bis-09#section-4.4.3.7. playback is not guaranteed.');
}
manifest.parttargetduration = parttargetduration;
}
return manifest;
};
/**
* loops through all supported media groups in master and calls the provided
* callback for each group
*
* @param {object} master
* the parsed master manifest object
* @param {function} callback
* callback to call for each media group
*/
var foreachmediagroup = function foreachmediagroup(master, callback) {
if (!master.mediagroups) {
return;
}
['audio', 'subtitles'].foreach(function (mediatype) {
if (!master.mediagroups[mediatype]) {
return;
}
for (var groupkey in master.mediagroups[mediatype]) {
for (var labelkey in master.mediagroups[mediatype][groupkey]) {
var mediaproperties = master.mediagroups[mediatype][groupkey][labelkey];
callback(mediaproperties, mediatype, groupkey, labelkey);
}
}
});
};
/**
* adds properties and attributes to the playlist to keep consistent functionality for
* playlists throughout vhs.
*
* @param {object} config
* arguments object
* @param {object} config.playlist
* the media playlist
* @param {string} [config.uri]
* the uri to the media playlist (if media playlist is not from within a master
* playlist)
* @param {string} id
* id to use for the playlist
*/
var setupmediaplaylist = function setupmediaplaylist(_ref2) {
var playlist = _ref2.playlist,
uri = _ref2.uri,
id = _ref2.id;
playlist.id = id;
playlist.playlisterrors_ = 0;
if (uri) {
// for media playlists, m3u8-parser does not have access to a uri, as hls media
// playlists do not contain their own source uri, but one is needed for consistency in
// vhs.
playlist.uri = uri;
} // for hls master playlists, even though certain attributes must be defined, the
// stream may still be played without them.
// for hls media playlists, m3u8-parser does not attach an attributes object to the
// manifest.
//
// to avoid undefined reference errors through the project, and make the code easier
// to write/read, add an empty attributes object for these cases.
playlist.attributes = playlist.attributes || {};
};
/**
* adds id, resolveduri, and attributes properties to each playlist of the master, where
* necessary. in addition, creates playlist ids for each playlist and adds playlist id to
* playlist references to the playlists array.
*
* @param {object} master
* the master playlist
*/
var setupmediaplaylists = function setupmediaplaylists(master) {
var i = master.playlists.length;
while (i--) {
var playlist = master.playlists[i];
setupmediaplaylist({
playlist: playlist,
id: createplaylistid(i, playlist.uri)
});
playlist.resolveduri = resolveurl(master.uri, playlist.uri);
master.playlists[playlist.id] = playlist; // uri reference added for backwards compatibility
master.playlists[playlist.uri] = playlist; // although the spec states an #ext-x-stream-inf tag must have a bandwidth attribute,
// the stream can be played without it. although an attributes property may have been
// added to the playlist to prevent undefined references, issue a warning to fix the
// manifest.
if (!playlist.attributes.bandwidth) {
log.warn('invalid playlist stream-inf detected. missing bandwidth attribute.');
}
}
};
/**
* adds resolveduri properties to each media group.
*
* @param {object} master
* the master playlist
*/
var resolvemediagroupuris = function resolvemediagroupuris(master) {
foreachmediagroup(master, function (properties) {
if (properties.uri) {
properties.resolveduri = resolveurl(master.uri, properties.uri);
}
});
};
/**
* creates a master playlist wrapper to insert a sole media playlist into.
*
* @param {object} media
* media playlist
* @param {string} uri
* the media uri
*
* @return {object}
* master playlist
*/
var masterformedia = function masterformedia(media, uri) {
var id = createplaylistid(0, uri);
var master = {
mediagroups: {
'audio': {},
'video': {},
'closed-captions': {},
'subtitles': {}
},
uri: global_window__webpack_imported_module_0___default.a.location.href,
resolveduri: global_window__webpack_imported_module_0___default.a.location.href,
playlists: [{
uri: uri,
id: id,
resolveduri: uri,
// m3u8-parser does not attach an attributes property to media playlists so make
// sure that the property is attached to avoid undefined reference errors
attributes: {}
}]
}; // set up id reference
master.playlists[id] = master.playlists[0]; // uri reference added for backwards compatibility
master.playlists[uri] = master.playlists[0];
return master;
};
/**
* does an in-place update of the master manifest to add updated playlist uri references
* as well as other properties needed by vhs that aren't included by the parser.
*
* @param {object} master
* master manifest object
* @param {string} uri
* the source uri
* @param {function} creategroupid
* a function to determine how to create the groupid for mediagroups
*/
var addpropertiestomaster = function addpropertiestomaster(master, uri, creategroupid) {
if (creategroupid === void 0) {
creategroupid = groupid;
}
master.uri = uri;
for (var i = 0; i < master.playlists.length; i++) {
if (!master.playlists[i].uri) {
// set up phony uris for the playlists since playlists are referenced by their uris
// throughout vhs, but some formats (e.g., dash) don't have external uris
// todo: consider adding dummy uris in mpd-parser
var phonyuri = "placeholder-uri-" + i;
master.playlists[i].uri = phonyuri;
}
}
var audioonlymaster = isaudioonly(master);
foreachmediagroup(master, function (properties, mediatype, groupkey, labelkey) {
// add a playlist array under properties
if (!properties.playlists || !properties.playlists.length) {
// if the manifest is audio only and this media group does not have a uri, check
// if the media group is located in the main list of playlists. if it is, don't add
// placeholder properties as it shouldn't be considered an alternate audio track.
if (audioonlymaster && mediatype === 'audio' && !properties.uri) {
for (var _i = 0; _i < master.playlists.length; _i++) {
var p = master.playlists[_i];
if (p.attributes && p.attributes.audio && p.attributes.audio === groupkey) {
return;
}
}
}
properties.playlists = [_babel_runtime_helpers_extends__webpack_imported_module_2___default()({}, properties)];
}
properties.playlists.foreach(function (p, i) {
var groupid = creategroupid(mediatype, groupkey, labelkey, p);
var id = createplaylistid(i, groupid);
if (p.uri) {
p.resolveduri = p.resolveduri || resolveurl(master.uri, p.uri);
} else {
// deprecated, this has been added to prevent a breaking change.
// previously we only ever had a single media group playlist, so
// we mark the first playlist uri without prepending the index as we used to
// ideally we would do all of the playlists the same way.
p.uri = i === 0 ? groupid : id; // don't resolve a placeholder uri to an absolute url, just use
// the placeholder again
p.resolveduri = p.uri;
}
p.id = p.id || id; // add an empty attributes object, all playlists are
// expected to have this.
p.attributes = p.attributes || {}; // setup id and uri references (uri for backwards compatibility)
master.playlists[p.id] = p;
master.playlists[p.uri] = p;
});
});
setupmediaplaylists(master);
resolvemediagroupuris(master);
};
var mergeoptions$2 = videojs.mergeoptions,
eventtarget$1 = videojs.eventtarget;
var addllhlsquerydirectives = function addllhlsquerydirectives(uri, media) {
if (media.endlist || !media.servercontrol) {
return uri;
}
var parameters = {};
if (media.servercontrol.canblockreload) {
var preloadsegment = media.preloadsegment; // next msn is a zero based value, length is not.
var nextmsn = media.mediasequence + media.segments.length; // if preload segment has parts then it is likely
// that we are going to request a part of that preload segment.
// the logic below is used to determine that.
if (preloadsegment) {
var parts = preloadsegment.parts || []; // _hls_part is a zero based index
var nextpart = getknownpartcount(media) - 1; // if nextpart is > -1 and not equal to just the
// length of parts, then we know we had part preload hints
// and we need to add the _hls_part= query
if (nextpart > -1 && nextpart !== parts.length - 1) {
// add existing parts to our preload hints
// eslint-disable-next-line
parameters._hls_part = nextpart;
} // this if statement makes sure that we request the msn
// of the preload segment if:
// 1. the preload segment had parts (and was not yet a full segment)
// but was added to our segments array
// 2. the preload segment had preload hints for parts that are not in
// the manifest yet.
// in all other cases we want the segment after the preload segment
// which will be given by using media.segments.length because it is 1 based
// rather than 0 based.
if (nextpart > -1 || parts.length) {
nextmsn--;
}
} // add _hls_msn= in front of any _hls_part query
// eslint-disable-next-line
parameters._hls_msn = nextmsn;
}
if (media.servercontrol && media.servercontrol.canskipuntil) {
// add _hls_skip= infront of all other queries.
// eslint-disable-next-line
parameters._hls_skip = media.servercontrol.canskipdateranges ? 'v2' : 'yes';
}
if (object.keys(parameters).length) {
var parseduri = new global_window__webpack_imported_module_0___default.a.url(uri);
['_hls_skip', '_hls_msn', '_hls_part'].foreach(function (name) {
if (!parameters.hasownproperty(name)) {
return;
}
parseduri.searchparams.set(name, parameters[name]);
});
uri = parseduri.tostring();
}
return uri;
};
/**
* returns a new segment object with properties and
* the parts array merged.
*
* @param {object} a the old segment
* @param {object} b the new segment
*
* @return {object} the merged segment
*/
var updatesegment = function updatesegment(a, b) {
if (!a) {
return b;
}
var result = mergeoptions$2(a, b); // if only the old segment has preload hints
// and the new one does not, remove preload hints.
if (a.preloadhints && !b.preloadhints) {
delete result.preloadhints;
} // if only the old segment has parts
// then the parts are no longer valid
if (a.parts && !b.parts) {
delete result.parts; // if both segments have parts
// copy part propeties from the old segment
// to the new one.
} else if (a.parts && b.parts) {
for (var i = 0; i < b.parts.length; i++) {
if (a.parts && a.parts[i]) {
result.parts[i] = mergeoptions$2(a.parts[i], b.parts[i]);
}
}
} // set skipped to false for segments that have
// have had information merged from the old segment.
if (!a.skipped && b.skipped) {
result.skipped = false;
} // set preload to false for segments that have
// had information added in the new segment.
if (a.preload && !b.preload) {
result.preload = false;
}
return result;
};
/**
* returns a new array of segments that is the result of merging
* properties from an older list of segments onto an updated
* list. no properties on the updated playlist will be ovewritten.
*
* @param {array} original the outdated list of segments
* @param {array} update the updated list of segments
* @param {number=} offset the index of the first update
* segment in the original segment list. for non-live playlists,
* this should always be zero and does not need to be
* specified. for live playlists, it should be the difference
* between the media sequence numbers in the original and updated
* playlists.
* @return {array} a list of merged segment objects
*/
var updatesegments = function updatesegments(original, update, offset) {
var oldsegments = original.slice();
var newsegments = update.slice();
offset = offset || 0;
var result = [];
var currentmap;
for (var newindex = 0; newindex < newsegments.length; newindex++) {
var oldsegment = oldsegments[newindex + offset];
var newsegment = newsegments[newindex];
if (oldsegment) {
currentmap = oldsegment.map || currentmap;
result.push(updatesegment(oldsegment, newsegment));
} else {
// carry over map to new segment if it is missing
if (currentmap && !newsegment.map) {
newsegment.map = currentmap;
}
result.push(newsegment);
}
}
return result;
};
var resolvesegmenturis = function resolvesegmenturis(segment, baseuri) {
// preloadsegment will not have a uri at all
// as the segment isn't actually in the manifest yet, only parts
if (!segment.resolveduri && segment.uri) {
segment.resolveduri = resolveurl(baseuri, segment.uri);
}
if (segment.key && !segment.key.resolveduri) {
segment.key.resolveduri = resolveurl(baseuri, segment.key.uri);
}
if (segment.map && !segment.map.resolveduri) {
segment.map.resolveduri = resolveurl(baseuri, segment.map.uri);
}
if (segment.map && segment.map.key && !segment.map.key.resolveduri) {
segment.map.key.resolveduri = resolveurl(baseuri, segment.map.key.uri);
}
if (segment.parts && segment.parts.length) {
segment.parts.foreach(function (p) {
if (p.resolveduri) {
return;
}
p.resolveduri = resolveurl(baseuri, p.uri);
});
}
if (segment.preloadhints && segment.preloadhints.length) {
segment.preloadhints.foreach(function (p) {
if (p.resolveduri) {
return;
}
p.resolveduri = resolveurl(baseuri, p.uri);
});
}
};
var getallsegments = function getallsegments(media) {
var segments = media.segments || [];
var preloadsegment = media.preloadsegment; // a preloadsegment with only preloadhints is not currently
// a usable segment, only include a preloadsegment that has
// parts.
if (preloadsegment && preloadsegment.parts && preloadsegment.parts.length) {
// if preloadhints has a map that means that the
// init segment is going to change. we cannot use any of the parts
// from this preload segment.
if (preloadsegment.preloadhints) {
for (var i = 0; i < preloadsegment.preloadhints.length; i++) {
if (preloadsegment.preloadhints[i].type === 'map') {
return segments;
}
}
} // set the duration for our preload segment to target duration.
preloadsegment.duration = media.targetduration;
preloadsegment.preload = true;
segments.push(preloadsegment);
}
return segments;
}; // consider the playlist unchanged if the playlist object is the same or
// the number of segments is equal, the media sequence number is unchanged,
// and this playlist hasn't become the end of the playlist
var isplaylistunchanged = function isplaylistunchanged(a, b) {
return a === b || a.segments && b.segments && a.segments.length === b.segments.length && a.endlist === b.endlist && a.mediasequence === b.mediasequence && a.preloadsegment === b.preloadsegment;
};
/**
* returns a new master playlist that is the result of merging an
* updated media playlist into the original version. if the
* updated media playlist does not match any of the playlist
* entries in the original master playlist, null is returned.
*
* @param {object} master a parsed master m3u8 object
* @param {object} media a parsed media m3u8 object
* @return {object} a new object that represents the original
* master playlist with the updated media playlist merged in, or
* null if the merge produced no change.
*/
var updatemaster$1 = function updatemaster(master, newmedia, unchangedcheck) {
if (unchangedcheck === void 0) {
unchangedcheck = isplaylistunchanged;
}
var result = mergeoptions$2(master, {});
var oldmedia = result.playlists[newmedia.id];
if (!oldmedia) {
return null;
}
if (unchangedcheck(oldmedia, newmedia)) {
return null;
}
newmedia.segments = getallsegments(newmedia);
var mergedplaylist = mergeoptions$2(oldmedia, newmedia); // always use the new media's preload segment
if (mergedplaylist.preloadsegment && !newmedia.preloadsegment) {
delete mergedplaylist.preloadsegment;
} // if the update could overlap existing segment information, merge the two segment lists
if (oldmedia.segments) {
if (newmedia.skip) {
newmedia.segments = newmedia.segments || []; // add back in objects for skipped segments, so that we merge
// old properties into the new segments
for (var i = 0; i < newmedia.skip.skippedsegments; i++) {
newmedia.segments.unshift({
skipped: true
});
}
}
mergedplaylist.segments = updatesegments(oldmedia.segments, newmedia.segments, newmedia.mediasequence - oldmedia.mediasequence);
} // resolve any segment uris to prevent us from having to do it later
mergedplaylist.segments.foreach(function (segment) {
resolvesegmenturis(segment, mergedplaylist.resolveduri);
}); // todo right now in the playlists array there are two references to each playlist, one
// that is referenced by index, and one by uri. the index reference may no longer be
// necessary.
for (var _i = 0; _i < result.playlists.length; _i++) {
if (result.playlists[_i].id === newmedia.id) {
result.playlists[_i] = mergedplaylist;
}
}
result.playlists[newmedia.id] = mergedplaylist; // uri reference added for backwards compatibility
result.playlists[newmedia.uri] = mergedplaylist; // update media group playlist references.
foreachmediagroup(master, function (properties, mediatype, groupkey, labelkey) {
if (!properties.playlists) {
return;
}
for (var _i2 = 0; _i2 < properties.playlists.length; _i2++) {
if (newmedia.id === properties.playlists[_i2].id) {
properties.playlists[_i2] = mergedplaylist;
}
}
});
return result;
};
/**
* calculates the time to wait before refreshing a live playlist
*
* @param {object} media
* the current media
* @param {boolean} update
* true if there were any updates from the last refresh, false otherwise
* @return {number}
* the time in ms to wait before refreshing the live playlist
*/
var refreshdelay = function refreshdelay(media, update) {
var segments = media.segments || [];
var lastsegment = segments[segments.length - 1];
var lastpart = lastsegment && lastsegment.parts && lastsegment.parts[lastsegment.parts.length - 1];
var lastduration = lastpart && lastpart.duration || lastsegment && lastsegment.duration;
if (update && lastduration) {
return lastduration * 1000;
} // if the playlist is unchanged since the last reload or last segment duration
// cannot be determined, try again after half the target duration
return (media.parttargetduration || media.targetduration || 10) * 500;
};
/**
* load a playlist from a remote location
*
* @class playlistloader
* @extends stream
* @param {string|object} src url or object of manifest
* @param {boolean} withcredentials the withcredentials xhr option
* @class
*/
var playlistloader = /*#__pure__*/function (_eventtarget) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(playlistloader, _eventtarget);
function playlistloader(src, vhs, options) {
var _this;
if (options === void 0) {
options = {};
}
_this = _eventtarget.call(this) || this;
if (!src) {
throw new error('a non-empty playlist url or object is required');
}
_this.logger_ = logger('playlistloader');
var _options = options,
_options$withcredenti = _options.withcredentials,
withcredentials = _options$withcredenti === void 0 ? false : _options$withcredenti,
_options$handlemanife = _options.handlemanifestredirects,
handlemanifestredirects = _options$handlemanife === void 0 ? false : _options$handlemanife;
_this.src = src;
_this.vhs_ = vhs;
_this.withcredentials = withcredentials;
_this.handlemanifestredirects = handlemanifestredirects;
var vhsoptions = vhs.options_;
_this.customtagparsers = vhsoptions && vhsoptions.customtagparsers || [];
_this.customtagmappers = vhsoptions && vhsoptions.customtagmappers || [];
_this.experimentalllhls = vhsoptions && vhsoptions.experimentalllhls || false; // force experimentalllhls for ie 11
if (videojs.browser.ie_version) {
_this.experimentalllhls = false;
} // initialize the loader state
_this.state = 'have_nothing'; // live playlist staleness timeout
_this.handlemediaupdatetimeout_ = _this.handlemediaupdatetimeout_.bind(_babel_runtime_helpers_assertthisinitialized__webpack_imported_module_4___default()(_this));
_this.on('mediaupdatetimeout', _this.handlemediaupdatetimeout_);
return _this;
}
var _proto = playlistloader.prototype;
_proto.handlemediaupdatetimeout_ = function handlemediaupdatetimeout_() {
var _this2 = this;
if (this.state !== 'have_metadata') {
// only refresh the media playlist if no other activity is going on
return;
}
var media = this.media();
var uri = resolveurl(this.master.uri, media.uri);
if (this.experimentalllhls) {
uri = addllhlsquerydirectives(uri, media);
}
this.state = 'have_current_metadata';
this.request = this.vhs_.xhr({
uri: uri,
withcredentials: this.withcredentials
}, function (error, req) {
// disposed
if (!_this2.request) {
return;
}
if (error) {
return _this2.playlistrequesterror(_this2.request, _this2.media(), 'have_metadata');
}
_this2.havemetadata({
playliststring: _this2.request.responsetext,
url: _this2.media().uri,
id: _this2.media().id
});
});
};
_proto.playlistrequesterror = function playlistrequesterror(xhr, playlist, startingstate) {
var uri = playlist.uri,
id = playlist.id; // any in-flight request is now finished
this.request = null;
if (startingstate) {
this.state = startingstate;
}
this.error = {
playlist: this.master.playlists[id],
status: xhr.status,
message: "hls playlist request error at url: " + uri + ".",
responsetext: xhr.responsetext,
code: xhr.status >= 500 ? 4 : 2
};
this.trigger('error');
};
_proto.parsemanifest_ = function parsemanifest_(_ref) {
var _this3 = this;
var url = _ref.url,
manifeststring = _ref.manifeststring;
return parsemanifest({
onwarn: function onwarn(_ref2) {
var message = _ref2.message;
return _this3.logger_("m3u8-parser warn for " + url + ": " + message);
},
oninfo: function oninfo(_ref3) {
var message = _ref3.message;
return _this3.logger_("m3u8-parser info for " + url + ": " + message);
},
manifeststring: manifeststring,
customtagparsers: this.customtagparsers,
customtagmappers: this.customtagmappers,
experimentalllhls: this.experimentalllhls
});
}
/**
* update the playlist loader's state in response to a new or updated playlist.
*
* @param {string} [playliststring]
* playlist string (if playlistobject is not provided)
* @param {object} [playlistobject]
* playlist object (if playliststring is not provided)
* @param {string} url
* url of playlist
* @param {string} id
* id to use for playlist
*/
;
_proto.havemetadata = function havemetadata(_ref4) {
var playliststring = _ref4.playliststring,
playlistobject = _ref4.playlistobject,
url = _ref4.url,
id = _ref4.id; // any in-flight request is now finished
this.request = null;
this.state = 'have_metadata';
var playlist = playlistobject || this.parsemanifest_({
url: url,
manifeststring: playliststring
});
playlist.lastrequest = date.now();
setupmediaplaylist({
playlist: playlist,
uri: url,
id: id
}); // merge this playlist into the master
var update = updatemaster$1(this.master, playlist);
this.targetduration = playlist.parttargetduration || playlist.targetduration;
this.pendingmedia_ = null;
if (update) {
this.master = update;
this.media_ = this.master.playlists[id];
} else {
this.trigger('playlistunchanged');
}
this.updatemediaupdatetimeout_(refreshdelay(this.media(), !!update));
this.trigger('loadedplaylist');
}
/**
* abort any outstanding work and clean up.
*/
;
_proto.dispose = function dispose() {
this.trigger('dispose');
this.stoprequest();
global_window__webpack_imported_module_0___default.a.cleartimeout(this.mediaupdatetimeout);
global_window__webpack_imported_module_0___default.a.cleartimeout(this.finalrenditiontimeout);
this.off();
};
_proto.stoprequest = function stoprequest() {
if (this.request) {
var oldrequest = this.request;
this.request = null;
oldrequest.onreadystatechange = null;
oldrequest.abort();
}
}
/**
* when called without any arguments, returns the currently
* active media playlist. when called with a single argument,
* triggers the playlist loader to asynchronously switch to the
* specified media playlist. calling this method while the
* loader is in the have_nothing causes an error to be emitted
* but otherwise has no effect.
*
* @param {object=} playlist the parsed media playlist
* object to switch to
* @param {boolean=} shoulddelay whether we should delay the request by half target duration
*
* @return {playlist} the current loaded media
*/
;
_proto.media = function media(playlist, shoulddelay) {
var _this4 = this; // getter
if (!playlist) {
return this.media_;
} // setter
if (this.state === 'have_nothing') {
throw new error('cannot switch media playlist from ' + this.state);
} // find the playlist object if the target playlist has been
// specified by uri
if (typeof playlist === 'string') {
if (!this.master.playlists[playlist]) {
throw new error('unknown playlist uri: ' + playlist);
}
playlist = this.master.playlists[playlist];
}
global_window__webpack_imported_module_0___default.a.cleartimeout(this.finalrenditiontimeout);
if (shoulddelay) {
var delay = (playlist.parttargetduration || playlist.targetduration) / 2 * 1000 || 5 * 1000;
this.finalrenditiontimeout = global_window__webpack_imported_module_0___default.a.settimeout(this.media.bind(this, playlist, false), delay);
return;
}
var startingstate = this.state;
var mediachange = !this.media_ || playlist.id !== this.media_.id;
var masterplaylistref = this.master.playlists[playlist.id]; // switch to fully loaded playlists immediately
if (masterplaylistref && masterplaylistref.endlist || // handle the case of a playlist object (e.g., if using vhs-json with a resolved
// media playlist or, for the case of demuxed audio, a resolved audio media group)
playlist.endlist && playlist.segments.length) {
// abort outstanding playlist requests
if (this.request) {
this.request.onreadystatechange = null;
this.request.abort();
this.request = null;
}
this.state = 'have_metadata';
this.media_ = playlist; // trigger media change if the active media has been updated
if (mediachange) {
this.trigger('mediachanging');
if (startingstate === 'have_master') {
// the initial playlist was a master manifest, and the first media selected was
// also provided (in the form of a resolved playlist object) as part of the
// source object (rather than just a url). therefore, since the media playlist
// doesn't need to be requested, loadedmetadata won't trigger as part of the
// normal flow, and needs an explicit trigger here.
this.trigger('loadedmetadata');
} else {
this.trigger('mediachange');
}
}
return;
} // we update/set the timeout here so that live playlists
// that are not a media change will "start" the loader as expected.
// we expect that this function will start the media update timeout
// cycle again. this also prevents a playlist switch failure from
// causing us to stall during live.
this.updatemediaupdatetimeout_(refreshdelay(playlist, true)); // switching to the active playlist is a no-op
if (!mediachange) {
return;
}
this.state = 'switching_media'; // there is already an outstanding playlist request
if (this.request) {
if (playlist.resolveduri === this.request.url) {
// requesting to switch to the same playlist multiple times
// has no effect after the first
return;
}
this.request.onreadystatechange = null;
this.request.abort();
this.request = null;
} // request the new playlist
if (this.media_) {
this.trigger('mediachanging');
}
this.pendingmedia_ = playlist;
this.request = this.vhs_.xhr({
uri: playlist.resolveduri,
withcredentials: this.withcredentials
}, function (error, req) {
// disposed
if (!_this4.request) {
return;
}
playlist.lastrequest = date.now();
playlist.resolveduri = resolvemanifestredirect(_this4.handlemanifestredirects, playlist.resolveduri, req);
if (error) {
return _this4.playlistrequesterror(_this4.request, playlist, startingstate);
}
_this4.havemetadata({
playliststring: req.responsetext,
url: playlist.uri,
id: playlist.id
}); // fire loadedmetadata the first time a media playlist is loaded
if (startingstate === 'have_master') {
_this4.trigger('loadedmetadata');
} else {
_this4.trigger('mediachange');
}
});
}
/**
* pause loading of the playlist
*/
;
_proto.pause = function pause() {
if (this.mediaupdatetimeout) {
global_window__webpack_imported_module_0___default.a.cleartimeout(this.mediaupdatetimeout);
this.mediaupdatetimeout = null;
}
this.stoprequest();
if (this.state === 'have_nothing') {
// if we pause the loader before any data has been retrieved, its as if we never
// started, so reset to an unstarted state.
this.started = false;
} // need to restore state now that no activity is happening
if (this.state === 'switching_media') {
// if the loader was in the process of switching media, it should either return to
// have_master or have_metadata depending on if the loader has loaded a media
// playlist yet. this is determined by the existence of loader.media_
if (this.media_) {
this.state = 'have_metadata';
} else {
this.state = 'have_master';
}
} else if (this.state === 'have_current_metadata') {
this.state = 'have_metadata';
}
}
/**
* start loading of the playlist
*/
;
_proto.load = function load(shoulddelay) {
var _this5 = this;
if (this.mediaupdatetimeout) {
global_window__webpack_imported_module_0___default.a.cleartimeout(this.mediaupdatetimeout);
this.mediaupdatetimeout = null;
}
var media = this.media();
if (shoulddelay) {
var delay = media ? (media.parttargetduration || media.targetduration) / 2 * 1000 : 5 * 1000;
this.mediaupdatetimeout = global_window__webpack_imported_module_0___default.a.settimeout(function () {
_this5.mediaupdatetimeout = null;
_this5.load();
}, delay);
return;
}
if (!this.started) {
this.start();
return;
}
if (media && !media.endlist) {
this.trigger('mediaupdatetimeout');
} else {
this.trigger('loadedplaylist');
}
};
_proto.updatemediaupdatetimeout_ = function updatemediaupdatetimeout_(delay) {
var _this6 = this;
if (this.mediaupdatetimeout) {
global_window__webpack_imported_module_0___default.a.cleartimeout(this.mediaupdatetimeout);
this.mediaupdatetimeout = null;
} // we only have use mediaupdatetimeout for live playlists.
if (!this.media() || this.media().endlist) {
return;
}
this.mediaupdatetimeout = global_window__webpack_imported_module_0___default.a.settimeout(function () {
_this6.mediaupdatetimeout = null;
_this6.trigger('mediaupdatetimeout');
_this6.updatemediaupdatetimeout_(delay);
}, delay);
}
/**
* start loading of the playlist
*/
;
_proto.start = function start() {
var _this7 = this;
this.started = true;
if (typeof this.src === 'object') {
// in the case of an entirely constructed manifest object (meaning there's no actual
// manifest on a server), default the uri to the page's href
if (!this.src.uri) {
this.src.uri = global_window__webpack_imported_module_0___default.a.location.href;
} // resolveduri is added on internally after the initial request. since there's no
// request for pre-resolved manifests, add on resolveduri here.
this.src.resolveduri = this.src.uri; // since a manifest object was passed in as the source (instead of a url), the first
// request can be skipped (since the top level of the manifest, at a minimum, is
// already available as a parsed manifest object). however, if the manifest object
// represents a master playlist, some media playlists may need to be resolved before
// the starting segment list is available. therefore, go directly to setup of the
// initial playlist, and let the normal flow continue from there.
//
// note that the call to setup is asynchronous, as other sections of vhs may assume
// that the first request is asynchronous.
settimeout(function () {
_this7.setupinitialplaylist(_this7.src);
}, 0);
return;
} // request the specified url
this.request = this.vhs_.xhr({
uri: this.src,
withcredentials: this.withcredentials
}, function (error, req) {
// disposed
if (!_this7.request) {
return;
} // clear the loader's request reference
_this7.request = null;
if (error) {
_this7.error = {
status: req.status,
message: "hls playlist request error at url: " + _this7.src + ".",
responsetext: req.responsetext,
// media_err_network
code: 2
};
if (_this7.state === 'have_nothing') {
_this7.started = false;
}
return _this7.trigger('error');
}
_this7.src = resolvemanifestredirect(_this7.handlemanifestredirects, _this7.src, req);
var manifest = _this7.parsemanifest_({
manifeststring: req.responsetext,
url: _this7.src
});
_this7.setupinitialplaylist(manifest);
});
};
_proto.srcuri = function srcuri() {
return typeof this.src === 'string' ? this.src : this.src.uri;
}
/**
* given a manifest object that's either a master or media playlist, trigger the proper
* events and set the state of the playlist loader.
*
* if the manifest object represents a master playlist, `loadedplaylist` will be
* triggered to allow listeners to select a playlist. if none is selected, the loader
* will default to the first one in the playlists array.
*
* if the manifest object represents a media playlist, `loadedplaylist` will be
* triggered followed by `loadedmetadata`, as the only available playlist is loaded.
*
* in the case of a media playlist, a master playlist object wrapper with one playlist
* will be created so that all logic can handle playlists in the same fashion (as an
* assumed manifest object schema).
*
* @param {object} manifest
* the parsed manifest object
*/
;
_proto.setupinitialplaylist = function setupinitialplaylist(manifest) {
this.state = 'have_master';
if (manifest.playlists) {
this.master = manifest;
addpropertiestomaster(this.master, this.srcuri()); // if the initial master playlist has playlists wtih segments already resolved,
// then resolve uris in advance, as they are usually done after a playlist request,
// which may not happen if the playlist is resolved.
manifest.playlists.foreach(function (playlist) {
playlist.segments = getallsegments(playlist);
playlist.segments.foreach(function (segment) {
resolvesegmenturis(segment, playlist.resolveduri);
});
});
this.trigger('loadedplaylist');
if (!this.request) {
// no media playlist was specifically selected so start
// from the first listed one
this.media(this.master.playlists[0]);
}
return;
} // in order to support media playlists passed in as vhs-json, the case where the uri
// is not provided as part of the manifest should be considered, and an appropriate
// default used.
var uri = this.srcuri() || global_window__webpack_imported_module_0___default.a.location.href;
this.master = masterformedia(manifest, uri);
this.havemetadata({
playlistobject: manifest,
url: uri,
id: this.master.playlists[0].id
});
this.trigger('loadedmetadata');
};
return playlistloader;
}(eventtarget$1);
/**
* @file xhr.js
*/
var videojsxhr = videojs.xhr,
mergeoptions$1 = videojs.mergeoptions;
var callbackwrapper = function callbackwrapper(request, error, response, callback) {
var reqresponse = request.responsetype === 'arraybuffer' ? request.response : request.responsetext;
if (!error && reqresponse) {
request.responsetime = date.now();
request.roundtriptime = request.responsetime - request.requesttime;
request.bytesreceived = reqresponse.bytelength || reqresponse.length;
if (!request.bandwidth) {
request.bandwidth = math.floor(request.bytesreceived / request.roundtriptime * 8 * 1000);
}
}
if (response.headers) {
request.responseheaders = response.headers;
} // videojs.xhr now uses a specific code on the error
// object to signal that a request has timed out instead
// of setting a boolean on the request object
if (error && error.code === 'etimedout') {
request.timedout = true;
} // videojs.xhr no longer considers status codes outside of 200 and 0
// (for file uris) to be errors, but the old xhr did, so emulate that
// behavior. status 206 may be used in response to byterange requests.
if (!error && !request.aborted && response.statuscode !== 200 && response.statuscode !== 206 && response.statuscode !== 0) {
error = new error('xhr failed with a response of: ' + (request && (reqresponse || request.responsetext)));
}
callback(error, request);
};
var xhrfactory = function xhrfactory() {
var xhr = function xhrfunction(options, callback) {
// add a default timeout
options = mergeoptions$1({
timeout: 45e3
}, options); // allow an optional user-specified function to modify the option
// object before we construct the xhr request
var beforerequest = xhrfunction.beforerequest || videojs.vhs.xhr.beforerequest;
if (beforerequest && typeof beforerequest === 'function') {
var newoptions = beforerequest(options);
if (newoptions) {
options = newoptions;
}
} // use the standard videojs.xhr() method unless `videojs.vhs.xhr` has been overriden
// todo: switch back to videojs.vhs.xhr.name === 'xhrfunction' when we drop ie11
var xhrmethod = videojs.vhs.xhr.original === true ? videojsxhr : videojs.vhs.xhr;
var request = xhrmethod(options, function (error, response) {
return callbackwrapper(request, error, response, callback);
});
var originalabort = request.abort;
request.abort = function () {
request.aborted = true;
return originalabort.apply(request, arguments);
};
request.uri = options.uri;
request.requesttime = date.now();
return request;
};
xhr.original = true;
return xhr;
};
/**
* turns segment byterange into a string suitable for use in
* http range requests
*
* @param {object} byterange - an object with two values defining the start and end
* of a byte-range
*/
var byterangestr = function byterangestr(byterange) {
// `byterangeend` is one less than `offset + length` because the http range
// header uses inclusive ranges
var byterangeend;
var byterangestart = byterange.offset;
if (typeof byterange.offset === 'bigint' || typeof byterange.length === 'bigint') {
byterangeend = global_window__webpack_imported_module_0___default.a.bigint(byterange.offset) + global_window__webpack_imported_module_0___default.a.bigint(byterange.length) - global_window__webpack_imported_module_0___default.a.bigint(1);
} else {
byterangeend = byterange.offset + byterange.length - 1;
}
return 'bytes=' + byterangestart + '-' + byterangeend;
};
/**
* defines headers for use in the xhr request for a particular segment.
*
* @param {object} segment - a simplified copy of the segmentinfo object
* from segmentloader
*/
var segmentxhrheaders = function segmentxhrheaders(segment) {
var headers = {};
if (segment.byterange) {
headers.range = byterangestr(segment.byterange);
}
return headers;
};
/**
* @file bin-utils.js
*/
/**
* convert a timerange to text
*
* @param {timerange} range the timerange to use for conversion
* @param {number} i the iterator on the range to convert
* @return {string} the range in string format
*/
var textrange = function textrange(range, i) {
return range.start(i) + '-' + range.end(i);
};
/**
* format a number as hex string
*
* @param {number} e the number
* @param {number} i the iterator
* @return {string} the hex formatted number as a string
*/
var formathexstring = function formathexstring(e, i) {
var value = e.tostring(16);
return '00'.substring(0, 2 - value.length) + value + (i % 2 ? ' ' : '');
};
var formatasciistring = function formatasciistring(e) {
if (e >= 0x20 && e < 0x7e) {
return string.fromcharcode(e);
}
return '.';
};
/**
* creates an object for sending to a web worker modifying properties that are typedarrays
* into a new object with seperated properties for the buffer, byteoffset, and bytelength.
*
* @param {object} message
* object of properties and values to send to the web worker
* @return {object}
* modified message with typedarray values expanded
* @function createtransferablemessage
*/
var createtransferablemessage = function createtransferablemessage(message) {
var transferable = {};
object.keys(message).foreach(function (key) {
var value = message[key];
if (object(_videojs_vhs_utils_es_byte_helpers__webpack_imported_module_15__[/* isarraybufferview */ "e"])(value)) {
transferable[key] = {
bytes: value.buffer,
byteoffset: value.byteoffset,
bytelength: value.bytelength
};
} else {
transferable[key] = value;
}
});
return transferable;
};
/**
* returns a unique string identifier for a media initialization
* segment.
*
* @param {object} initsegment
* the init segment object.
*
* @return {string} the generated init segment id
*/
var initsegmentid = function initsegmentid(initsegment) {
var byterange = initsegment.byterange || {
length: infinity,
offset: 0
};
return [byterange.length, byterange.offset, initsegment.resolveduri].join(',');
};
/**
* returns a unique string identifier for a media segment key.
*
* @param {object} key the encryption key
* @return {string} the unique id for the media segment key.
*/
var segmentkeyid = function segmentkeyid(key) {
return key.resolveduri;
};
/**
* utils to help dump binary data to the console
*
* @param {array|typedarray} data
* data to dump to a string
*
* @return {string} the data as a hex string.
*/
var hexdump = function hexdump(data) {
var bytes = array.prototype.slice.call(data);
var step = 16;
var result = '';
var hex;
var ascii;
for (var j = 0; j < bytes.length / step; j++) {
hex = bytes.slice(j * step, j * step + step).map(formathexstring).join('');
ascii = bytes.slice(j * step, j * step + step).map(formatasciistring).join('');
result += hex + ' ' + ascii + '\n';
}
return result;
};
var tagdump = function tagdump(_ref) {
var bytes = _ref.bytes;
return hexdump(bytes);
};
var textranges = function textranges(ranges) {
var result = '';
var i;
for (i = 0; i < ranges.length; i++) {
result += textrange(ranges, i) + ' ';
}
return result;
};
var utils = /*#__pure__*/object.freeze({
__proto__: null,
createtransferablemessage: createtransferablemessage,
initsegmentid: initsegmentid,
segmentkeyid: segmentkeyid,
hexdump: hexdump,
tagdump: tagdump,
textranges: textranges
}); // todo handle fmp4 case where the timing info is accurate and doesn't involve transmux
// 25% was arbitrarily chosen, and may need to be refined over time.
var segment_end_fudge_percent = 0.25;
/**
* converts a player time (any time that can be gotten/set from player.currenttime(),
* e.g., any time within player.seekable().start(0) to player.seekable().end(0)) to a
* program time (any time referencing the real world (e.g., ext-x-program-date-time)).
*
* the containing segment is required as the ext-x-program-date-time serves as an "anchor
* point" (a point where we have a mapping from program time to player time, with player
* time being the post transmux start of the segment).
*
* for more details, see [this doc](../../docs/program-time-from-player-time.md).
*
* @param {number} playertime the player time
* @param {object} segment the segment which contains the player time
* @return {date} program time
*/
var playertimetoprogramtime = function playertimetoprogramtime(playertime, segment) {
if (!segment.datetimeobject) {
// can't convert without an "anchor point" for the program time (i.e., a time that can
// be used to map the start of a segment with a real world time).
return null;
}
var transmuxerprependedseconds = segment.videotiminginfo.transmuxerprependedseconds;
var transmuxedstart = segment.videotiminginfo.transmuxedpresentationstart; // get the start of the content from before old content is prepended
var startofsegment = transmuxedstart + transmuxerprependedseconds;
var offsetfromsegmentstart = playertime - startofsegment;
return new date(segment.datetimeobject.gettime() + offsetfromsegmentstart * 1000);
};
var originalsegmentvideoduration = function originalsegmentvideoduration(videotiminginfo) {
return videotiminginfo.transmuxedpresentationend - videotiminginfo.transmuxedpresentationstart - videotiminginfo.transmuxerprependedseconds;
};
/**
* finds a segment that contains the time requested given as an iso-8601 string. the
* returned segment might be an estimate or an accurate match.
*
* @param {string} programtime the iso-8601 programtime to find a match for
* @param {object} playlist a playlist object to search within
*/
var findsegmentforprogramtime = function findsegmentforprogramtime(programtime, playlist) {
// assumptions:
// - verifyprogramdatetimetags has already been run
// - live streams have been started
var datetimeobject;
try {
datetimeobject = new date(programtime);
} catch (e) {
return null;
}
if (!playlist || !playlist.segments || playlist.segments.length === 0) {
return null;
}
var segment = playlist.segments[0];
if (datetimeobject < segment.datetimeobject) {
// requested time is before stream start.
return null;
}
for (var i = 0; i < playlist.segments.length - 1; i++) {
segment = playlist.segments[i];
var nextsegmentstart = playlist.segments[i + 1].datetimeobject;
if (datetimeobject < nextsegmentstart) {
break;
}
}
var lastsegment = playlist.segments[playlist.segments.length - 1];
var lastsegmentstart = lastsegment.datetimeobject;
var lastsegmentduration = lastsegment.videotiminginfo ? originalsegmentvideoduration(lastsegment.videotiminginfo) : lastsegment.duration + lastsegment.duration * segment_end_fudge_percent;
var lastsegmentend = new date(lastsegmentstart.gettime() + lastsegmentduration * 1000);
if (datetimeobject > lastsegmentend) {
// beyond the end of the stream, or our best guess of the end of the stream.
return null;
}
if (datetimeobject > lastsegmentstart) {
segment = lastsegment;
}
return {
segment: segment,
estimatedstart: segment.videotiminginfo ? segment.videotiminginfo.transmuxedpresentationstart : playlist.duration(playlist, playlist.mediasequence + playlist.segments.indexof(segment)),
// although, given that all segments have accurate date time objects, the segment
// selected should be accurate, unless the video has been transmuxed at some point
// (determined by the presence of the videotiminginfo object), the segment's "player
// time" (the start time in the player) can't be considered accurate.
type: segment.videotiminginfo ? 'accurate' : 'estimate'
};
};
/**
* finds a segment that contains the given player time(in seconds).
*
* @param {number} time the player time to find a match for
* @param {object} playlist a playlist object to search within
*/
var findsegmentforplayertime = function findsegmentforplayertime(time, playlist) {
// assumptions:
// - there will always be a segment.duration
// - we can start from zero
// - segments are in time order
if (!playlist || !playlist.segments || playlist.segments.length === 0) {
return null;
}
var segmentend = 0;
var segment;
for (var i = 0; i < playlist.segments.length; i++) {
segment = playlist.segments[i]; // videotiminginfo is set after the segment is downloaded and transmuxed, and
// should contain the most accurate values we have for the segment's player times.
//
// use the accurate transmuxedpresentationend value if it is available, otherwise fall
// back to an estimate based on the manifest derived (inaccurate) segment.duration, to
// calculate an end value.
segmentend = segment.videotiminginfo ? segment.videotiminginfo.transmuxedpresentationend : segmentend + segment.duration;
if (time <= segmentend) {
break;
}
}
var lastsegment = playlist.segments[playlist.segments.length - 1];
if (lastsegment.videotiminginfo && lastsegment.videotiminginfo.transmuxedpresentationend < time) {
// the time requested is beyond the stream end.
return null;
}
if (time > segmentend) {
// the time is within or beyond the last segment.
//
// check to see if the time is beyond a reasonable guess of the end of the stream.
if (time > segmentend + lastsegment.duration * segment_end_fudge_percent) {
// technically, because the duration value is only an estimate, the time may still
// exist in the last segment, however, there isn't enough information to make even
// a reasonable estimate.
return null;
}
segment = lastsegment;
}
return {
segment: segment,
estimatedstart: segment.videotiminginfo ? segment.videotiminginfo.transmuxedpresentationstart : segmentend - segment.duration,
// because videotiminginfo is only set after transmux, it is the only way to get
// accurate timing values.
type: segment.videotiminginfo ? 'accurate' : 'estimate'
};
};
/**
* gives the offset of the comparisontimestamp from the programtime timestamp in seconds.
* if the offset returned is positive, the programtime occurs after the
* comparisontimestamp.
* if the offset is negative, the programtime occurs before the comparisontimestamp.
*
* @param {string} comparisontimestamp an iso-8601 timestamp to compare against
* @param {string} programtime the programtime as an iso-8601 string
* @return {number} offset
*/
var getoffsetfromtimestamp = function getoffsetfromtimestamp(comparisontimestamp, programtime) {
var segmentdatetime;
var programdatetime;
try {
segmentdatetime = new date(comparisontimestamp);
programdatetime = new date(programtime);
} catch (e) {// todo handle error
}
var segmenttimeepoch = segmentdatetime.gettime();
var programtimeepoch = programdatetime.gettime();
return (programtimeepoch - segmenttimeepoch) / 1000;
};
/**
* checks that all segments in this playlist have programdatetime tags.
*
* @param {object} playlist a playlist object
*/
var verifyprogramdatetimetags = function verifyprogramdatetimetags(playlist) {
if (!playlist.segments || playlist.segments.length === 0) {
return false;
}
for (var i = 0; i < playlist.segments.length; i++) {
var segment = playlist.segments[i];
if (!segment.datetimeobject) {
return false;
}
}
return true;
};
/**
* returns the programtime of the media given a playlist and a playertime.
* the playlist must have programdatetime tags for a programdatetime tag to be returned.
* if the segments containing the time requested have not been buffered yet, an estimate
* may be returned to the callback.
*
* @param {object} args
* @param {object} args.playlist a playlist object to search within
* @param {number} time a playertime in seconds
* @param {function} callback(err, programtime)
* @return {string} err.message a detailed error message
* @return {object} programtime
* @return {number} programtime.mediaseconds the streamtime in seconds
* @return {string} programtime.programdatetime the programtime as an iso-8601 string
*/
var getprogramtime = function getprogramtime(_ref) {
var playlist = _ref.playlist,
_ref$time = _ref.time,
time = _ref$time === void 0 ? undefined : _ref$time,
callback = _ref.callback;
if (!callback) {
throw new error('getprogramtime: callback must be provided');
}
if (!playlist || time === undefined) {
return callback({
message: 'getprogramtime: playlist and time must be provided'
});
}
var matchedsegment = findsegmentforplayertime(time, playlist);
if (!matchedsegment) {
return callback({
message: 'valid programtime was not found'
});
}
if (matchedsegment.type === 'estimate') {
return callback({
message: 'accurate programtime could not be determined.' + ' please seek to e.seektime and try again',
seektime: matchedsegment.estimatedstart
});
}
var programtimeobject = {
mediaseconds: time
};
var programtime = playertimetoprogramtime(time, matchedsegment.segment);
if (programtime) {
programtimeobject.programdatetime = programtime.toisostring();
}
return callback(null, programtimeobject);
};
/**
* seeks in the player to a time that matches the given programtime iso-8601 string.
*
* @param {object} args
* @param {string} args.programtime a programtime to seek to as an iso-8601 string
* @param {object} args.playlist a playlist to look within
* @param {number} args.retrycount the number of times to try for an accurate seek. default is 2.
* @param {function} args.seekto a method to perform a seek
* @param {boolean} args.pauseafterseek whether to end in a paused state after seeking. default is true.
* @param {object} args.tech the tech to seek on
* @param {function} args.callback(err, newtime) a callback to return the new time to
* @return {string} err.message a detailed error message
* @return {number} newtime the exact time that was seeked to in seconds
*/
var seektoprogramtime = function seektoprogramtime(_ref2) {
var programtime = _ref2.programtime,
playlist = _ref2.playlist,
_ref2$retrycount = _ref2.retrycount,
retrycount = _ref2$retrycount === void 0 ? 2 : _ref2$retrycount,
seekto = _ref2.seekto,
_ref2$pauseafterseek = _ref2.pauseafterseek,
pauseafterseek = _ref2$pauseafterseek === void 0 ? true : _ref2$pauseafterseek,
tech = _ref2.tech,
callback = _ref2.callback;
if (!callback) {
throw new error('seektoprogramtime: callback must be provided');
}
if (typeof programtime === 'undefined' || !playlist || !seekto) {
return callback({
message: 'seektoprogramtime: programtime, seekto and playlist must be provided'
});
}
if (!playlist.endlist && !tech.hasstarted_) {
return callback({
message: 'player must be playing a live stream to start buffering'
});
}
if (!verifyprogramdatetimetags(playlist)) {
return callback({
message: 'programdatetime tags must be provided in the manifest ' + playlist.resolveduri
});
}
var matchedsegment = findsegmentforprogramtime(programtime, playlist); // no match
if (!matchedsegment) {
return callback({
message: programtime + " was not found in the stream"
});
}
var segment = matchedsegment.segment;
var mediaoffset = getoffsetfromtimestamp(segment.datetimeobject, programtime);
if (matchedsegment.type === 'estimate') {
// we've run out of retries
if (retrycount === 0) {
return callback({
message: programtime + " is not buffered yet. try again"
});
}
seekto(matchedsegment.estimatedstart + mediaoffset);
tech.one('seeked', function () {
seektoprogramtime({
programtime: programtime,
playlist: playlist,
retrycount: retrycount - 1,
seekto: seekto,
pauseafterseek: pauseafterseek,
tech: tech,
callback: callback
});
});
return;
} // since the segment.start value is determined from the buffered end or ending time
// of the prior segment, the seektotime doesn't need to account for any transmuxer
// modifications.
var seektotime = segment.start + mediaoffset;
var seekedcallback = function seekedcallback() {
return callback(null, tech.currenttime());
}; // listen for seeked event
tech.one('seeked', seekedcallback); // pause before seeking as video.js will restore this state
if (pauseafterseek) {
tech.pause();
}
seekto(seektotime);
}; // which will only happen if the request is complete.
var callbackoncompleted = function callbackoncompleted(request, cb) {
if (request.readystate === 4) {
return cb();
}
return;
};
var containerrequest = function containerrequest(uri, xhr, cb) {
var bytes = [];
var id3offset;
var finished = false;
var endrequestandcallback = function endrequestandcallback(err, req, type, _bytes) {
req.abort();
finished = true;
return cb(err, req, type, _bytes);
};
var progresslistener = function progresslistener(error, request) {
if (finished) {
return;
}
if (error) {
return endrequestandcallback(error, request, '', bytes);
} // grap the new part of content that was just downloaded
var newpart = request.responsetext.substring(bytes && bytes.bytelength || 0, request.responsetext.length); // add that onto bytes
bytes = object(_videojs_vhs_utils_es_byte_helpers__webpack_imported_module_15__[/* concattypedarrays */ "d"])(bytes, object(_videojs_vhs_utils_es_byte_helpers__webpack_imported_module_15__[/* stringtobytes */ "h"])(newpart, true));
id3offset = id3offset || object(_videojs_vhs_utils_es_id3_helpers__webpack_imported_module_18__[/* getid3offset */ "a"])(bytes); // we need at least 10 bytes to determine a type
// or we need at least two bytes after an id3offset
if (bytes.length < 10 || id3offset && bytes.length < id3offset + 2) {
return callbackoncompleted(request, function () {
return endrequestandcallback(error, request, '', bytes);
});
}
var type = object(_videojs_vhs_utils_es_containers__webpack_imported_module_19__[/* detectcontainerforbytes */ "a"])(bytes); // if this looks like a ts segment but we don't have enough data
// to see the second sync byte, wait until we have enough data
// before declaring it ts
if (type === 'ts' && bytes.length < 188) {
return callbackoncompleted(request, function () {
return endrequestandcallback(error, request, '', bytes);
});
} // this may be an unsynced ts segment
// wait for 376 bytes before detecting no container
if (!type && bytes.length < 376) {
return callbackoncompleted(request, function () {
return endrequestandcallback(error, request, '', bytes);
});
}
return endrequestandcallback(null, request, type, bytes);
};
var options = {
uri: uri,
beforesend: function beforesend(request) {
// this forces the browser to pass the bytes to us unprocessed
request.overridemimetype('text/plain; charset=x-user-defined');
request.addeventlistener('progress', function (_ref) {
_ref.total;
_ref.loaded;
return callbackwrapper(request, null, {
statuscode: request.status
}, progresslistener);
});
}
};
var request = xhr(options, function (error, response) {
return callbackwrapper(request, error, response, progresslistener);
});
return request;
};
var eventtarget = videojs.eventtarget,
mergeoptions = videojs.mergeoptions;
var dashplaylistunchanged = function dashplaylistunchanged(a, b) {
if (!isplaylistunchanged(a, b)) {
return false;
} // for dash the above check will often return true in scenarios where
// the playlist actually has changed because mediasequence isn't a
// dash thing, and we often set it to 1. so if the playlists have the same amount
// of segments we return true.
// so for dash we need to make sure that the underlying segments are different.
// if sidx changed then the playlists are different.
if (a.sidx && b.sidx && (a.sidx.offset !== b.sidx.offset || a.sidx.length !== b.sidx.length)) {
return false;
} else if (!a.sidx && b.sidx || a.sidx && !b.sidx) {
return false;
} // one or the other does not have segments
// there was a change.
if (a.segments && !b.segments || !a.segments && b.segments) {
return false;
} // neither has segments nothing changed
if (!a.segments && !b.segments) {
return true;
} // check segments themselves
for (var i = 0; i < a.segments.length; i++) {
var asegment = a.segments[i];
var bsegment = b.segments[i]; // if uris are different between segments there was a change
if (asegment.uri !== bsegment.uri) {
return false;
} // neither segment has a byterange, there will be no byterange change.
if (!asegment.byterange && !bsegment.byterange) {
continue;
}
var abyterange = asegment.byterange;
var bbyterange = bsegment.byterange; // if byterange only exists on one of the segments, there was a change.
if (abyterange && !bbyterange || !abyterange && bbyterange) {
return false;
} // if both segments have byterange with different offsets, there was a change.
if (abyterange.offset !== bbyterange.offset || abyterange.length !== bbyterange.length) {
return false;
}
} // if everything was the same with segments, this is the same playlist.
return true;
};
/**
* use the representation ids from the mpd object to create groupids, the name is set to mandatory representation
* id in the parser. this allows for continuous playout across periods with the same representation ids
* (continuous periods as defined in dash-if 3.2.12). this is assumed in the mpd-parser as well. if we want to support
* periods without continuous playback this function may need modification as well as the parser.
*/
var dashgroupid = function dashgroupid(type, group, label, playlist) {
// if the manifest somehow does not have an id (non-dash compliant), use the label.
var playlistid = playlist.attributes.name || label;
return "placeholder-uri-" + type + "-" + group + "-" + playlistid;
};
/**
* parses the master xml string and updates playlist uri references.
*
* @param {object} config
* object of arguments
* @param {string} config.masterxml
* the mpd xml
* @param {string} config.srcurl
* the mpd url
* @param {date} config.clientoffset
* a time difference between server and client
* @param {object} config.sidxmapping
* sidx mappings for moof/mdat uris and byte ranges
* @return {object}
* the parsed mpd manifest object
*/
var parsemasterxml = function parsemasterxml(_ref) {
var masterxml = _ref.masterxml,
srcurl = _ref.srcurl,
clientoffset = _ref.clientoffset,
sidxmapping = _ref.sidxmapping,
previousmanifest = _ref.previousmanifest;
var manifest = object(mpd_parser__webpack_imported_module_16__[/* parse */ "c"])(masterxml, {
manifesturi: srcurl,
clientoffset: clientoffset,
sidxmapping: sidxmapping,
previousmanifest: previousmanifest
});
addpropertiestomaster(manifest, srcurl, dashgroupid);
return manifest;
};
/**
* removes any mediagroup labels that no longer exist in the newmaster
*
* @param {object} update
* the previous mpd object being updated
* @param {object} newmaster
* the new mpd object
*/
var removeoldmediagrouplabels = function removeoldmediagrouplabels(update, newmaster) {
foreachmediagroup(update, function (properties, type, group, label) {
if (!(label in newmaster.mediagroups[type][group])) {
delete update.mediagroups[type][group][label];
}
});
};
/**
* returns a new master manifest that is the result of merging an updated master manifest
* into the original version.
*
* @param {object} oldmaster
* the old parsed mpd object
* @param {object} newmaster
* the updated parsed mpd object
* @return {object}
* a new object representing the original master manifest with the updated media
* playlists merged in
*/
var updatemaster = function updatemaster(oldmaster, newmaster, sidxmapping) {
var nochanges = true;
var update = mergeoptions(oldmaster, {
// these are top level properties that can be updated
duration: newmaster.duration,
minimumupdateperiod: newmaster.minimumupdateperiod,
timelinestarts: newmaster.timelinestarts
}); // first update the playlists in playlist list
for (var i = 0; i < newmaster.playlists.length; i++) {
var playlist = newmaster.playlists[i];
if (playlist.sidx) {
var sidxkey = object(mpd_parser__webpack_imported_module_16__[/* generatesidxkey */ "b"])(playlist.sidx); // add sidx segments to the playlist if we have all the sidx info already
if (sidxmapping && sidxmapping[sidxkey] && sidxmapping[sidxkey].sidx) {
object(mpd_parser__webpack_imported_module_16__[/* addsidxsegmentstoplaylist */ "a"])(playlist, sidxmapping[sidxkey].sidx, playlist.sidx.resolveduri);
}
}
var playlistupdate = updatemaster$1(update, playlist, dashplaylistunchanged);
if (playlistupdate) {
update = playlistupdate;
nochanges = false;
}
} // then update media group playlists
foreachmediagroup(newmaster, function (properties, type, group, label) {
if (properties.playlists && properties.playlists.length) {
var id = properties.playlists[0].id;
var _playlistupdate = updatemaster$1(update, properties.playlists[0], dashplaylistunchanged);
if (_playlistupdate) {
update = _playlistupdate; // add new mediagroup label if it doesn't exist and assign the new mediagroup.
if (!(label in update.mediagroups[type][group])) {
update.mediagroups[type][group][label] = properties;
} // update the playlist reference within media groups
update.mediagroups[type][group][label].playlists[0] = update.playlists[id];
nochanges = false;
}
}
}); // remove mediagroup labels and references that no longer exist in the newmaster
removeoldmediagrouplabels(update, newmaster);
if (newmaster.minimumupdateperiod !== oldmaster.minimumupdateperiod) {
nochanges = false;
}
if (nochanges) {
return null;
}
return update;
}; // sidx should be equivalent if the uri and byteranges of the sidx match.
// if the sidxs have maps, the two maps should match,
// both `a` and `b` missing sidxs is considered matching.
// if `a` or `b` but not both have a map, they aren't matching.
var equivalentsidx = function equivalentsidx(a, b) {
var neithermap = boolean(!a.map && !b.map);
var equivalentmap = neithermap || boolean(a.map && b.map && a.map.byterange.offset === b.map.byterange.offset && a.map.byterange.length === b.map.byterange.length);
return equivalentmap && a.uri === b.uri && a.byterange.offset === b.byterange.offset && a.byterange.length === b.byterange.length;
}; // exported for testing
var comparesidxentry = function comparesidxentry(playlists, oldsidxmapping) {
var newsidxmapping = {};
for (var id in playlists) {
var playlist = playlists[id];
var currentsidxinfo = playlist.sidx;
if (currentsidxinfo) {
var key = object(mpd_parser__webpack_imported_module_16__[/* generatesidxkey */ "b"])(currentsidxinfo);
if (!oldsidxmapping[key]) {
break;
}
var savedsidxinfo = oldsidxmapping[key].sidxinfo;
if (equivalentsidx(savedsidxinfo, currentsidxinfo)) {
newsidxmapping[key] = oldsidxmapping[key];
}
}
}
return newsidxmapping;
};
/**
* a function that filters out changed items as they need to be requested separately.
*
* the method is exported for testing
*
* @param {object} master the parsed mpd xml returned via mpd-parser
* @param {object} oldsidxmapping the sidx to compare against
*/
var filterchangedsidxmappings = function filterchangedsidxmappings(master, oldsidxmapping) {
var videosidx = comparesidxentry(master.playlists, oldsidxmapping);
var mediagroupsidx = videosidx;
foreachmediagroup(master, function (properties, mediatype, groupkey, labelkey) {
if (properties.playlists && properties.playlists.length) {
var playlists = properties.playlists;
mediagroupsidx = mergeoptions(mediagroupsidx, comparesidxentry(playlists, oldsidxmapping));
}
});
return mediagroupsidx;
};
var dashplaylistloader = /*#__pure__*/function (_eventtarget) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(dashplaylistloader, _eventtarget); // dashplaylistloader must accept either a src url or a playlist because subsequent
// playlist loader setups from media groups will expect to be able to pass a playlist
// (since there aren't external urls to media playlists with dash)
function dashplaylistloader(srcurlorplaylist, vhs, options, masterplaylistloader) {
var _this;
if (options === void 0) {
options = {};
}
_this = _eventtarget.call(this) || this;
_this.masterplaylistloader_ = masterplaylistloader || _babel_runtime_helpers_assertthisinitialized__webpack_imported_module_4___default()(_this);
if (!masterplaylistloader) {
_this.ismaster_ = true;
}
var _options = options,
_options$withcredenti = _options.withcredentials,
withcredentials = _options$withcredenti === void 0 ? false : _options$withcredenti,
_options$handlemanife = _options.handlemanifestredirects,
handlemanifestredirects = _options$handlemanife === void 0 ? false : _options$handlemanife;
_this.vhs_ = vhs;
_this.withcredentials = withcredentials;
_this.handlemanifestredirects = handlemanifestredirects;
if (!srcurlorplaylist) {
throw new error('a non-empty playlist url or object is required');
} // event naming?
_this.on('minimumupdateperiod', function () {
_this.refreshxml_();
}); // live playlist staleness timeout
_this.on('mediaupdatetimeout', function () {
_this.refreshmedia_(_this.media().id);
});
_this.state = 'have_nothing';
_this.loadedplaylists_ = {};
_this.logger_ = logger('dashplaylistloader'); // initialize the loader state
// the masterplaylistloader will be created with a string
if (_this.ismaster_) {
_this.masterplaylistloader_.srcurl = srcurlorplaylist; // todo: reset sidxmapping between period changes
// once multi-period is refactored
_this.masterplaylistloader_.sidxmapping_ = {};
} else {
_this.childplaylist_ = srcurlorplaylist;
}
return _this;
}
var _proto = dashplaylistloader.prototype;
_proto.requesterrored_ = function requesterrored_(err, request, startingstate) {
// disposed
if (!this.request) {
return true;
} // pending request is cleared
this.request = null;
if (err) {
// use the provided error object or create one
// based on the request/response
this.error = typeof err === 'object' && !(err instanceof error) ? err : {
status: request.status,
message: 'dash request error at url: ' + request.uri,
response: request.response,
// media_err_network
code: 2
};
if (startingstate) {
this.state = startingstate;
}
this.trigger('error');
return true;
}
}
/**
* verify that the container of the sidx segment can be parsed
* and if it can, get and parse that segment.
*/
;
_proto.addsidxsegments_ = function addsidxsegments_(playlist, startingstate, cb) {
var _this2 = this;
var sidxkey = playlist.sidx && object(mpd_parser__webpack_imported_module_16__[/* generatesidxkey */ "b"])(playlist.sidx); // playlist lacks sidx or sidx segments were added to this playlist already.
if (!playlist.sidx || !sidxkey || this.masterplaylistloader_.sidxmapping_[sidxkey]) {
// keep this function async
this.mediarequest_ = global_window__webpack_imported_module_0___default.a.settimeout(function () {
return cb(false);
}, 0);
return;
} // resolve the segment url relative to the playlist
var uri = resolvemanifestredirect(this.handlemanifestredirects, playlist.sidx.resolveduri);
var fin = function fin(err, request) {
if (_this2.requesterrored_(err, request, startingstate)) {
return;
}
var sidxmapping = _this2.masterplaylistloader_.sidxmapping_;
var sidx;
try {
sidx = mux_js_lib_tools_parse_sidx__webpack_imported_module_17___default()(object(_videojs_vhs_utils_es_byte_helpers__webpack_imported_module_15__[/* touint8 */ "k"])(request.response).subarray(8));
} catch (e) {
// sidx parsing failed.
_this2.requesterrored_(e, request, startingstate);
return;
}
sidxmapping[sidxkey] = {
sidxinfo: playlist.sidx,
sidx: sidx
};
object(mpd_parser__webpack_imported_module_16__[/* addsidxsegmentstoplaylist */ "a"])(playlist, sidx, playlist.sidx.resolveduri);
return cb(true);
};
this.request = containerrequest(uri, this.vhs_.xhr, function (err, request, container, bytes) {
if (err) {
return fin(err, request);
}
if (!container || container !== 'mp4') {
return fin({
status: request.status,
message: "unsupported " + (container || 'unknown') + " container type for sidx segment at url: " + uri,
// response is just bytes in this case
// but we really don't want to return that.
response: '',
playlist: playlist,
internal: true,
blacklistduration: infinity,
// media_err_network
code: 2
}, request);
} // if we already downloaded the sidx bytes in the container request, use them
var _playlist$sidx$bytera = playlist.sidx.byterange,
offset = _playlist$sidx$bytera.offset,
length = _playlist$sidx$bytera.length;
if (bytes.length >= length + offset) {
return fin(err, {
response: bytes.subarray(offset, offset + length),
status: request.status,
uri: request.uri
});
} // otherwise request sidx bytes
_this2.request = _this2.vhs_.xhr({
uri: uri,
responsetype: 'arraybuffer',
headers: segmentxhrheaders({
byterange: playlist.sidx.byterange
})
}, fin);
});
};
_proto.dispose = function dispose() {
this.trigger('dispose');
this.stoprequest();
this.loadedplaylists_ = {};
global_window__webpack_imported_module_0___default.a.cleartimeout(this.minimumupdateperiodtimeout_);
global_window__webpack_imported_module_0___default.a.cleartimeout(this.mediarequest_);
global_window__webpack_imported_module_0___default.a.cleartimeout(this.mediaupdatetimeout);
this.mediaupdatetimeout = null;
this.mediarequest_ = null;
this.minimumupdateperiodtimeout_ = null;
if (this.masterplaylistloader_.createmuponmedia_) {
this.off('loadedmetadata', this.masterplaylistloader_.createmuponmedia_);
this.masterplaylistloader_.createmuponmedia_ = null;
}
this.off();
};
_proto.haspendingrequest = function haspendingrequest() {
return this.request || this.mediarequest_;
};
_proto.stoprequest = function stoprequest() {
if (this.request) {
var oldrequest = this.request;
this.request = null;
oldrequest.onreadystatechange = null;
oldrequest.abort();
}
};
_proto.media = function media(playlist) {
var _this3 = this; // getter
if (!playlist) {
return this.media_;
} // setter
if (this.state === 'have_nothing') {
throw new error('cannot switch media playlist from ' + this.state);
}
var startingstate = this.state; // find the playlist object if the target playlist has been specified by uri
if (typeof playlist === 'string') {
if (!this.masterplaylistloader_.master.playlists[playlist]) {
throw new error('unknown playlist uri: ' + playlist);
}
playlist = this.masterplaylistloader_.master.playlists[playlist];
}
var mediachange = !this.media_ || playlist.id !== this.media_.id; // switch to previously loaded playlists immediately
if (mediachange && this.loadedplaylists_[playlist.id] && this.loadedplaylists_[playlist.id].endlist) {
this.state = 'have_metadata';
this.media_ = playlist; // trigger media change if the active media has been updated
if (mediachange) {
this.trigger('mediachanging');
this.trigger('mediachange');
}
return;
} // switching to the active playlist is a no-op
if (!mediachange) {
return;
} // switching from an already loaded playlist
if (this.media_) {
this.trigger('mediachanging');
}
this.addsidxsegments_(playlist, startingstate, function (sidxchanged) {
// everything is ready just continue to havemetadata
_this3.havemetadata({
startingstate: startingstate,
playlist: playlist
});
});
};
_proto.havemetadata = function havemetadata(_ref2) {
var startingstate = _ref2.startingstate,
playlist = _ref2.playlist;
this.state = 'have_metadata';
this.loadedplaylists_[playlist.id] = playlist;
this.mediarequest_ = null; // this will trigger loadedplaylist
this.refreshmedia_(playlist.id); // fire loadedmetadata the first time a media playlist is loaded
// to resolve setup of media groups
if (startingstate === 'have_master') {
this.trigger('loadedmetadata');
} else {
// trigger media change if the active media has been updated
this.trigger('mediachange');
}
};
_proto.pause = function pause() {
if (this.masterplaylistloader_.createmuponmedia_) {
this.off('loadedmetadata', this.masterplaylistloader_.createmuponmedia_);
this.masterplaylistloader_.createmuponmedia_ = null;
}
this.stoprequest();
global_window__webpack_imported_module_0___default.a.cleartimeout(this.mediaupdatetimeout);
this.mediaupdatetimeout = null;
if (this.ismaster_) {
global_window__webpack_imported_module_0___default.a.cleartimeout(this.masterplaylistloader_.minimumupdateperiodtimeout_);
this.masterplaylistloader_.minimumupdateperiodtimeout_ = null;
}
if (this.state === 'have_nothing') {
// if we pause the loader before any data has been retrieved, its as if we never
// started, so reset to an unstarted state.
this.started = false;
}
};
_proto.load = function load(isfinalrendition) {
var _this4 = this;
global_window__webpack_imported_module_0___default.a.cleartimeout(this.mediaupdatetimeout);
this.mediaupdatetimeout = null;
var media = this.media();
if (isfinalrendition) {
var delay = media ? media.targetduration / 2 * 1000 : 5 * 1000;
this.mediaupdatetimeout = global_window__webpack_imported_module_0___default.a.settimeout(function () {
return _this4.load();
}, delay);
return;
} // because the playlists are internal to the manifest, load should either load the
// main manifest, or do nothing but trigger an event
if (!this.started) {
this.start();
return;
}
if (media && !media.endlist) {
// check to see if this is the master loader and the mup was cleared (this happens
// when the loader was paused). `media` should be set at this point since one is always
// set during `start()`.
if (this.ismaster_ && !this.minimumupdateperiodtimeout_) {
// trigger minimumupdateperiod to refresh the master manifest
this.trigger('minimumupdateperiod'); // since there was no prior minimumupdateperiodtimeout it should be recreated
this.updateminimumupdateperiodtimeout_();
}
this.trigger('mediaupdatetimeout');
} else {
this.trigger('loadedplaylist');
}
};
_proto.start = function start() {
var _this5 = this;
this.started = true; // we don't need to request the master manifest again
// call this asynchronously to match the xhr request behavior below
if (!this.ismaster_) {
this.mediarequest_ = global_window__webpack_imported_module_0___default.a.settimeout(function () {
return _this5.havemaster_();
}, 0);
return;
}
this.requestmaster_(function (req, masterchanged) {
_this5.havemaster_();
if (!_this5.haspendingrequest() && !_this5.media_) {
_this5.media(_this5.masterplaylistloader_.master.playlists[0]);
}
});
};
_proto.requestmaster_ = function requestmaster_(cb) {
var _this6 = this;
this.request = this.vhs_.xhr({
uri: this.masterplaylistloader_.srcurl,
withcredentials: this.withcredentials
}, function (error, req) {
if (_this6.requesterrored_(error, req)) {
if (_this6.state === 'have_nothing') {
_this6.started = false;
}
return;
}
var masterchanged = req.responsetext !== _this6.masterplaylistloader_.masterxml_;
_this6.masterplaylistloader_.masterxml_ = req.responsetext;
if (req.responseheaders && req.responseheaders.date) {
_this6.masterloaded_ = date.parse(req.responseheaders.date);
} else {
_this6.masterloaded_ = date.now();
}
_this6.masterplaylistloader_.srcurl = resolvemanifestredirect(_this6.handlemanifestredirects, _this6.masterplaylistloader_.srcurl, req);
if (masterchanged) {
_this6.handlemaster_();
_this6.syncclientserverclock_(function () {
return cb(req, masterchanged);
});
return;
}
return cb(req, masterchanged);
});
}
/**
* parses the master xml for utctiming node to sync the client clock to the server
* clock. if the utctiming node requires a head or get request, that request is made.
*
* @param {function} done
* function to call when clock sync has completed
*/
;
_proto.syncclientserverclock_ = function syncclientserverclock_(done) {
var _this7 = this;
var utctiming = object(mpd_parser__webpack_imported_module_16__[/* parseutctiming */ "d"])(this.masterplaylistloader_.masterxml_); // no utctiming element found in the mpd. use date header from mpd request as the
// server clock
if (utctiming === null) {
this.masterplaylistloader_.clientoffset_ = this.masterloaded_ - date.now();
return done();
}
if (utctiming.method === 'direct') {
this.masterplaylistloader_.clientoffset_ = utctiming.value - date.now();
return done();
}
this.request = this.vhs_.xhr({
uri: resolveurl(this.masterplaylistloader_.srcurl, utctiming.value),
method: utctiming.method,
withcredentials: this.withcredentials
}, function (error, req) {
// disposed
if (!_this7.request) {
return;
}
if (error) {
// sync request failed, fall back to using date header from mpd
// todo: log warning
_this7.masterplaylistloader_.clientoffset_ = _this7.masterloaded_ - date.now();
return done();
}
var servertime;
if (utctiming.method === 'head') {
if (!req.responseheaders || !req.responseheaders.date) {
// expected date header not preset, fall back to using date header from mpd
// todo: log warning
servertime = _this7.masterloaded_;
} else {
servertime = date.parse(req.responseheaders.date);
}
} else {
servertime = date.parse(req.responsetext);
}
_this7.masterplaylistloader_.clientoffset_ = servertime - date.now();
done();
});
};
_proto.havemaster_ = function havemaster_() {
this.state = 'have_master';
if (this.ismaster_) {
// we have the master playlist at this point, so
// trigger this to allow masterplaylistcontroller
// to make an initial playlist selection
this.trigger('loadedplaylist');
} else if (!this.media_) {
// no media playlist was specifically selected so select
// the one the child playlist loader was created with
this.media(this.childplaylist_);
}
};
_proto.handlemaster_ = function handlemaster_() {
// clear media request
this.mediarequest_ = null;
var oldmaster = this.masterplaylistloader_.master;
var newmaster = parsemasterxml({
masterxml: this.masterplaylistloader_.masterxml_,
srcurl: this.masterplaylistloader_.srcurl,
clientoffset: this.masterplaylistloader_.clientoffset_,
sidxmapping: this.masterplaylistloader_.sidxmapping_,
previousmanifest: oldmaster
}); // if we have an old master to compare the new master against
if (oldmaster) {
newmaster = updatemaster(oldmaster, newmaster, this.masterplaylistloader_.sidxmapping_);
} // only update master if we have a new master
this.masterplaylistloader_.master = newmaster ? newmaster : oldmaster;
var location = this.masterplaylistloader_.master.locations && this.masterplaylistloader_.master.locations[0];
if (location && location !== this.masterplaylistloader_.srcurl) {
this.masterplaylistloader_.srcurl = location;
}
if (!oldmaster || newmaster && newmaster.minimumupdateperiod !== oldmaster.minimumupdateperiod) {
this.updateminimumupdateperiodtimeout_();
}
return boolean(newmaster);
};
_proto.updateminimumupdateperiodtimeout_ = function updateminimumupdateperiodtimeout_() {
var mpl = this.masterplaylistloader_; // cancel any pending creation of mup on media
// a new one will be added if needed.
if (mpl.createmuponmedia_) {
mpl.off('loadedmetadata', mpl.createmuponmedia_);
mpl.createmuponmedia_ = null;
} // clear any pending timeouts
if (mpl.minimumupdateperiodtimeout_) {
global_window__webpack_imported_module_0___default.a.cleartimeout(mpl.minimumupdateperiodtimeout_);
mpl.minimumupdateperiodtimeout_ = null;
}
var mup = mpl.master && mpl.master.minimumupdateperiod; // if the minimumupdateperiod has a value of 0, that indicates that the current
// mpd has no future validity, so a new one will need to be acquired when new
// media segments are to be made available. thus, we use the target duration
// in this case
if (mup === 0) {
if (mpl.media()) {
mup = mpl.media().targetduration * 1000;
} else {
mpl.createmuponmedia_ = mpl.updateminimumupdateperiodtimeout_;
mpl.one('loadedmetadata', mpl.createmuponmedia_);
}
} // if minimumupdateperiod is invalid or <= zero, which
// can happen when a live video becomes vod. skip timeout
// creation.
if (typeof mup !== 'number' || mup <= 0) {
if (mup < 0) {
this.logger_("found invalid minimumupdateperiod of " + mup + ", not setting a timeout");
}
return;
}
this.createmuptimeout_(mup);
};
_proto.createmuptimeout_ = function createmuptimeout_(mup) {
var mpl = this.masterplaylistloader_;
mpl.minimumupdateperiodtimeout_ = global_window__webpack_imported_module_0___default.a.settimeout(function () {
mpl.minimumupdateperiodtimeout_ = null;
mpl.trigger('minimumupdateperiod');
mpl.createmuptimeout_(mup);
}, mup);
}
/**
* sends request to refresh the master xml and updates the parsed master manifest
*/
;
_proto.refreshxml_ = function refreshxml_() {
var _this8 = this;
this.requestmaster_(function (req, masterchanged) {
if (!masterchanged) {
return;
}
if (_this8.media_) {
_this8.media_ = _this8.masterplaylistloader_.master.playlists[_this8.media_.id];
} // this will filter out updated sidx info from the mapping
_this8.masterplaylistloader_.sidxmapping_ = filterchangedsidxmappings(_this8.masterplaylistloader_.master, _this8.masterplaylistloader_.sidxmapping_);
_this8.addsidxsegments_(_this8.media(), _this8.state, function (sidxchanged) {
// todo: do we need to reload the current playlist?
_this8.refreshmedia_(_this8.media().id);
});
});
}
/**
* refreshes the media playlist by re-parsing the master xml and updating playlist
* references. if this is an alternate loader, the updated parsed manifest is retrieved
* from the master loader.
*/
;
_proto.refreshmedia_ = function refreshmedia_(mediaid) {
var _this9 = this;
if (!mediaid) {
throw new error('refreshmedia_ must take a media id');
} // for master we have to reparse the master xml
// to re-create segments based on current timing values
// which may change media. we only skip updating master
// if this is the first time this.media_ is being set.
// as master was just parsed in that case.
if (this.media_ && this.ismaster_) {
this.handlemaster_();
}
var playlists = this.masterplaylistloader_.master.playlists;
var mediachanged = !this.media_ || this.media_ !== playlists[mediaid];
if (mediachanged) {
this.media_ = playlists[mediaid];
} else {
this.trigger('playlistunchanged');
}
if (!this.mediaupdatetimeout) {
var createmediaupdatetimeout = function createmediaupdatetimeout() {
if (_this9.media().endlist) {
return;
}
_this9.mediaupdatetimeout = global_window__webpack_imported_module_0___default.a.settimeout(function () {
_this9.trigger('mediaupdatetimeout');
createmediaupdatetimeout();
}, refreshdelay(_this9.media(), boolean(mediachanged)));
};
createmediaupdatetimeout();
}
this.trigger('loadedplaylist');
};
return dashplaylistloader;
}(eventtarget);
var config = {
goal_buffer_length: 30,
max_goal_buffer_length: 60,
back_buffer_length: 30,
goal_buffer_length_rate: 1,
// 0.5 mb/s
initial_bandwidth: 4194304,
// a fudge factor to apply to advertised playlist bitrates to account for
// temporary flucations in client bandwidth
bandwidth_variance: 1.2,
// how much of the buffer must be filled before we consider upswitching
buffer_low_water_line: 0,
max_buffer_low_water_line: 30,
// todo: remove this when experimentalbufferbasedabr is removed
experimental_max_buffer_low_water_line: 16,
buffer_low_water_line_rate: 1,
// if the buffer is greater than the high water line, we won't switch down
buffer_high_water_line: 30
};
var stringtoarraybuffer = function stringtoarraybuffer(string) {
var view = new uint8array(new arraybuffer(string.length));
for (var i = 0; i < string.length; i++) {
view[i] = string.charcodeat(i);
}
return view.buffer;
};
/* global blob, blobbuilder, worker */
// unify worker interface
var browserworkerpolyfill = function browserworkerpolyfill(workerobj) {
// node only supports on/off
workerobj.on = workerobj.addeventlistener;
workerobj.off = workerobj.removeeventlistener;
return workerobj;
};
var createobjecturl = function createobjecturl(str) {
try {
return url.createobjecturl(new blob([str], {
type: 'application/javascript'
}));
} catch (e) {
var blob = new blobbuilder();
blob.append(str);
return url.createobjecturl(blob.getblob());
}
};
var factory = function factory(code) {
return function () {
var objecturl = createobjecturl(code);
var worker = browserworkerpolyfill(new worker(objecturl));
worker.objurl = objecturl;
var terminate = worker.terminate;
worker.on = worker.addeventlistener;
worker.off = worker.removeeventlistener;
worker.terminate = function () {
url.revokeobjecturl(objecturl);
return terminate.call(this);
};
return worker;
};
};
var transform = function transform(code) {
return "var browserworkerpolyfill = " + browserworkerpolyfill.tostring() + ";\n" + 'browserworkerpolyfill(self);\n' + code;
};
var getworkerstring = function getworkerstring(fn) {
return fn.tostring().replace(/^function.+?{/, '').slice(0, -1);
};
/* rollup-plugin-worker-factory start for worker!/home/runner/work/http-streaming/http-streaming/src/transmuxer-worker.js */
var workercode$1 = transform(getworkerstring(function () {
/**
* mux.js
*
* copyright (c) brightcove
* licensed apache-2.0 https://github.com/videojs/mux.js/blob/master/license
*
* a lightweight readable stream implemention that handles event dispatching.
* objects that inherit from streams should call init in their constructors.
*/
var stream = function stream() {
this.init = function () {
var listeners = {};
/**
* add a listener for a specified event type.
* @param type {string} the event name
* @param listener {function} the callback to be invoked when an event of
* the specified type occurs
*/
this.on = function (type, listener) {
if (!listeners[type]) {
listeners[type] = [];
}
listeners[type] = listeners[type].concat(listener);
};
/**
* remove a listener for a specified event type.
* @param type {string} the event name
* @param listener {function} a function previously registered for this
* type of event through `on`
*/
this.off = function (type, listener) {
var index;
if (!listeners[type]) {
return false;
}
index = listeners[type].indexof(listener);
listeners[type] = listeners[type].slice();
listeners[type].splice(index, 1);
return index > -1;
};
/**
* trigger an event of the specified type on this stream. any additional
* arguments to this function are passed as parameters to event listeners.
* @param type {string} the event name
*/
this.trigger = function (type) {
var callbacks, i, length, args;
callbacks = listeners[type];
if (!callbacks) {
return;
} // slicing the arguments on every invocation of this method
// can add a significant amount of overhead. avoid the
// intermediate object creation for the common case of a
// single callback argument
if (arguments.length === 2) {
length = callbacks.length;
for (i = 0; i < length; ++i) {
callbacks[i].call(this, arguments[1]);
}
} else {
args = [];
i = arguments.length;
for (i = 1; i < arguments.length; ++i) {
args.push(arguments[i]);
}
length = callbacks.length;
for (i = 0; i < length; ++i) {
callbacks[i].apply(this, args);
}
}
};
/**
* destroys the stream and cleans up.
*/
this.dispose = function () {
listeners = {};
};
};
};
/**
* forwards all `data` events on this stream to the destination stream. the
* destination stream should provide a method `push` to receive the data
* events as they arrive.
* @param destination {stream} the stream that will receive all `data` events
* @param autoflush {boolean} if false, we will not call `flush` on the destination
* when the current stream emits a 'done' event
* @see http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
*/
stream.prototype.pipe = function (destination) {
this.on('data', function (data) {
destination.push(data);
});
this.on('done', function (flushsource) {
destination.flush(flushsource);
});
this.on('partialdone', function (flushsource) {
destination.partialflush(flushsource);
});
this.on('endedtimeline', function (flushsource) {
destination.endtimeline(flushsource);
});
this.on('reset', function (flushsource) {
destination.reset(flushsource);
});
return destination;
}; // default stream functions that are expected to be overridden to perform
// actual work. these are provided by the prototype as a sort of no-op
// implementation so that we don't have to check for their existence in the
// `pipe` function above.
stream.prototype.push = function (data) {
this.trigger('data', data);
};
stream.prototype.flush = function (flushsource) {
this.trigger('done', flushsource);
};
stream.prototype.partialflush = function (flushsource) {
this.trigger('partialdone', flushsource);
};
stream.prototype.endtimeline = function (flushsource) {
this.trigger('endedtimeline', flushsource);
};
stream.prototype.reset = function (flushsource) {
this.trigger('reset', flushsource);
};
var stream = stream;
var max_uint32$1 = math.pow(2, 32);
var getuint64$2 = function getuint64(uint8) {
var dv = new dataview(uint8.buffer, uint8.byteoffset, uint8.bytelength);
var value;
if (dv.getbiguint64) {
value = dv.getbiguint64(0);
if (value < number.max_safe_integer) {
return number(value);
}
return value;
}
return dv.getuint32(0) * max_uint32$1 + dv.getuint32(4);
};
var numbers = {
getuint64: getuint64$2,
max_uint32: max_uint32$1
};
var max_uint32 = numbers.max_uint32;
var box, dinf, esds, ftyp, mdat, mfhd, minf, moof, moov, mvex, mvhd, trak, tkhd, mdia, mdhd, hdlr, sdtp, stbl, stsd, traf, trex, trun$1, types, major_brand, minor_version, avc1_brand, video_hdlr, audio_hdlr, hdlr_types, vmhd, smhd, dref, stco, stsc, stsz, stts; // pre-calculate constants
(function () {
var i;
types = {
avc1: [],
// codingname
avcc: [],
btrt: [],
dinf: [],
dref: [],
esds: [],
ftyp: [],
hdlr: [],
mdat: [],
mdhd: [],
mdia: [],
mfhd: [],
minf: [],
moof: [],
moov: [],
mp4a: [],
// codingname
mvex: [],
mvhd: [],
pasp: [],
sdtp: [],
smhd: [],
stbl: [],
stco: [],
stsc: [],
stsd: [],
stsz: [],
stts: [],
styp: [],
tfdt: [],
tfhd: [],
traf: [],
trak: [],
trun: [],
trex: [],
tkhd: [],
vmhd: []
}; // in environments where uint8array is undefined (e.g., ie8), skip set up so that we
// don't throw an error
if (typeof uint8array === 'undefined') {
return;
}
for (i in types) {
if (types.hasownproperty(i)) {
types[i] = [i.charcodeat(0), i.charcodeat(1), i.charcodeat(2), i.charcodeat(3)];
}
}
major_brand = new uint8array(['i'.charcodeat(0), 's'.charcodeat(0), 'o'.charcodeat(0), 'm'.charcodeat(0)]);
avc1_brand = new uint8array(['a'.charcodeat(0), 'v'.charcodeat(0), 'c'.charcodeat(0), '1'.charcodeat(0)]);
minor_version = new uint8array([0, 0, 0, 1]);
video_hdlr = new uint8array([0x00, // version 0
0x00, 0x00, 0x00, // flags
0x00, 0x00, 0x00, 0x00, // pre_defined
0x76, 0x69, 0x64, 0x65, // handler_type: 'vide'
0x00, 0x00, 0x00, 0x00, // reserved
0x00, 0x00, 0x00, 0x00, // reserved
0x00, 0x00, 0x00, 0x00, // reserved
0x56, 0x69, 0x64, 0x65, 0x6f, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'videohandler'
]);
audio_hdlr = new uint8array([0x00, // version 0
0x00, 0x00, 0x00, // flags
0x00, 0x00, 0x00, 0x00, // pre_defined
0x73, 0x6f, 0x75, 0x6e, // handler_type: 'soun'
0x00, 0x00, 0x00, 0x00, // reserved
0x00, 0x00, 0x00, 0x00, // reserved
0x00, 0x00, 0x00, 0x00, // reserved
0x53, 0x6f, 0x75, 0x6e, 0x64, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'soundhandler'
]);
hdlr_types = {
video: video_hdlr,
audio: audio_hdlr
};
dref = new uint8array([0x00, // version 0
0x00, 0x00, 0x00, // flags
0x00, 0x00, 0x00, 0x01, // entry_count
0x00, 0x00, 0x00, 0x0c, // entry_size
0x75, 0x72, 0x6c, 0x20, // 'url' type
0x00, // version 0
0x00, 0x00, 0x01 // entry_flags
]);
smhd = new uint8array([0x00, // version
0x00, 0x00, 0x00, // flags
0x00, 0x00, // balance, 0 means centered
0x00, 0x00 // reserved
]);
stco = new uint8array([0x00, // version
0x00, 0x00, 0x00, // flags
0x00, 0x00, 0x00, 0x00 // entry_count
]);
stsc = stco;
stsz = new uint8array([0x00, // version
0x00, 0x00, 0x00, // flags
0x00, 0x00, 0x00, 0x00, // sample_size
0x00, 0x00, 0x00, 0x00 // sample_count
]);
stts = stco;
vmhd = new uint8array([0x00, // version
0x00, 0x00, 0x01, // flags
0x00, 0x00, // graphicsmode
0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // opcolor
]);
})();
box = function box(type) {
var payload = [],
size = 0,
i,
result,
view;
for (i = 1; i < arguments.length; i++) {
payload.push(arguments[i]);
}
i = payload.length; // calculate the total size we need to allocate
while (i--) {
size += payload[i].bytelength;
}
result = new uint8array(size + 8);
view = new dataview(result.buffer, result.byteoffset, result.bytelength);
view.setuint32(0, result.bytelength);
result.set(type, 4); // copy the payload into the result
for (i = 0, size = 8; i < payload.length; i++) {
result.set(payload[i], size);
size += payload[i].bytelength;
}
return result;
};
dinf = function dinf() {
return box(types.dinf, box(types.dref, dref));
};
esds = function esds(track) {
return box(types.esds, new uint8array([0x00, // version
0x00, 0x00, 0x00, // flags
// es_descriptor
0x03, // tag, es_descrtag
0x19, // length
0x00, 0x00, // es_id
0x00, // streamdependenceflag, url_flag, reserved, streampriority
// decoderconfigdescriptor
0x04, // tag, decoderconfigdescrtag
0x11, // length
0x40, // object type
0x15, // streamtype
0x00, 0x06, 0x00, // buffersizedb
0x00, 0x00, 0xda, 0xc0, // maxbitrate
0x00, 0x00, 0xda, 0xc0, // avgbitrate
// decoderspecificinfo
0x05, // tag, decoderspecificinfotag
0x02, // length
// iso/iec 14496-3, audiospecificconfig
// for samplingfrequencyindex see iso/iec 13818-7:2006, 8.1.3.2.2, table 35
track.audioobjecttype << 3 | track.samplingfrequencyindex >>> 1, track.samplingfrequencyindex << 7 | track.channelcount << 3, 0x06, 0x01, 0x02 // gaspecificconfig
]));
};
ftyp = function ftyp() {
return box(types.ftyp, major_brand, minor_version, major_brand, avc1_brand);
};
hdlr = function hdlr(type) {
return box(types.hdlr, hdlr_types[type]);
};
mdat = function mdat(data) {
return box(types.mdat, data);
};
mdhd = function mdhd(track) {
var result = new uint8array([0x00, // version 0
0x00, 0x00, 0x00, // flags
0x00, 0x00, 0x00, 0x02, // creation_time
0x00, 0x00, 0x00, 0x03, // modification_time
0x00, 0x01, 0x5f, 0x90, // timescale, 90,000 "ticks" per second
track.duration >>> 24 & 0xff, track.duration >>> 16 & 0xff, track.duration >>> 8 & 0xff, track.duration & 0xff, // duration
0x55, 0xc4, // 'und' language (undetermined)
0x00, 0x00]); // use the sample rate from the track metadata, when it is
// defined. the sample rate can be parsed out of an adts header, for
// instance.
if (track.samplerate) {
result[12] = track.samplerate >>> 24 & 0xff;
result[13] = track.samplerate >>> 16 & 0xff;
result[14] = track.samplerate >>> 8 & 0xff;
result[15] = track.samplerate & 0xff;
}
return box(types.mdhd, result);
};
mdia = function mdia(track) {
return box(types.mdia, mdhd(track), hdlr(track.type), minf(track));
};
mfhd = function mfhd(sequencenumber) {
return box(types.mfhd, new uint8array([0x00, 0x00, 0x00, 0x00, // flags
(sequencenumber & 0xff000000) >> 24, (sequencenumber & 0xff0000) >> 16, (sequencenumber & 0xff00) >> 8, sequencenumber & 0xff // sequence_number
]));
};
minf = function minf(track) {
return box(types.minf, track.type === 'video' ? box(types.vmhd, vmhd) : box(types.smhd, smhd), dinf(), stbl(track));
};
moof = function moof(sequencenumber, tracks) {
var trackfragments = [],
i = tracks.length; // build traf boxes for each track fragment
while (i--) {
trackfragments[i] = traf(tracks[i]);
}
return box.apply(null, [types.moof, mfhd(sequencenumber)].concat(trackfragments));
};
/**
* returns a movie box.
* @param tracks {array} the tracks associated with this movie
* @see iso/iec 14496-12:2012(e), section 8.2.1
*/
moov = function moov(tracks) {
var i = tracks.length,
boxes = [];
while (i--) {
boxes[i] = trak(tracks[i]);
}
return box.apply(null, [types.moov, mvhd(0xffffffff)].concat(boxes).concat(mvex(tracks)));
};
mvex = function mvex(tracks) {
var i = tracks.length,
boxes = [];
while (i--) {
boxes[i] = trex(tracks[i]);
}
return box.apply(null, [types.mvex].concat(boxes));
};
mvhd = function mvhd(duration) {
var bytes = new uint8array([0x00, // version 0
0x00, 0x00, 0x00, // flags
0x00, 0x00, 0x00, 0x01, // creation_time
0x00, 0x00, 0x00, 0x02, // modification_time
0x00, 0x01, 0x5f, 0x90, // timescale, 90,000 "ticks" per second
(duration & 0xff000000) >> 24, (duration & 0xff0000) >> 16, (duration & 0xff00) >> 8, duration & 0xff, // duration
0x00, 0x01, 0x00, 0x00, // 1.0 rate
0x01, 0x00, // 1.0 volume
0x00, 0x00, // reserved
0x00, 0x00, 0x00, 0x00, // reserved
0x00, 0x00, 0x00, 0x00, // reserved
0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, // transformation: unity matrix
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // pre_defined
0xff, 0xff, 0xff, 0xff // next_track_id
]);
return box(types.mvhd, bytes);
};
sdtp = function sdtp(track) {
var samples = track.samples || [],
bytes = new uint8array(4 + samples.length),
flags,
i; // leave the full box header (4 bytes) all zero
// write the sample table
for (i = 0; i < samples.length; i++) {
flags = samples[i].flags;
bytes[i + 4] = flags.dependson << 4 | flags.isdependedon << 2 | flags.hasredundancy;
}
return box(types.sdtp, bytes);
};
stbl = function stbl(track) {
return box(types.stbl, stsd(track), box(types.stts, stts), box(types.stsc, stsc), box(types.stsz, stsz), box(types.stco, stco));
};
(function () {
var videosample, audiosample;
stsd = function stsd(track) {
return box(types.stsd, new uint8array([0x00, // version 0
0x00, 0x00, 0x00, // flags
0x00, 0x00, 0x00, 0x01]), track.type === 'video' ? videosample(track) : audiosample(track));
};
videosample = function videosample(track) {
var sps = track.sps || [],
pps = track.pps || [],
sequenceparametersets = [],
pictureparametersets = [],
i,
avc1box; // assemble the spss
for (i = 0; i < sps.length; i++) {
sequenceparametersets.push((sps[i].bytelength & 0xff00) >>> 8);
sequenceparametersets.push(sps[i].bytelength & 0xff); // sequenceparametersetlength
sequenceparametersets = sequenceparametersets.concat(array.prototype.slice.call(sps[i])); // sps
} // assemble the ppss
for (i = 0; i < pps.length; i++) {
pictureparametersets.push((pps[i].bytelength & 0xff00) >>> 8);
pictureparametersets.push(pps[i].bytelength & 0xff);
pictureparametersets = pictureparametersets.concat(array.prototype.slice.call(pps[i]));
}
avc1box = [types.avc1, new uint8array([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
0x00, 0x01, // data_reference_index
0x00, 0x00, // pre_defined
0x00, 0x00, // reserved
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // pre_defined
(track.width & 0xff00) >> 8, track.width & 0xff, // width
(track.height & 0xff00) >> 8, track.height & 0xff, // height
0x00, 0x48, 0x00, 0x00, // horizresolution
0x00, 0x48, 0x00, 0x00, // vertresolution
0x00, 0x00, 0x00, 0x00, // reserved
0x00, 0x01, // frame_count
0x13, 0x76, 0x69, 0x64, 0x65, 0x6f, 0x6a, 0x73, 0x2d, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x69, 0x62, 0x2d, 0x68, 0x6c, 0x73, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // compressorname
0x00, 0x18, // depth = 24
0x11, 0x11 // pre_defined = -1
]), box(types.avcc, new uint8array([0x01, // configurationversion
track.profileidc, // avcprofileindication
track.profilecompatibility, // profile_compatibility
track.levelidc, // avclevelindication
0xff // lengthsizeminusone, hard-coded to 4 bytes
].concat([sps.length], // numofsequenceparametersets
sequenceparametersets, // "sps"
[pps.length], // numofpictureparametersets
pictureparametersets // "pps"
))), box(types.btrt, new uint8array([0x00, 0x1c, 0x9c, 0x80, // buffersizedb
0x00, 0x2d, 0xc6, 0xc0, // maxbitrate
0x00, 0x2d, 0xc6, 0xc0 // avgbitrate
]))];
if (track.sarratio) {
var hspacing = track.sarratio[0],
vspacing = track.sarratio[1];
avc1box.push(box(types.pasp, new uint8array([(hspacing & 0xff000000) >> 24, (hspacing & 0xff0000) >> 16, (hspacing & 0xff00) >> 8, hspacing & 0xff, (vspacing & 0xff000000) >> 24, (vspacing & 0xff0000) >> 16, (vspacing & 0xff00) >> 8, vspacing & 0xff])));
}
return box.apply(null, avc1box);
};
audiosample = function audiosample(track) {
return box(types.mp4a, new uint8array([// sampleentry, iso/iec 14496-12
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
0x00, 0x01, // data_reference_index
// audiosampleentry, iso/iec 14496-12
0x00, 0x00, 0x00, 0x00, // reserved
0x00, 0x00, 0x00, 0x00, // reserved
(track.channelcount & 0xff00) >> 8, track.channelcount & 0xff, // channelcount
(track.samplesize & 0xff00) >> 8, track.samplesize & 0xff, // samplesize
0x00, 0x00, // pre_defined
0x00, 0x00, // reserved
(track.samplerate & 0xff00) >> 8, track.samplerate & 0xff, 0x00, 0x00 // samplerate, 16.16
// mp4audiosampleentry, iso/iec 14496-14
]), esds(track));
};
})();
tkhd = function tkhd(track) {
var result = new uint8array([0x00, // version 0
0x00, 0x00, 0x07, // flags
0x00, 0x00, 0x00, 0x00, // creation_time
0x00, 0x00, 0x00, 0x00, // modification_time
(track.id & 0xff000000) >> 24, (track.id & 0xff0000) >> 16, (track.id & 0xff00) >> 8, track.id & 0xff, // track_id
0x00, 0x00, 0x00, 0x00, // reserved
(track.duration & 0xff000000) >> 24, (track.duration & 0xff0000) >> 16, (track.duration & 0xff00) >> 8, track.duration & 0xff, // duration
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
0x00, 0x00, // layer
0x00, 0x00, // alternate_group
0x01, 0x00, // non-audio track volume
0x00, 0x00, // reserved
0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, // transformation: unity matrix
(track.width & 0xff00) >> 8, track.width & 0xff, 0x00, 0x00, // width
(track.height & 0xff00) >> 8, track.height & 0xff, 0x00, 0x00 // height
]);
return box(types.tkhd, result);
};
/**
* generate a track fragment (traf) box. a traf box collects metadata
* about tracks in a movie fragment (moof) box.
*/
traf = function traf(track) {
var trackfragmentheader, trackfragmentdecodetime, trackfragmentrun, sampledependencytable, dataoffset, upperwordbasemediadecodetime, lowerwordbasemediadecodetime;
trackfragmentheader = box(types.tfhd, new uint8array([0x00, // version 0
0x00, 0x00, 0x3a, // flags
(track.id & 0xff000000) >> 24, (track.id & 0xff0000) >> 16, (track.id & 0xff00) >> 8, track.id & 0xff, // track_id
0x00, 0x00, 0x00, 0x01, // sample_description_index
0x00, 0x00, 0x00, 0x00, // default_sample_duration
0x00, 0x00, 0x00, 0x00, // default_sample_size
0x00, 0x00, 0x00, 0x00 // default_sample_flags
]));
upperwordbasemediadecodetime = math.floor(track.basemediadecodetime / max_uint32);
lowerwordbasemediadecodetime = math.floor(track.basemediadecodetime % max_uint32);
trackfragmentdecodetime = box(types.tfdt, new uint8array([0x01, // version 1
0x00, 0x00, 0x00, // flags
// basemediadecodetime
upperwordbasemediadecodetime >>> 24 & 0xff, upperwordbasemediadecodetime >>> 16 & 0xff, upperwordbasemediadecodetime >>> 8 & 0xff, upperwordbasemediadecodetime & 0xff, lowerwordbasemediadecodetime >>> 24 & 0xff, lowerwordbasemediadecodetime >>> 16 & 0xff, lowerwordbasemediadecodetime >>> 8 & 0xff, lowerwordbasemediadecodetime & 0xff])); // the data offset specifies the number of bytes from the start of
// the containing moof to the first payload byte of the associated
// mdat
dataoffset = 32 + // tfhd
20 + // tfdt
8 + // traf header
16 + // mfhd
8 + // moof header
8; // mdat header
// audio tracks require less metadata
if (track.type === 'audio') {
trackfragmentrun = trun$1(track, dataoffset);
return box(types.traf, trackfragmentheader, trackfragmentdecodetime, trackfragmentrun);
} // video tracks should contain an independent and disposable samples
// box (sdtp)
// generate one and adjust offsets to match
sampledependencytable = sdtp(track);
trackfragmentrun = trun$1(track, sampledependencytable.length + dataoffset);
return box(types.traf, trackfragmentheader, trackfragmentdecodetime, trackfragmentrun, sampledependencytable);
};
/**
* generate a track box.
* @param track {object} a track definition
* @return {uint8array} the track box
*/
trak = function trak(track) {
track.duration = track.duration || 0xffffffff;
return box(types.trak, tkhd(track), mdia(track));
};
trex = function trex(track) {
var result = new uint8array([0x00, // version 0
0x00, 0x00, 0x00, // flags
(track.id & 0xff000000) >> 24, (track.id & 0xff0000) >> 16, (track.id & 0xff00) >> 8, track.id & 0xff, // track_id
0x00, 0x00, 0x00, 0x01, // default_sample_description_index
0x00, 0x00, 0x00, 0x00, // default_sample_duration
0x00, 0x00, 0x00, 0x00, // default_sample_size
0x00, 0x01, 0x00, 0x01 // default_sample_flags
]); // the last two bytes of default_sample_flags is the sample
// degradation priority, a hint about the importance of this sample
// relative to others. lower the degradation priority for all sample
// types other than video.
if (track.type !== 'video') {
result[result.length - 1] = 0x00;
}
return box(types.trex, result);
};
(function () {
var audiotrun, videotrun, trunheader; // this method assumes all samples are uniform. that is, if a
// duration is present for the first sample, it will be present for
// all subsequent samples.
// see iso/iec 14496-12:2012, section 8.8.8.1
trunheader = function trunheader(samples, offset) {
var durationpresent = 0,
sizepresent = 0,
flagspresent = 0,
compositiontimeoffset = 0; // trun flag constants
if (samples.length) {
if (samples[0].duration !== undefined) {
durationpresent = 0x1;
}
if (samples[0].size !== undefined) {
sizepresent = 0x2;
}
if (samples[0].flags !== undefined) {
flagspresent = 0x4;
}
if (samples[0].compositiontimeoffset !== undefined) {
compositiontimeoffset = 0x8;
}
}
return [0x00, // version 0
0x00, durationpresent | sizepresent | flagspresent | compositiontimeoffset, 0x01, // flags
(samples.length & 0xff000000) >>> 24, (samples.length & 0xff0000) >>> 16, (samples.length & 0xff00) >>> 8, samples.length & 0xff, // sample_count
(offset & 0xff000000) >>> 24, (offset & 0xff0000) >>> 16, (offset & 0xff00) >>> 8, offset & 0xff // data_offset
];
};
videotrun = function videotrun(track, offset) {
var bytesoffest, bytes, header, samples, sample, i;
samples = track.samples || [];
offset += 8 + 12 + 16 * samples.length;
header = trunheader(samples, offset);
bytes = new uint8array(header.length + samples.length * 16);
bytes.set(header);
bytesoffest = header.length;
for (i = 0; i < samples.length; i++) {
sample = samples[i];
bytes[bytesoffest++] = (sample.duration & 0xff000000) >>> 24;
bytes[bytesoffest++] = (sample.duration & 0xff0000) >>> 16;
bytes[bytesoffest++] = (sample.duration & 0xff00) >>> 8;
bytes[bytesoffest++] = sample.duration & 0xff; // sample_duration
bytes[bytesoffest++] = (sample.size & 0xff000000) >>> 24;
bytes[bytesoffest++] = (sample.size & 0xff0000) >>> 16;
bytes[bytesoffest++] = (sample.size & 0xff00) >>> 8;
bytes[bytesoffest++] = sample.size & 0xff; // sample_size
bytes[bytesoffest++] = sample.flags.isleading << 2 | sample.flags.dependson;
bytes[bytesoffest++] = sample.flags.isdependedon << 6 | sample.flags.hasredundancy << 4 | sample.flags.paddingvalue << 1 | sample.flags.isnonsyncsample;
bytes[bytesoffest++] = sample.flags.degradationpriority & 0xf0 << 8;
bytes[bytesoffest++] = sample.flags.degradationpriority & 0x0f; // sample_flags
bytes[bytesoffest++] = (sample.compositiontimeoffset & 0xff000000) >>> 24;
bytes[bytesoffest++] = (sample.compositiontimeoffset & 0xff0000) >>> 16;
bytes[bytesoffest++] = (sample.compositiontimeoffset & 0xff00) >>> 8;
bytes[bytesoffest++] = sample.compositiontimeoffset & 0xff; // sample_composition_time_offset
}
return box(types.trun, bytes);
};
audiotrun = function audiotrun(track, offset) {
var bytes, bytesoffest, header, samples, sample, i;
samples = track.samples || [];
offset += 8 + 12 + 8 * samples.length;
header = trunheader(samples, offset);
bytes = new uint8array(header.length + samples.length * 8);
bytes.set(header);
bytesoffest = header.length;
for (i = 0; i < samples.length; i++) {
sample = samples[i];
bytes[bytesoffest++] = (sample.duration & 0xff000000) >>> 24;
bytes[bytesoffest++] = (sample.duration & 0xff0000) >>> 16;
bytes[bytesoffest++] = (sample.duration & 0xff00) >>> 8;
bytes[bytesoffest++] = sample.duration & 0xff; // sample_duration
bytes[bytesoffest++] = (sample.size & 0xff000000) >>> 24;
bytes[bytesoffest++] = (sample.size & 0xff0000) >>> 16;
bytes[bytesoffest++] = (sample.size & 0xff00) >>> 8;
bytes[bytesoffest++] = sample.size & 0xff; // sample_size
}
return box(types.trun, bytes);
};
trun$1 = function trun(track, offset) {
if (track.type === 'audio') {
return audiotrun(track, offset);
}
return videotrun(track, offset);
};
})();
var mp4generator = {
ftyp: ftyp,
mdat: mdat,
moof: moof,
moov: moov,
initsegment: function initsegment(tracks) {
var filetype = ftyp(),
movie = moov(tracks),
result;
result = new uint8array(filetype.bytelength + movie.bytelength);
result.set(filetype);
result.set(movie, filetype.bytelength);
return result;
}
};
/**
* mux.js
*
* copyright (c) brightcove
* licensed apache-2.0 https://github.com/videojs/mux.js/blob/master/license
*/
// convert an array of nal units into an array of frames with each frame being
// composed of the nal units that make up that frame
// also keep track of cummulative data about the frame from the nal units such
// as the frame duration, starting pts, etc.
var groupnalsintoframes = function groupnalsintoframes(nalunits) {
var i,
currentnal,
currentframe = [],
frames = []; // todo added for lhls, make sure this is ok
frames.bytelength = 0;
frames.nalcount = 0;
frames.duration = 0;
currentframe.bytelength = 0;
for (i = 0; i < nalunits.length; i++) {
currentnal = nalunits[i]; // split on 'aud'-type nal units
if (currentnal.nalunittype === 'access_unit_delimiter_rbsp') {
// since the very first nal unit is expected to be an aud
// only push to the frames array when currentframe is not empty
if (currentframe.length) {
currentframe.duration = currentnal.dts - currentframe.dts; // todo added for lhls, make sure this is ok
frames.bytelength += currentframe.bytelength;
frames.nalcount += currentframe.length;
frames.duration += currentframe.duration;
frames.push(currentframe);
}
currentframe = [currentnal];
currentframe.bytelength = currentnal.data.bytelength;
currentframe.pts = currentnal.pts;
currentframe.dts = currentnal.dts;
} else {
// specifically flag key frames for ease of use later
if (currentnal.nalunittype === 'slice_layer_without_partitioning_rbsp_idr') {
currentframe.keyframe = true;
}
currentframe.duration = currentnal.dts - currentframe.dts;
currentframe.bytelength += currentnal.data.bytelength;
currentframe.push(currentnal);
}
} // for the last frame, use the duration of the previous frame if we
// have nothing better to go on
if (frames.length && (!currentframe.duration || currentframe.duration <= 0)) {
currentframe.duration = frames[frames.length - 1].duration;
} // push the final frame
// todo added for lhls, make sure this is ok
frames.bytelength += currentframe.bytelength;
frames.nalcount += currentframe.length;
frames.duration += currentframe.duration;
frames.push(currentframe);
return frames;
}; // convert an array of frames into an array of gop with each gop being composed
// of the frames that make up that gop
// also keep track of cummulative data about the gop from the frames such as the
// gop duration, starting pts, etc.
var groupframesintogops = function groupframesintogops(frames) {
var i,
currentframe,
currentgop = [],
gops = []; // we must pre-set some of the values on the gop since we
// keep running totals of these values
currentgop.bytelength = 0;
currentgop.nalcount = 0;
currentgop.duration = 0;
currentgop.pts = frames[0].pts;
currentgop.dts = frames[0].dts; // store some metadata about all the gops
gops.bytelength = 0;
gops.nalcount = 0;
gops.duration = 0;
gops.pts = frames[0].pts;
gops.dts = frames[0].dts;
for (i = 0; i < frames.length; i++) {
currentframe = frames[i];
if (currentframe.keyframe) {
// since the very first frame is expected to be an keyframe
// only push to the gops array when currentgop is not empty
if (currentgop.length) {
gops.push(currentgop);
gops.bytelength += currentgop.bytelength;
gops.nalcount += currentgop.nalcount;
gops.duration += currentgop.duration;
}
currentgop = [currentframe];
currentgop.nalcount = currentframe.length;
currentgop.bytelength = currentframe.bytelength;
currentgop.pts = currentframe.pts;
currentgop.dts = currentframe.dts;
currentgop.duration = currentframe.duration;
} else {
currentgop.duration += currentframe.duration;
currentgop.nalcount += currentframe.length;
currentgop.bytelength += currentframe.bytelength;
currentgop.push(currentframe);
}
}
if (gops.length && currentgop.duration <= 0) {
currentgop.duration = gops[gops.length - 1].duration;
}
gops.bytelength += currentgop.bytelength;
gops.nalcount += currentgop.nalcount;
gops.duration += currentgop.duration; // push the final gop
gops.push(currentgop);
return gops;
};
/*
* search for the first keyframe in the gops and throw away all frames
* until that keyframe. then extend the duration of the pulled keyframe
* and pull the pts and dts of the keyframe so that it covers the time
* range of the frames that were disposed.
*
* @param {array} gops video gops
* @returns {array} modified video gops
*/
var extendfirstkeyframe = function extendfirstkeyframe(gops) {
var currentgop;
if (!gops[0][0].keyframe && gops.length > 1) {
// remove the first gop
currentgop = gops.shift();
gops.bytelength -= currentgop.bytelength;
gops.nalcount -= currentgop.nalcount; // extend the first frame of what is now the
// first gop to cover the time period of the
// frames we just removed
gops[0][0].dts = currentgop.dts;
gops[0][0].pts = currentgop.pts;
gops[0][0].duration += currentgop.duration;
}
return gops;
};
/**
* default sample object
* see iso/iec 14496-12:2012, section 8.6.4.3
*/
var createdefaultsample = function createdefaultsample() {
return {
size: 0,
flags: {
isleading: 0,
dependson: 1,
isdependedon: 0,
hasredundancy: 0,
degradationpriority: 0,
isnonsyncsample: 1
}
};
};
/*
* collates information from a video frame into an object for eventual
* entry into an mp4 sample table.
*
* @param {object} frame the video frame
* @param {number} dataoffset the byte offset to position the sample
* @return {object} object containing sample table info for a frame
*/
var sampleforframe = function sampleforframe(frame, dataoffset) {
var sample = createdefaultsample();
sample.dataoffset = dataoffset;
sample.compositiontimeoffset = frame.pts - frame.dts;
sample.duration = frame.duration;
sample.size = 4 * frame.length; // space for nal unit size
sample.size += frame.bytelength;
if (frame.keyframe) {
sample.flags.dependson = 2;
sample.flags.isnonsyncsample = 0;
}
return sample;
}; // generate the track's sample table from an array of gops
var generatesampletable$1 = function generatesampletable(gops, basedataoffset) {
var h,
i,
sample,
currentgop,
currentframe,
dataoffset = basedataoffset || 0,
samples = [];
for (h = 0; h < gops.length; h++) {
currentgop = gops[h];
for (i = 0; i < currentgop.length; i++) {
currentframe = currentgop[i];
sample = sampleforframe(currentframe, dataoffset);
dataoffset += sample.size;
samples.push(sample);
}
}
return samples;
}; // generate the track's raw mdat data from an array of gops
var concatenatenaldata = function concatenatenaldata(gops) {
var h,
i,
j,
currentgop,
currentframe,
currentnal,
dataoffset = 0,
nalsbytelength = gops.bytelength,
numberofnals = gops.nalcount,
totalbytelength = nalsbytelength + 4 * numberofnals,
data = new uint8array(totalbytelength),
view = new dataview(data.buffer); // for each gop..
for (h = 0; h < gops.length; h++) {
currentgop = gops[h]; // for each frame..
for (i = 0; i < currentgop.length; i++) {
currentframe = currentgop[i]; // for each nal..
for (j = 0; j < currentframe.length; j++) {
currentnal = currentframe[j];
view.setuint32(dataoffset, currentnal.data.bytelength);
dataoffset += 4;
data.set(currentnal.data, dataoffset);
dataoffset += currentnal.data.bytelength;
}
}
}
return data;
}; // generate the track's sample table from a frame
var generatesampletableforframe = function generatesampletableforframe(frame, basedataoffset) {
var sample,
dataoffset = basedataoffset || 0,
samples = [];
sample = sampleforframe(frame, dataoffset);
samples.push(sample);
return samples;
}; // generate the track's raw mdat data from a frame
var concatenatenaldataforframe = function concatenatenaldataforframe(frame) {
var i,
currentnal,
dataoffset = 0,
nalsbytelength = frame.bytelength,
numberofnals = frame.length,
totalbytelength = nalsbytelength + 4 * numberofnals,
data = new uint8array(totalbytelength),
view = new dataview(data.buffer); // for each nal..
for (i = 0; i < frame.length; i++) {
currentnal = frame[i];
view.setuint32(dataoffset, currentnal.data.bytelength);
dataoffset += 4;
data.set(currentnal.data, dataoffset);
dataoffset += currentnal.data.bytelength;
}
return data;
};
var frameutils = {
groupnalsintoframes: groupnalsintoframes,
groupframesintogops: groupframesintogops,
extendfirstkeyframe: extendfirstkeyframe,
generatesampletable: generatesampletable$1,
concatenatenaldata: concatenatenaldata,
generatesampletableforframe: generatesampletableforframe,
concatenatenaldataforframe: concatenatenaldataforframe
};
/**
* mux.js
*
* copyright (c) brightcove
* licensed apache-2.0 https://github.com/videojs/mux.js/blob/master/license
*/
var highprefix = [33, 16, 5, 32, 164, 27];
var lowprefix = [33, 65, 108, 84, 1, 2, 4, 8, 168, 2, 4, 8, 17, 191, 252];
var zerofill = function zerofill(count) {
var a = [];
while (count--) {
a.push(0);
}
return a;
};
var maketable = function maketable(metatable) {
return object.keys(metatable).reduce(function (obj, key) {
obj[key] = new uint8array(metatable[key].reduce(function (arr, part) {
return arr.concat(part);
}, []));
return obj;
}, {});
};
var silence;
var silence_1 = function silence_1() {
if (!silence) {
// frames-of-silence to use for filling in missing aac frames
var coneofsilence = {
96000: [highprefix, [227, 64], zerofill(154), [56]],
88200: [highprefix, [231], zerofill(170), [56]],
64000: [highprefix, [248, 192], zerofill(240), [56]],
48000: [highprefix, [255, 192], zerofill(268), [55, 148, 128], zerofill(54), [112]],
44100: [highprefix, [255, 192], zerofill(268), [55, 163, 128], zerofill(84), [112]],
32000: [highprefix, [255, 192], zerofill(268), [55, 234], zerofill(226), [112]],
24000: [highprefix, [255, 192], zerofill(268), [55, 255, 128], zerofill(268), [111, 112], zerofill(126), [224]],
16000: [highprefix, [255, 192], zerofill(268), [55, 255, 128], zerofill(268), [111, 255], zerofill(269), [223, 108], zerofill(195), [1, 192]],
12000: [lowprefix, zerofill(268), [3, 127, 248], zerofill(268), [6, 255, 240], zerofill(268), [13, 255, 224], zerofill(268), [27, 253, 128], zerofill(259), [56]],
11025: [lowprefix, zerofill(268), [3, 127, 248], zerofill(268), [6, 255, 240], zerofill(268), [13, 255, 224], zerofill(268), [27, 255, 192], zerofill(268), [55, 175, 128], zerofill(108), [112]],
8000: [lowprefix, zerofill(268), [3, 121, 16], zerofill(47), [7]]
};
silence = maketable(coneofsilence);
}
return silence;
};
/**
* mux.js
*
* copyright (c) brightcove
* licensed apache-2.0 https://github.com/videojs/mux.js/blob/master/license
*/
var one_second_in_ts$4 = 90000,
// 90khz clock
secondstovideots,
secondstoaudiots,
videotstoseconds,
audiotstoseconds,
audiotstovideots,
videotstoaudiots,
metadatatstoseconds;
secondstovideots = function secondstovideots(seconds) {
return seconds * one_second_in_ts$4;
};
secondstoaudiots = function secondstoaudiots(seconds, samplerate) {
return seconds * samplerate;
};
videotstoseconds = function videotstoseconds(timestamp) {
return timestamp / one_second_in_ts$4;
};
audiotstoseconds = function audiotstoseconds(timestamp, samplerate) {
return timestamp / samplerate;
};
audiotstovideots = function audiotstovideots(timestamp, samplerate) {
return secondstovideots(audiotstoseconds(timestamp, samplerate));
};
videotstoaudiots = function videotstoaudiots(timestamp, samplerate) {
return secondstoaudiots(videotstoseconds(timestamp), samplerate);
};
/**
* adjust id3 tag or caption timing information by the timeline pts values
* (if keeporiginaltimestamps is false) and convert to seconds
*/
metadatatstoseconds = function metadatatstoseconds(timestamp, timelinestartpts, keeporiginaltimestamps) {
return videotstoseconds(keeporiginaltimestamps ? timestamp : timestamp - timelinestartpts);
};
var clock = {
one_second_in_ts: one_second_in_ts$4,
secondstovideots: secondstovideots,
secondstoaudiots: secondstoaudiots,
videotstoseconds: videotstoseconds,
audiotstoseconds: audiotstoseconds,
audiotstovideots: audiotstovideots,
videotstoaudiots: videotstoaudiots,
metadatatstoseconds: metadatatstoseconds
};
/**
* mux.js
*
* copyright (c) brightcove
* licensed apache-2.0 https://github.com/videojs/mux.js/blob/master/license
*/
/**
* sum the `bytelength` properties of the data in each aac frame
*/
var sumframebytelengths = function sumframebytelengths(array) {
var i,
currentobj,
sum = 0; // sum the bytelength's all each nal unit in the frame
for (i = 0; i < array.length; i++) {
currentobj = array[i];
sum += currentobj.data.bytelength;
}
return sum;
}; // possibly pad (prefix) the audio track with silence if appending this track
// would lead to the introduction of a gap in the audio buffer
var prefixwithsilence = function prefixwithsilence(track, frames, audioappendstartts, videobasemediadecodetime) {
var basemediadecodetimets,
frameduration = 0,
audiogapduration = 0,
audiofillframecount = 0,
audiofillduration = 0,
silentframe,
i,
firstframe;
if (!frames.length) {
return;
}
basemediadecodetimets = clock.audiotstovideots(track.basemediadecodetime, track.samplerate); // determine frame clock duration based on sample rate, round up to avoid overfills
frameduration = math.ceil(clock.one_second_in_ts / (track.samplerate / 1024));
if (audioappendstartts && videobasemediadecodetime) {
// insert the shortest possible amount (audio gap or audio to video gap)
audiogapduration = basemediadecodetimets - math.max(audioappendstartts, videobasemediadecodetime); // number of full frames in the audio gap
audiofillframecount = math.floor(audiogapduration / frameduration);
audiofillduration = audiofillframecount * frameduration;
} // don't attempt to fill gaps smaller than a single frame or larger
// than a half second
if (audiofillframecount < 1 || audiofillduration > clock.one_second_in_ts / 2) {
return;
}
silentframe = silence_1()[track.samplerate];
if (!silentframe) {
// we don't have a silent frame pregenerated for the sample rate, so use a frame
// from the content instead
silentframe = frames[0].data;
}
for (i = 0; i < audiofillframecount; i++) {
firstframe = frames[0];
frames.splice(0, 0, {
data: silentframe,
dts: firstframe.dts - frameduration,
pts: firstframe.pts - frameduration
});
}
track.basemediadecodetime -= math.floor(clock.videotstoaudiots(audiofillduration, track.samplerate));
return audiofillduration;
}; // if the audio segment extends before the earliest allowed dts
// value, remove aac frames until starts at or after the earliest
// allowed dts so that we don't end up with a negative basemedia-
// decodetime for the audio track
var trimadtsframesbyearliestdts = function trimadtsframesbyearliestdts(adtsframes, track, earliestalloweddts) {
if (track.minsegmentdts >= earliestalloweddts) {
return adtsframes;
} // we will need to recalculate the earliest segment dts
track.minsegmentdts = infinity;
return adtsframes.filter(function (currentframe) {
// if this is an allowed frame, keep it and record it's dts
if (currentframe.dts >= earliestalloweddts) {
track.minsegmentdts = math.min(track.minsegmentdts, currentframe.dts);
track.minsegmentpts = track.minsegmentdts;
return true;
} // otherwise, discard it
return false;
});
}; // generate the track's raw mdat data from an array of frames
var generatesampletable = function generatesampletable(frames) {
var i,
currentframe,
samples = [];
for (i = 0; i < frames.length; i++) {
currentframe = frames[i];
samples.push({
size: currentframe.data.bytelength,
duration: 1024 // for aac audio, all samples contain 1024 samples
});
}
return samples;
}; // generate the track's sample table from an array of frames
var concatenateframedata = function concatenateframedata(frames) {
var i,
currentframe,
dataoffset = 0,
data = new uint8array(sumframebytelengths(frames));
for (i = 0; i < frames.length; i++) {
currentframe = frames[i];
data.set(currentframe.data, dataoffset);
dataoffset += currentframe.data.bytelength;
}
return data;
};
var audioframeutils = {
prefixwithsilence: prefixwithsilence,
trimadtsframesbyearliestdts: trimadtsframesbyearliestdts,
generatesampletable: generatesampletable,
concatenateframedata: concatenateframedata
};
/**
* mux.js
*
* copyright (c) brightcove
* licensed apache-2.0 https://github.com/videojs/mux.js/blob/master/license
*/
var one_second_in_ts$3 = clock.one_second_in_ts;
/**
* store information about the start and end of the track and the
* duration for each frame/sample we process in order to calculate
* the basemediadecodetime
*/
var collectdtsinfo = function collectdtsinfo(track, data) {
if (typeof data.pts === 'number') {
if (track.timelinestartinfo.pts === undefined) {
track.timelinestartinfo.pts = data.pts;
}
if (track.minsegmentpts === undefined) {
track.minsegmentpts = data.pts;
} else {
track.minsegmentpts = math.min(track.minsegmentpts, data.pts);
}
if (track.maxsegmentpts === undefined) {
track.maxsegmentpts = data.pts;
} else {
track.maxsegmentpts = math.max(track.maxsegmentpts, data.pts);
}
}
if (typeof data.dts === 'number') {
if (track.timelinestartinfo.dts === undefined) {
track.timelinestartinfo.dts = data.dts;
}
if (track.minsegmentdts === undefined) {
track.minsegmentdts = data.dts;
} else {
track.minsegmentdts = math.min(track.minsegmentdts, data.dts);
}
if (track.maxsegmentdts === undefined) {
track.maxsegmentdts = data.dts;
} else {
track.maxsegmentdts = math.max(track.maxsegmentdts, data.dts);
}
}
};
/**
* clear values used to calculate the basemediadecodetime between
* tracks
*/
var cleardtsinfo = function cleardtsinfo(track) {
delete track.minsegmentdts;
delete track.maxsegmentdts;
delete track.minsegmentpts;
delete track.maxsegmentpts;
};
/**
* calculate the track's basemediadecodetime based on the earliest
* dts the transmuxer has ever seen and the minimum dts for the
* current track
* @param track {object} track metadata configuration
* @param keeporiginaltimestamps {boolean} if true, keep the timestamps
* in the source; false to adjust the first segment to start at 0.
*/
var calculatetrackbasemediadecodetime = function calculatetrackbasemediadecodetime(track, keeporiginaltimestamps) {
var basemediadecodetime,
scale,
minsegmentdts = track.minsegmentdts; // optionally adjust the time so the first segment starts at zero.
if (!keeporiginaltimestamps) {
minsegmentdts -= track.timelinestartinfo.dts;
} // track.timelinestartinfo.basemediadecodetime is the location, in time, where
// we want the start of the first segment to be placed
basemediadecodetime = track.timelinestartinfo.basemediadecodetime; // add to that the distance this segment is from the very first
basemediadecodetime += minsegmentdts; // basemediadecodetime must not become negative
basemediadecodetime = math.max(0, basemediadecodetime);
if (track.type === 'audio') {
// audio has a different clock equal to the sampling_rate so we need to
// scale the pts values into the clock rate of the track
scale = track.samplerate / one_second_in_ts$3;
basemediadecodetime *= scale;
basemediadecodetime = math.floor(basemediadecodetime);
}
return basemediadecodetime;
};
var trackdecodeinfo = {
cleardtsinfo: cleardtsinfo,
calculatetrackbasemediadecodetime: calculatetrackbasemediadecodetime,
collectdtsinfo: collectdtsinfo
};
/**
* mux.js
*
* copyright (c) brightcove
* licensed apache-2.0 https://github.com/videojs/mux.js/blob/master/license
*
* reads in-band caption information from a video elementary
* stream. captions must follow the cea-708 standard for injection
* into an mpeg-2 transport streams.
* @see https://en.wikipedia.org/wiki/cea-708
* @see https://www.gpo.gov/fdsys/pkg/cfr-2007-title47-vol1/pdf/cfr-2007-title47-vol1-sec15-119.pdf
*/
// payload type field to indicate how they are to be
// interpreted. ceas-708 caption content is always transmitted with
// payload type 0x04.
var user_data_registered_itu_t_t35 = 4,
rbsp_trailing_bits = 128;
/**
* parse a supplemental enhancement information (sei) nal unit.
* stops parsing once a message of type itu t t35 has been found.
*
* @param bytes {uint8array} the bytes of a sei nal unit
* @return {object} the parsed sei payload
* @see rec. itu-t h.264, 7.3.2.3.1
*/
var parsesei = function parsesei(bytes) {
var i = 0,
result = {
payloadtype: -1,
payloadsize: 0
},
payloadtype = 0,
payloadsize = 0; // go through the sei_rbsp parsing each each individual sei_message
while (i < bytes.bytelength) {
// stop once we have hit the end of the sei_rbsp
if (bytes[i] === rbsp_trailing_bits) {
break;
} // parse payload type
while (bytes[i] === 0xff) {
payloadtype += 255;
i++;
}
payloadtype += bytes[i++]; // parse payload size
while (bytes[i] === 0xff) {
payloadsize += 255;
i++;
}
payloadsize += bytes[i++]; // this sei_message is a 608/708 caption so save it and break
// there can only ever be one caption message in a frame's sei
if (!result.payload && payloadtype === user_data_registered_itu_t_t35) {
var useridentifier = string.fromcharcode(bytes[i + 3], bytes[i + 4], bytes[i + 5], bytes[i + 6]);
if (useridentifier === 'ga94') {
result.payloadtype = payloadtype;
result.payloadsize = payloadsize;
result.payload = bytes.subarray(i, i + payloadsize);
break;
} else {
result.payload = void 0;
}
} // skip the payload and parse the next message
i += payloadsize;
payloadtype = 0;
payloadsize = 0;
}
return result;
}; // see ansi/scte 128-1 (2013), section 8.1
var parseuserdata = function parseuserdata(sei) {
// itu_t_t35_contry_code must be 181 (united states) for
// captions
if (sei.payload[0] !== 181) {
return null;
} // itu_t_t35_provider_code should be 49 (atsc) for captions
if ((sei.payload[1] << 8 | sei.payload[2]) !== 49) {
return null;
} // the user_identifier should be "ga94" to indicate atsc1 data
if (string.fromcharcode(sei.payload[3], sei.payload[4], sei.payload[5], sei.payload[6]) !== 'ga94') {
return null;
} // finally, user_data_type_code should be 0x03 for caption data
if (sei.payload[7] !== 0x03) {
return null;
} // return the user_data_type_structure and strip the trailing
// marker bits
return sei.payload.subarray(8, sei.payload.length - 1);
}; // see cea-708-d, section 4.4
var parsecaptionpackets = function parsecaptionpackets(pts, userdata) {
var results = [],
i,
count,
offset,
data; // if this is just filler, return immediately
if (!(userdata[0] & 0x40)) {
return results;
} // parse out the cc_data_1 and cc_data_2 fields
count = userdata[0] & 0x1f;
for (i = 0; i < count; i++) {
offset = i * 3;
data = {
type: userdata[offset + 2] & 0x03,
pts: pts
}; // capture cc data when cc_valid is 1
if (userdata[offset + 2] & 0x04) {
data.ccdata = userdata[offset + 3] << 8 | userdata[offset + 4];
results.push(data);
}
}
return results;
};
var discardemulationpreventionbytes$1 = function discardemulationpreventionbytes(data) {
var length = data.bytelength,
emulationpreventionbytespositions = [],
i = 1,
newlength,
newdata; // find all `emulation prevention bytes`
while (i < length - 2) {
if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
emulationpreventionbytespositions.push(i + 2);
i += 2;
} else {
i++;
}
} // if no emulation prevention bytes were found just return the original
// array
if (emulationpreventionbytespositions.length === 0) {
return data;
} // create a new array to hold the nal unit data
newlength = length - emulationpreventionbytespositions.length;
newdata = new uint8array(newlength);
var sourceindex = 0;
for (i = 0; i < newlength; sourceindex++, i++) {
if (sourceindex === emulationpreventionbytespositions[0]) {
// skip this byte
sourceindex++; // remove this position index
emulationpreventionbytespositions.shift();
}
newdata[i] = data[sourceindex];
}
return newdata;
}; // exports
var captionpacketparser = {
parsesei: parsesei,
parseuserdata: parseuserdata,
parsecaptionpackets: parsecaptionpackets,
discardemulationpreventionbytes: discardemulationpreventionbytes$1,
user_data_registered_itu_t_t35: user_data_registered_itu_t_t35
}; // link to transport
// -----------------
var captionstream$1 = function captionstream(options) {
options = options || {};
captionstream.prototype.init.call(this); // parse708captions flag, default to true
this.parse708captions_ = typeof options.parse708captions === 'boolean' ? options.parse708captions : true;
this.captionpackets_ = [];
this.ccstreams_ = [new cea608stream(0, 0), // eslint-disable-line no-use-before-define
new cea608stream(0, 1), // eslint-disable-line no-use-before-define
new cea608stream(1, 0), // eslint-disable-line no-use-before-define
new cea608stream(1, 1) // eslint-disable-line no-use-before-define
];
if (this.parse708captions_) {
this.cc708stream_ = new cea708stream({
captionservices: options.captionservices
}); // eslint-disable-line no-use-before-define
}
this.reset(); // forward data and done events from ccs to this captionstream
this.ccstreams_.foreach(function (cc) {
cc.on('data', this.trigger.bind(this, 'data'));
cc.on('partialdone', this.trigger.bind(this, 'partialdone'));
cc.on('done', this.trigger.bind(this, 'done'));
}, this);
if (this.parse708captions_) {
this.cc708stream_.on('data', this.trigger.bind(this, 'data'));
this.cc708stream_.on('partialdone', this.trigger.bind(this, 'partialdone'));
this.cc708stream_.on('done', this.trigger.bind(this, 'done'));
}
};
captionstream$1.prototype = new stream();
captionstream$1.prototype.push = function (event) {
var sei, userdata, newcaptionpackets; // only examine sei nals
if (event.nalunittype !== 'sei_rbsp') {
return;
} // parse the sei
sei = captionpacketparser.parsesei(event.escapedrbsp); // no payload data, skip
if (!sei.payload) {
return;
} // ignore everything but user_data_registered_itu_t_t35
if (sei.payloadtype !== captionpacketparser.user_data_registered_itu_t_t35) {
return;
} // parse out the user data payload
userdata = captionpacketparser.parseuserdata(sei); // ignore unrecognized userdata
if (!userdata) {
return;
} // sometimes, the same segment # will be downloaded twice. to stop the
// caption data from being processed twice, we track the latest dts we've
// received and ignore everything with a dts before that. however, since
// data for a specific dts can be split across packets on either side of
// a segment boundary, we need to make sure we *don't* ignore the packets
// from the *next* segment that have dts === this.latestdts_. by constantly
// tracking the number of packets received with dts === this.latestdts_, we
// know how many should be ignored once we start receiving duplicates.
if (event.dts < this.latestdts_) {
// we've started getting older data, so set the flag.
this.ignorenextequaldts_ = true;
return;
} else if (event.dts === this.latestdts_ && this.ignorenextequaldts_) {
this.numsamedts_--;
if (!this.numsamedts_) {
// we've received the last duplicate packet, time to start processing again
this.ignorenextequaldts_ = false;
}
return;
} // parse out cc data packets and save them for later
newcaptionpackets = captionpacketparser.parsecaptionpackets(event.pts, userdata);
this.captionpackets_ = this.captionpackets_.concat(newcaptionpackets);
if (this.latestdts_ !== event.dts) {
this.numsamedts_ = 0;
}
this.numsamedts_++;
this.latestdts_ = event.dts;
};
captionstream$1.prototype.flushccstreams = function (flushtype) {
this.ccstreams_.foreach(function (cc) {
return flushtype === 'flush' ? cc.flush() : cc.partialflush();
}, this);
};
captionstream$1.prototype.flushstream = function (flushtype) {
// make sure we actually parsed captions before proceeding
if (!this.captionpackets_.length) {
this.flushccstreams(flushtype);
return;
} // in chrome, the array#sort function is not stable so add a
// presortindex that we can use to ensure we get a stable-sort
this.captionpackets_.foreach(function (elem, idx) {
elem.presortindex = idx;
}); // sort caption byte-pairs based on their pts values
this.captionpackets_.sort(function (a, b) {
if (a.pts === b.pts) {
return a.presortindex - b.presortindex;
}
return a.pts - b.pts;
});
this.captionpackets_.foreach(function (packet) {
if (packet.type < 2) {
// dispatch packet to the right cea608stream
this.dispatchcea608packet(packet);
} else {
// dispatch packet to the cea708stream
this.dispatchcea708packet(packet);
}
}, this);
this.captionpackets_.length = 0;
this.flushccstreams(flushtype);
};
captionstream$1.prototype.flush = function () {
return this.flushstream('flush');
}; // only called if handling partial data
captionstream$1.prototype.partialflush = function () {
return this.flushstream('partialflush');
};
captionstream$1.prototype.reset = function () {
this.latestdts_ = null;
this.ignorenextequaldts_ = false;
this.numsamedts_ = 0;
this.activecea608channel_ = [null, null];
this.ccstreams_.foreach(function (ccstream) {
ccstream.reset();
});
}; // from the cea-608 spec:
/*
* when xds sub-packets are interleaved with other services, the end of each sub-packet shall be followed
* by a control pair to change to a different service. when any of the control codes from 0x10 to 0x1f is
* used to begin a control code pair, it indicates the return to captioning or text data. the control code pair
* and subsequent data should then be processed according to the fcc rules. it may be necessary for the
* line 21 data encoder to automatically insert a control code pair (i.e. rcl, ru2, ru3, ru4, rdc, or rtd)
* to switch to captioning or text.
*/
// with that in mind, we ignore any data between an xds control code and a
// subsequent closed-captioning control code.
captionstream$1.prototype.dispatchcea608packet = function (packet) {
// note: packet.type is the cea608 field
if (this.setstextorxdsactive(packet)) {
this.activecea608channel_[packet.type] = null;
} else if (this.setschannel1active(packet)) {
this.activecea608channel_[packet.type] = 0;
} else if (this.setschannel2active(packet)) {
this.activecea608channel_[packet.type] = 1;
}
if (this.activecea608channel_[packet.type] === null) {
// if we haven't received anything to set the active channel, or the
// packets are text/xds data, discard the data; we don't want jumbled
// captions
return;
}
this.ccstreams_[(packet.type << 1) + this.activecea608channel_[packet.type]].push(packet);
};
captionstream$1.prototype.setschannel1active = function (packet) {
return (packet.ccdata & 0x7800) === 0x1000;
};
captionstream$1.prototype.setschannel2active = function (packet) {
return (packet.ccdata & 0x7800) === 0x1800;
};
captionstream$1.prototype.setstextorxdsactive = function (packet) {
return (packet.ccdata & 0x7100) === 0x0100 || (packet.ccdata & 0x78fe) === 0x102a || (packet.ccdata & 0x78fe) === 0x182a;
};
captionstream$1.prototype.dispatchcea708packet = function (packet) {
if (this.parse708captions_) {
this.cc708stream_.push(packet);
}
}; // ----------------------
// session to application
// ----------------------
// this hash maps special and extended character codes to their
// proper unicode equivalent. the first one-byte key is just a
// non-standard character code. the two-byte keys that follow are
// the extended cea708 character codes, along with the preceding
// 0x10 extended character byte to distinguish these codes from
// non-extended character codes. every cea708 character code that
// is not in this object maps directly to a standard unicode
// character code.
// the transparent space and non-breaking transparent space are
// technically not fully supported since there is no code to
// make them transparent, so they have normal non-transparent
// stand-ins.
// the special closed caption (cc) character isn't a standard
// unicode character, so a fairly similar unicode character was
// chosen in it's place.
var character_translation_708 = {
0x7f: 0x266a,
// ♪
0x1020: 0x20,
// transparent space
0x1021: 0xa0,
// nob-breaking transparent space
0x1025: 0x2026,
// …
0x102a: 0x0160,
// š
0x102c: 0x0152,
// œ
0x1030: 0x2588,
// █
0x1031: 0x2018,
// ‘
0x1032: 0x2019,
// ’
0x1033: 0x201c,
// “
0x1034: 0x201d,
// ”
0x1035: 0x2022,
// •
0x1039: 0x2122,
// ™
0x103a: 0x0161,
// š
0x103c: 0x0153,
// œ
0x103d: 0x2120,
// ℠
0x103f: 0x0178,
// ÿ
0x1076: 0x215b,
// ⅛
0x1077: 0x215c,
// ⅜
0x1078: 0x215d,
// ⅝
0x1079: 0x215e,
// ⅞
0x107a: 0x23d0,
// ⏐
0x107b: 0x23a4,
// ⎤
0x107c: 0x23a3,
// ⎣
0x107d: 0x23af,
// ⎯
0x107e: 0x23a6,
// ⎦
0x107f: 0x23a1,
// ⎡
0x10a0: 0x3138 // ㄸ (cc char)
};
var get708charfromcode = function get708charfromcode(code) {
var newcode = character_translation_708[code] || code;
if (code & 0x1000 && code === newcode) {
// invalid extended code
return '';
}
return string.fromcharcode(newcode);
};
var within708textblock = function within708textblock(b) {
return 0x20 <= b && b <= 0x7f || 0xa0 <= b && b <= 0xff;
};
var cea708window = function cea708window(windownum) {
this.windownum = windownum;
this.reset();
};
cea708window.prototype.reset = function () {
this.cleartext();
this.pendingnewline = false;
this.winattr = {};
this.penattr = {};
this.penloc = {};
this.pencolor = {}; // these default values are arbitrary,
// definewindow will usually override them
this.visible = 0;
this.rowlock = 0;
this.columnlock = 0;
this.priority = 0;
this.relativepositioning = 0;
this.anchorvertical = 0;
this.anchorhorizontal = 0;
this.anchorpoint = 0;
this.rowcount = 1;
this.virtualrowcount = this.rowcount + 1;
this.columncount = 41;
this.windowstyle = 0;
this.penstyle = 0;
};
cea708window.prototype.gettext = function () {
return this.rows.join('\n');
};
cea708window.prototype.cleartext = function () {
this.rows = [''];
this.rowidx = 0;
};
cea708window.prototype.newline = function (pts) {
if (this.rows.length >= this.virtualrowcount && typeof this.beforerowoverflow === 'function') {
this.beforerowoverflow(pts);
}
if (this.rows.length > 0) {
this.rows.push('');
this.rowidx++;
} // show all virtual rows since there's no visible scrolling
while (this.rows.length > this.virtualrowcount) {
this.rows.shift();
this.rowidx--;
}
};
cea708window.prototype.isempty = function () {
if (this.rows.length === 0) {
return true;
} else if (this.rows.length === 1) {
return this.rows[0] === '';
}
return false;
};
cea708window.prototype.addtext = function (text) {
this.rows[this.rowidx] += text;
};
cea708window.prototype.backspace = function () {
if (!this.isempty()) {
var row = this.rows[this.rowidx];
this.rows[this.rowidx] = row.substr(0, row.length - 1);
}
};
var cea708service = function cea708service(servicenum, encoding, stream) {
this.servicenum = servicenum;
this.text = '';
this.currentwindow = new cea708window(-1);
this.windows = [];
this.stream = stream; // try to setup a textdecoder if an `encoding` value was provided
if (typeof encoding === 'string') {
this.createtextdecoder(encoding);
}
};
/**
* initialize service windows
* must be run before service use
*
* @param {integer} pts pts value
* @param {function} beforerowoverflow function to execute before row overflow of a window
*/
cea708service.prototype.init = function (pts, beforerowoverflow) {
this.startpts = pts;
for (var win = 0; win < 8; win++) {
this.windows[win] = new cea708window(win);
if (typeof beforerowoverflow === 'function') {
this.windows[win].beforerowoverflow = beforerowoverflow;
}
}
};
/**
* set current window of service to be affected by commands
*
* @param {integer} windownum window number
*/
cea708service.prototype.setcurrentwindow = function (windownum) {
this.currentwindow = this.windows[windownum];
};
/**
* try to create a textdecoder if it is natively supported
*/
cea708service.prototype.createtextdecoder = function (encoding) {
if (typeof textdecoder === 'undefined') {
this.stream.trigger('log', {
level: 'warn',
message: 'the `encoding` option is unsupported without textdecoder support'
});
} else {
try {
this.textdecoder_ = new textdecoder(encoding);
} catch (error) {
this.stream.trigger('log', {
level: 'warn',
message: 'textdecoder could not be created with ' + encoding + ' encoding. ' + error
});
}
}
};
var cea708stream = function cea708stream(options) {
options = options || {};
cea708stream.prototype.init.call(this);
var self = this;
var captionservices = options.captionservices || {};
var captionserviceencodings = {};
var serviceprops; // get service encodings from captionservices option block
object.keys(captionservices).foreach(function (servicename) {
serviceprops = captionservices[servicename];
if (/^service/.test(servicename)) {
captionserviceencodings[servicename] = serviceprops.encoding;
}
});
this.serviceencodings = captionserviceencodings;
this.current708packet = null;
this.services = {};
this.push = function (packet) {
if (packet.type === 3) {
// 708 packet start
self.new708packet();
self.add708bytes(packet);
} else {
if (self.current708packet === null) {
// this should only happen at the start of a file if there's no packet start.
self.new708packet();
}
self.add708bytes(packet);
}
};
};
cea708stream.prototype = new stream();
/**
* push current 708 packet, create new 708 packet.
*/
cea708stream.prototype.new708packet = function () {
if (this.current708packet !== null) {
this.push708packet();
}
this.current708packet = {
data: [],
ptsvals: []
};
};
/**
* add pts and both bytes from packet into current 708 packet.
*/
cea708stream.prototype.add708bytes = function (packet) {
var data = packet.ccdata;
var byte0 = data >>> 8;
var byte1 = data & 0xff; // i would just keep a list of packets instead of bytes, but it isn't clear in the spec
// that service blocks will always line up with byte pairs.
this.current708packet.ptsvals.push(packet.pts);
this.current708packet.data.push(byte0);
this.current708packet.data.push(byte1);
};
/**
* parse completed 708 packet into service blocks and push each service block.
*/
cea708stream.prototype.push708packet = function () {
var packet708 = this.current708packet;
var packetdata = packet708.data;
var servicenum = null;
var blocksize = null;
var i = 0;
var b = packetdata[i++];
packet708.seq = b >> 6;
packet708.sizecode = b & 0x3f; // 0b00111111;
for (; i < packetdata.length; i++) {
b = packetdata[i++];
servicenum = b >> 5;
blocksize = b & 0x1f; // 0b00011111
if (servicenum === 7 && blocksize > 0) {
// extended service num
b = packetdata[i++];
servicenum = b;
}
this.pushserviceblock(servicenum, i, blocksize);
if (blocksize > 0) {
i += blocksize - 1;
}
}
};
/**
* parse service block, execute commands, read text.
*
* note: while many of these commands serve important purposes,
* many others just parse out the parameters or attributes, but
* nothing is done with them because this is not a full and complete
* implementation of the entire 708 spec.
*
* @param {integer} servicenum service number
* @param {integer} start start index of the 708 packet data
* @param {integer} size block size
*/
cea708stream.prototype.pushserviceblock = function (servicenum, start, size) {
var b;
var i = start;
var packetdata = this.current708packet.data;
var service = this.services[servicenum];
if (!service) {
service = this.initservice(servicenum, i);
}
for (; i < start + size && i < packetdata.length; i++) {
b = packetdata[i];
if (within708textblock(b)) {
i = this.handletext(i, service);
} else if (b === 0x18) {
i = this.multibytecharacter(i, service);
} else if (b === 0x10) {
i = this.extendedcommands(i, service);
} else if (0x80 <= b && b <= 0x87) {
i = this.setcurrentwindow(i, service);
} else if (0x98 <= b && b <= 0x9f) {
i = this.definewindow(i, service);
} else if (b === 0x88) {
i = this.clearwindows(i, service);
} else if (b === 0x8c) {
i = this.deletewindows(i, service);
} else if (b === 0x89) {
i = this.displaywindows(i, service);
} else if (b === 0x8a) {
i = this.hidewindows(i, service);
} else if (b === 0x8b) {
i = this.togglewindows(i, service);
} else if (b === 0x97) {
i = this.setwindowattributes(i, service);
} else if (b === 0x90) {
i = this.setpenattributes(i, service);
} else if (b === 0x91) {
i = this.setpencolor(i, service);
} else if (b === 0x92) {
i = this.setpenlocation(i, service);
} else if (b === 0x8f) {
service = this.reset(i, service);
} else if (b === 0x08) {
// bs: backspace
service.currentwindow.backspace();
} else if (b === 0x0c) {
// ff: form feed
service.currentwindow.cleartext();
} else if (b === 0x0d) {
// cr: carriage return
service.currentwindow.pendingnewline = true;
} else if (b === 0x0e) {
// hcr: horizontal carriage return
service.currentwindow.cleartext();
} else if (b === 0x8d) {
// dly: delay, nothing to do
i++;
} else ;
}
};
/**
* execute an extended command
*
* @param {integer} i current index in the 708 packet
* @param {service} service the service object to be affected
* @return {integer} new index after parsing
*/
cea708stream.prototype.extendedcommands = function (i, service) {
var packetdata = this.current708packet.data;
var b = packetdata[++i];
if (within708textblock(b)) {
i = this.handletext(i, service, {
isextended: true
});
}
return i;
};
/**
* get pts value of a given byte index
*
* @param {integer} byteindex index of the byte
* @return {integer} pts
*/
cea708stream.prototype.getpts = function (byteindex) {
// there's 1 pts value per 2 bytes
return this.current708packet.ptsvals[math.floor(byteindex / 2)];
};
/**
* initializes a service
*
* @param {integer} servicenum service number
* @return {service} initialized service object
*/
cea708stream.prototype.initservice = function (servicenum, i) {
var servicename = 'service' + servicenum;
var self = this;
var servicename;
var encoding;
if (servicename in this.serviceencodings) {
encoding = this.serviceencodings[servicename];
}
this.services[servicenum] = new cea708service(servicenum, encoding, self);
this.services[servicenum].init(this.getpts(i), function (pts) {
self.flushdisplayed(pts, self.services[servicenum]);
});
return this.services[servicenum];
};
/**
* execute text writing to current window
*
* @param {integer} i current index in the 708 packet
* @param {service} service the service object to be affected
* @return {integer} new index after parsing
*/
cea708stream.prototype.handletext = function (i, service, options) {
var isextended = options && options.isextended;
var ismultibyte = options && options.ismultibyte;
var packetdata = this.current708packet.data;
var extended = isextended ? 0x1000 : 0x0000;
var currentbyte = packetdata[i];
var nextbyte = packetdata[i + 1];
var win = service.currentwindow;
var _char;
var charcodearray; // use the textdecoder if one was created for this service
if (service.textdecoder_ && !isextended) {
if (ismultibyte) {
charcodearray = [currentbyte, nextbyte];
i++;
} else {
charcodearray = [currentbyte];
}
_char = service.textdecoder_.decode(new uint8array(charcodearray));
} else {
_char = get708charfromcode(extended | currentbyte);
}
if (win.pendingnewline && !win.isempty()) {
win.newline(this.getpts(i));
}
win.pendingnewline = false;
win.addtext(_char);
return i;
};
/**
* handle decoding of multibyte character
*
* @param {integer} i current index in the 708 packet
* @param {service} service the service object to be affected
* @return {integer} new index after parsing
*/
cea708stream.prototype.multibytecharacter = function (i, service) {
var packetdata = this.current708packet.data;
var firstbyte = packetdata[i + 1];
var secondbyte = packetdata[i + 2];
if (within708textblock(firstbyte) && within708textblock(secondbyte)) {
i = this.handletext(++i, service, {
ismultibyte: true
});
}
return i;
};
/**
* parse and execute the cw# command.
*
* set the current window.
*
* @param {integer} i current index in the 708 packet
* @param {service} service the service object to be affected
* @return {integer} new index after parsing
*/
cea708stream.prototype.setcurrentwindow = function (i, service) {
var packetdata = this.current708packet.data;
var b = packetdata[i];
var windownum = b & 0x07;
service.setcurrentwindow(windownum);
return i;
};
/**
* parse and execute the df# command.
*
* define a window and set it as the current window.
*
* @param {integer} i current index in the 708 packet
* @param {service} service the service object to be affected
* @return {integer} new index after parsing
*/
cea708stream.prototype.definewindow = function (i, service) {
var packetdata = this.current708packet.data;
var b = packetdata[i];
var windownum = b & 0x07;
service.setcurrentwindow(windownum);
var win = service.currentwindow;
b = packetdata[++i];
win.visible = (b & 0x20) >> 5; // v
win.rowlock = (b & 0x10) >> 4; // rl
win.columnlock = (b & 0x08) >> 3; // cl
win.priority = b & 0x07; // p
b = packetdata[++i];
win.relativepositioning = (b & 0x80) >> 7; // rp
win.anchorvertical = b & 0x7f; // av
b = packetdata[++i];
win.anchorhorizontal = b; // ah
b = packetdata[++i];
win.anchorpoint = (b & 0xf0) >> 4; // ap
win.rowcount = b & 0x0f; // rc
b = packetdata[++i];
win.columncount = b & 0x3f; // cc
b = packetdata[++i];
win.windowstyle = (b & 0x38) >> 3; // ws
win.penstyle = b & 0x07; // ps
// the spec says there are (rowcount+1) "virtual rows"
win.virtualrowcount = win.rowcount + 1;
return i;
};
/**
* parse and execute the swa command.
*
* set attributes of the current window.
*
* @param {integer} i current index in the 708 packet
* @param {service} service the service object to be affected
* @return {integer} new index after parsing
*/
cea708stream.prototype.setwindowattributes = function (i, service) {
var packetdata = this.current708packet.data;
var b = packetdata[i];
var winattr = service.currentwindow.winattr;
b = packetdata[++i];
winattr.fillopacity = (b & 0xc0) >> 6; // fo
winattr.fillred = (b & 0x30) >> 4; // fr
winattr.fillgreen = (b & 0x0c) >> 2; // fg
winattr.fillblue = b & 0x03; // fb
b = packetdata[++i];
winattr.bordertype = (b & 0xc0) >> 6; // bt
winattr.borderred = (b & 0x30) >> 4; // br
winattr.bordergreen = (b & 0x0c) >> 2; // bg
winattr.borderblue = b & 0x03; // bb
b = packetdata[++i];
winattr.bordertype += (b & 0x80) >> 5; // bt
winattr.wordwrap = (b & 0x40) >> 6; // ww
winattr.printdirection = (b & 0x30) >> 4; // pd
winattr.scrolldirection = (b & 0x0c) >> 2; // sd
winattr.justify = b & 0x03; // j
b = packetdata[++i];
winattr.effectspeed = (b & 0xf0) >> 4; // es
winattr.effectdirection = (b & 0x0c) >> 2; // ed
winattr.displayeffect = b & 0x03; // de
return i;
};
/**
* gather text from all displayed windows and push a caption to output.
*
* @param {integer} i current index in the 708 packet
* @param {service} service the service object to be affected
*/
cea708stream.prototype.flushdisplayed = function (pts, service) {
var displayedtext = []; // todo: positioning not supported, displaying multiple windows will not necessarily
// display text in the correct order, but sample files so far have not shown any issue.
for (var winid = 0; winid < 8; winid++) {
if (service.windows[winid].visible && !service.windows[winid].isempty()) {
displayedtext.push(service.windows[winid].gettext());
}
}
service.endpts = pts;
service.text = displayedtext.join('\n\n');
this.pushcaption(service);
service.startpts = pts;
};
/**
* push a caption to output if the caption contains text.
*
* @param {service} service the service object to be affected
*/
cea708stream.prototype.pushcaption = function (service) {
if (service.text !== '') {
this.trigger('data', {
startpts: service.startpts,
endpts: service.endpts,
text: service.text,
stream: 'cc708_' + service.servicenum
});
service.text = '';
service.startpts = service.endpts;
}
};
/**
* parse and execute the dsw command.
*
* set visible property of windows based on the parsed bitmask.
*
* @param {integer} i current index in the 708 packet
* @param {service} service the service object to be affected
* @return {integer} new index after parsing
*/
cea708stream.prototype.displaywindows = function (i, service) {
var packetdata = this.current708packet.data;
var b = packetdata[++i];
var pts = this.getpts(i);
this.flushdisplayed(pts, service);
for (var winid = 0; winid < 8; winid++) {
if (b & 0x01 << winid) {
service.windows[winid].visible = 1;
}
}
return i;
};
/**
* parse and execute the hdw command.
*
* set visible property of windows based on the parsed bitmask.
*
* @param {integer} i current index in the 708 packet
* @param {service} service the service object to be affected
* @return {integer} new index after parsing
*/
cea708stream.prototype.hidewindows = function (i, service) {
var packetdata = this.current708packet.data;
var b = packetdata[++i];
var pts = this.getpts(i);
this.flushdisplayed(pts, service);
for (var winid = 0; winid < 8; winid++) {
if (b & 0x01 << winid) {
service.windows[winid].visible = 0;
}
}
return i;
};
/**
* parse and execute the tgw command.
*
* set visible property of windows based on the parsed bitmask.
*
* @param {integer} i current index in the 708 packet
* @param {service} service the service object to be affected
* @return {integer} new index after parsing
*/
cea708stream.prototype.togglewindows = function (i, service) {
var packetdata = this.current708packet.data;
var b = packetdata[++i];
var pts = this.getpts(i);
this.flushdisplayed(pts, service);
for (var winid = 0; winid < 8; winid++) {
if (b & 0x01 << winid) {
service.windows[winid].visible ^= 1;
}
}
return i;
};
/**
* parse and execute the clw command.
*
* clear text of windows based on the parsed bitmask.
*
* @param {integer} i current index in the 708 packet
* @param {service} service the service object to be affected
* @return {integer} new index after parsing
*/
cea708stream.prototype.clearwindows = function (i, service) {
var packetdata = this.current708packet.data;
var b = packetdata[++i];
var pts = this.getpts(i);
this.flushdisplayed(pts, service);
for (var winid = 0; winid < 8; winid++) {
if (b & 0x01 << winid) {
service.windows[winid].cleartext();
}
}
return i;
};
/**
* parse and execute the dlw command.
*
* re-initialize windows based on the parsed bitmask.
*
* @param {integer} i current index in the 708 packet
* @param {service} service the service object to be affected
* @return {integer} new index after parsing
*/
cea708stream.prototype.deletewindows = function (i, service) {
var packetdata = this.current708packet.data;
var b = packetdata[++i];
var pts = this.getpts(i);
this.flushdisplayed(pts, service);
for (var winid = 0; winid < 8; winid++) {
if (b & 0x01 << winid) {
service.windows[winid].reset();
}
}
return i;
};
/**
* parse and execute the spa command.
*
* set pen attributes of the current window.
*
* @param {integer} i current index in the 708 packet
* @param {service} service the service object to be affected
* @return {integer} new index after parsing
*/
cea708stream.prototype.setpenattributes = function (i, service) {
var packetdata = this.current708packet.data;
var b = packetdata[i];
var penattr = service.currentwindow.penattr;
b = packetdata[++i];
penattr.texttag = (b & 0xf0) >> 4; // tt
penattr.offset = (b & 0x0c) >> 2; // o
penattr.pensize = b & 0x03; // s
b = packetdata[++i];
penattr.italics = (b & 0x80) >> 7; // i
penattr.underline = (b & 0x40) >> 6; // u
penattr.edgetype = (b & 0x38) >> 3; // et
penattr.fontstyle = b & 0x07; // fs
return i;
};
/**
* parse and execute the spc command.
*
* set pen color of the current window.
*
* @param {integer} i current index in the 708 packet
* @param {service} service the service object to be affected
* @return {integer} new index after parsing
*/
cea708stream.prototype.setpencolor = function (i, service) {
var packetdata = this.current708packet.data;
var b = packetdata[i];
var pencolor = service.currentwindow.pencolor;
b = packetdata[++i];
pencolor.fgopacity = (b & 0xc0) >> 6; // fo
pencolor.fgred = (b & 0x30) >> 4; // fr
pencolor.fggreen = (b & 0x0c) >> 2; // fg
pencolor.fgblue = b & 0x03; // fb
b = packetdata[++i];
pencolor.bgopacity = (b & 0xc0) >> 6; // bo
pencolor.bgred = (b & 0x30) >> 4; // br
pencolor.bggreen = (b & 0x0c) >> 2; // bg
pencolor.bgblue = b & 0x03; // bb
b = packetdata[++i];
pencolor.edgered = (b & 0x30) >> 4; // er
pencolor.edgegreen = (b & 0x0c) >> 2; // eg
pencolor.edgeblue = b & 0x03; // eb
return i;
};
/**
* parse and execute the spl command.
*
* set pen location of the current window.
*
* @param {integer} i current index in the 708 packet
* @param {service} service the service object to be affected
* @return {integer} new index after parsing
*/
cea708stream.prototype.setpenlocation = function (i, service) {
var packetdata = this.current708packet.data;
var b = packetdata[i];
var penloc = service.currentwindow.penloc; // positioning isn't really supported at the moment, so this essentially just inserts a linebreak
service.currentwindow.pendingnewline = true;
b = packetdata[++i];
penloc.row = b & 0x0f; // r
b = packetdata[++i];
penloc.column = b & 0x3f; // c
return i;
};
/**
* execute the rst command.
*
* reset service to a clean slate. re-initialize.
*
* @param {integer} i current index in the 708 packet
* @param {service} service the service object to be affected
* @return {service} re-initialized service
*/
cea708stream.prototype.reset = function (i, service) {
var pts = this.getpts(i);
this.flushdisplayed(pts, service);
return this.initservice(service.servicenum, i);
}; // this hash maps non-ascii, special, and extended character codes to their
// proper unicode equivalent. the first keys that are only a single byte
// are the non-standard ascii characters, which simply map the cea608 byte
// to the standard ascii/unicode. the two-byte keys that follow are the cea608
// character codes, but have their msb bitmasked with 0x03 so that a lookup
// can be performed regardless of the field and data channel on which the
// character code was received.
var character_translation = {
0x2a: 0xe1,
// á
0x5c: 0xe9,
// é
0x5e: 0xed,
// í
0x5f: 0xf3,
// ó
0x60: 0xfa,
// ú
0x7b: 0xe7,
// ç
0x7c: 0xf7,
// ÷
0x7d: 0xd1,
// ñ
0x7e: 0xf1,
// ñ
0x7f: 0x2588,
// █
0x0130: 0xae,
// ®
0x0131: 0xb0,
// °
0x0132: 0xbd,
// ½
0x0133: 0xbf,
// ¿
0x0134: 0x2122,
// ™
0x0135: 0xa2,
// ¢
0x0136: 0xa3,
// £
0x0137: 0x266a,
// ♪
0x0138: 0xe0,
// à
0x0139: 0xa0,
//
0x013a: 0xe8,
// è
0x013b: 0xe2,
// â
0x013c: 0xea,
// ê
0x013d: 0xee,
// î
0x013e: 0xf4,
// ô
0x013f: 0xfb,
// û
0x0220: 0xc1,
// á
0x0221: 0xc9,
// é
0x0222: 0xd3,
// ó
0x0223: 0xda,
// ú
0x0224: 0xdc,
// ü
0x0225: 0xfc,
// ü
0x0226: 0x2018,
// ‘
0x0227: 0xa1,
// ¡
0x0228: 0x2a,
// *
0x0229: 0x27,
// '
0x022a: 0x2014,
// —
0x022b: 0xa9,
// ©
0x022c: 0x2120,
// ℠
0x022d: 0x2022,
// •
0x022e: 0x201c,
// “
0x022f: 0x201d,
// ”
0x0230: 0xc0,
// à
0x0231: 0xc2,
// â
0x0232: 0xc7,
// ç
0x0233: 0xc8,
// è
0x0234: 0xca,
// ê
0x0235: 0xcb,
// ë
0x0236: 0xeb,
// ë
0x0237: 0xce,
// î
0x0238: 0xcf,
// ï
0x0239: 0xef,
// ï
0x023a: 0xd4,
// ô
0x023b: 0xd9,
// ù
0x023c: 0xf9,
// ù
0x023d: 0xdb,
// û
0x023e: 0xab,
// «
0x023f: 0xbb,
// »
0x0320: 0xc3,
// ã
0x0321: 0xe3,
// ã
0x0322: 0xcd,
// í
0x0323: 0xcc,
// ì
0x0324: 0xec,
// ì
0x0325: 0xd2,
// ò
0x0326: 0xf2,
// ò
0x0327: 0xd5,
// õ
0x0328: 0xf5,
// õ
0x0329: 0x7b,
// {
0x032a: 0x7d,
// }
0x032b: 0x5c,
// \
0x032c: 0x5e,
// ^
0x032d: 0x5f,
// _
0x032e: 0x7c,
// |
0x032f: 0x7e,
// ~
0x0330: 0xc4,
// ä
0x0331: 0xe4,
// ä
0x0332: 0xd6,
// ö
0x0333: 0xf6,
// ö
0x0334: 0xdf,
// ß
0x0335: 0xa5,
// ¥
0x0336: 0xa4,
// ¤
0x0337: 0x2502,
// │
0x0338: 0xc5,
// å
0x0339: 0xe5,
// å
0x033a: 0xd8,
// ø
0x033b: 0xf8,
// ø
0x033c: 0x250c,
// ┌
0x033d: 0x2510,
// ┐
0x033e: 0x2514,
// └
0x033f: 0x2518 // ┘
};
var getcharfromcode = function getcharfromcode(code) {
if (code === null) {
return '';
}
code = character_translation[code] || code;
return string.fromcharcode(code);
}; // the index of the last row in a cea-608 display buffer
var bottom_row = 14; // this array is used for mapping pacs -> row #, since there's no way of
// getting it through bit logic.
var rows = [0x1100, 0x1120, 0x1200, 0x1220, 0x1500, 0x1520, 0x1600, 0x1620, 0x1700, 0x1720, 0x1000, 0x1300, 0x1320, 0x1400, 0x1420]; // cea-608 captions are rendered onto a 34x15 matrix of character
// cells. the "bottom" row is the last element in the outer array.
var createdisplaybuffer = function createdisplaybuffer() {
var result = [],
i = bottom_row + 1;
while (i--) {
result.push('');
}
return result;
};
var cea608stream = function cea608stream(field, datachannel) {
cea608stream.prototype.init.call(this);
this.field_ = field || 0;
this.datachannel_ = datachannel || 0;
this.name_ = 'cc' + ((this.field_ << 1 | this.datachannel_) + 1);
this.setconstants();
this.reset();
this.push = function (packet) {
var data, swap, char0, char1, text; // remove the parity bits
data = packet.ccdata & 0x7f7f; // ignore duplicate control codes; the spec demands they're sent twice
if (data === this.lastcontrolcode_) {
this.lastcontrolcode_ = null;
return;
} // store control codes
if ((data & 0xf000) === 0x1000) {
this.lastcontrolcode_ = data;
} else if (data !== this.padding_) {
this.lastcontrolcode_ = null;
}
char0 = data >>> 8;
char1 = data & 0xff;
if (data === this.padding_) {
return;
} else if (data === this.resume_caption_loading_) {
this.mode_ = 'popon';
} else if (data === this.end_of_caption_) {
// if an eoc is received while in paint-on mode, the displayed caption
// text should be swapped to non-displayed memory as if it was a pop-on
// caption. because of that, we should explicitly switch back to pop-on
// mode
this.mode_ = 'popon';
this.clearformatting(packet.pts); // if a caption was being displayed, it's gone now
this.flushdisplayed(packet.pts); // flip memory
swap = this.displayed_;
this.displayed_ = this.nondisplayed_;
this.nondisplayed_ = swap; // start measuring the time to display the caption
this.startpts_ = packet.pts;
} else if (data === this.roll_up_2_rows_) {
this.rolluprows_ = 2;
this.setrollup(packet.pts);
} else if (data === this.roll_up_3_rows_) {
this.rolluprows_ = 3;
this.setrollup(packet.pts);
} else if (data === this.roll_up_4_rows_) {
this.rolluprows_ = 4;
this.setrollup(packet.pts);
} else if (data === this.carriage_return_) {
this.clearformatting(packet.pts);
this.flushdisplayed(packet.pts);
this.shiftrowsup_();
this.startpts_ = packet.pts;
} else if (data === this.backspace_) {
if (this.mode_ === 'popon') {
this.nondisplayed_[this.row_] = this.nondisplayed_[this.row_].slice(0, -1);
} else {
this.displayed_[this.row_] = this.displayed_[this.row_].slice(0, -1);
}
} else if (data === this.erase_displayed_memory_) {
this.flushdisplayed(packet.pts);
this.displayed_ = createdisplaybuffer();
} else if (data === this.erase_non_displayed_memory_) {
this.nondisplayed_ = createdisplaybuffer();
} else if (data === this.resume_direct_captioning_) {
if (this.mode_ !== 'painton') {
// note: this should be removed when proper caption positioning is
// implemented
this.flushdisplayed(packet.pts);
this.displayed_ = createdisplaybuffer();
}
this.mode_ = 'painton';
this.startpts_ = packet.pts; // append special characters to caption text
} else if (this.isspecialcharacter(char0, char1)) {
// bitmask char0 so that we can apply character transformations
// regardless of field and data channel.
// then byte-shift to the left and or with char1 so we can pass the
// entire character code to `getcharfromcode`.
char0 = (char0 & 0x03) << 8;
text = getcharfromcode(char0 | char1);
this[this.mode_](packet.pts, text);
this.column_++; // append extended characters to caption text
} else if (this.isextcharacter(char0, char1)) {
// extended characters always follow their "non-extended" equivalents.
// ie if a "è" is desired, you'll always receive "eè"; non-compliant
// decoders are supposed to drop the "è", while compliant decoders
// backspace the "e" and insert "è".
// delete the previous character
if (this.mode_ === 'popon') {
this.nondisplayed_[this.row_] = this.nondisplayed_[this.row_].slice(0, -1);
} else {
this.displayed_[this.row_] = this.displayed_[this.row_].slice(0, -1);
} // bitmask char0 so that we can apply character transformations
// regardless of field and data channel.
// then byte-shift to the left and or with char1 so we can pass the
// entire character code to `getcharfromcode`.
char0 = (char0 & 0x03) << 8;
text = getcharfromcode(char0 | char1);
this[this.mode_](packet.pts, text);
this.column_++; // process mid-row codes
} else if (this.ismidrowcode(char0, char1)) {
// attributes are not additive, so clear all formatting
this.clearformatting(packet.pts); // according to the standard, mid-row codes
// should be replaced with spaces, so add one now
this[this.mode_](packet.pts, ' ');
this.column_++;
if ((char1 & 0xe) === 0xe) {
this.addformatting(packet.pts, ['i']);
}
if ((char1 & 0x1) === 0x1) {
this.addformatting(packet.pts, ['u']);
} // detect offset control codes and adjust cursor
} else if (this.isoffsetcontrolcode(char0, char1)) {
// cursor position is set by indent pac (see below) in 4-column
// increments, with an additional offset code of 1-3 to reach any
// of the 32 columns specified by cea-608. so all we need to do
// here is increment the column cursor by the given offset.
this.column_ += char1 & 0x03; // detect pacs (preamble address codes)
} else if (this.ispac(char0, char1)) {
// there's no logic for pac -> row mapping, so we have to just
// find the row code in an array and use its index :(
var row = rows.indexof(data & 0x1f20); // configure the caption window if we're in roll-up mode
if (this.mode_ === 'rollup') {
// this implies that the base row is incorrectly set.
// as per the recommendation in cea-608(base row implementation), defer to the number
// of roll-up rows set.
if (row - this.rolluprows_ + 1 < 0) {
row = this.rolluprows_ - 1;
}
this.setrollup(packet.pts, row);
}
if (row !== this.row_) {
// formatting is only persistent for current row
this.clearformatting(packet.pts);
this.row_ = row;
} // all pacs can apply underline, so detect and apply
// (all odd-numbered second bytes set underline)
if (char1 & 0x1 && this.formatting_.indexof('u') === -1) {
this.addformatting(packet.pts, ['u']);
}
if ((data & 0x10) === 0x10) {
// we've got an indent level code. each successive even number
// increments the column cursor by 4, so we can get the desired
// column position by bit-shifting to the right (to get n/2)
// and multiplying by 4.
this.column_ = ((data & 0xe) >> 1) * 4;
}
if (this.iscolorpac(char1)) {
// it's a color code, though we only support white, which
// can be either normal or italicized. white italics can be
// either 0x4e or 0x6e depending on the row, so we just
// bitwise-and with 0xe to see if italics should be turned on
if ((char1 & 0xe) === 0xe) {
this.addformatting(packet.pts, ['i']);
}
} // we have a normal character in char0, and possibly one in char1
} else if (this.isnormalchar(char0)) {
if (char1 === 0x00) {
char1 = null;
}
text = getcharfromcode(char0);
text += getcharfromcode(char1);
this[this.mode_](packet.pts, text);
this.column_ += text.length;
} // finish data processing
};
};
cea608stream.prototype = new stream(); // trigger a cue point that captures the current state of the
// display buffer
cea608stream.prototype.flushdisplayed = function (pts) {
var content = this.displayed_ // remove spaces from the start and end of the string
.map(function (row, index) {
try {
return row.trim();
} catch (e) {
// ordinarily, this shouldn't happen. however, caption
// parsing errors should not throw exceptions and
// break playback.
this.trigger('log', {
level: 'warn',
message: 'skipping a malformed 608 caption at index ' + index + '.'
});
return '';
}
}, this) // combine all text rows to display in one cue
.join('\n') // and remove blank rows from the start and end, but not the middle
.replace(/^\n+|\n+$/g, '');
if (content.length) {
this.trigger('data', {
startpts: this.startpts_,
endpts: pts,
text: content,
stream: this.name_
});
}
};
/**
* zero out the data, used for startup and on seek
*/
cea608stream.prototype.reset = function () {
this.mode_ = 'popon'; // when in roll-up mode, the index of the last row that will
// actually display captions. if a caption is shifted to a row
// with a lower index than this, it is cleared from the display
// buffer
this.toprow_ = 0;
this.startpts_ = 0;
this.displayed_ = createdisplaybuffer();
this.nondisplayed_ = createdisplaybuffer();
this.lastcontrolcode_ = null; // track row and column for proper line-breaking and spacing
this.column_ = 0;
this.row_ = bottom_row;
this.rolluprows_ = 2; // this variable holds currently-applied formatting
this.formatting_ = [];
};
/**
* sets up control code and related constants for this instance
*/
cea608stream.prototype.setconstants = function () {
// the following attributes have these uses:
// ext_ : char0 for mid-row codes, and the base for extended
// chars (ext_+0, ext_+1, and ext_+2 are char0s for
// extended codes)
// control_: char0 for control codes, except byte-shifted to the
// left so that we can do this.control_ | control_code
// offset_: char0 for tab offset codes
//
// it's also worth noting that control codes, and _only_ control codes,
// differ between field 1 and field2. field 2 control codes are always
// their field 1 value plus 1. that's why there's the "| field" on the
// control value.
if (this.datachannel_ === 0) {
this.base_ = 0x10;
this.ext_ = 0x11;
this.control_ = (0x14 | this.field_) << 8;
this.offset_ = 0x17;
} else if (this.datachannel_ === 1) {
this.base_ = 0x18;
this.ext_ = 0x19;
this.control_ = (0x1c | this.field_) << 8;
this.offset_ = 0x1f;
} // constants for the lsbyte command codes recognized by cea608stream. this
// list is not exhaustive. for a more comprehensive listing and semantics see
// http://www.gpo.gov/fdsys/pkg/cfr-2010-title47-vol1/pdf/cfr-2010-title47-vol1-sec15-119.pdf
// padding
this.padding_ = 0x0000; // pop-on mode
this.resume_caption_loading_ = this.control_ | 0x20;
this.end_of_caption_ = this.control_ | 0x2f; // roll-up mode
this.roll_up_2_rows_ = this.control_ | 0x25;
this.roll_up_3_rows_ = this.control_ | 0x26;
this.roll_up_4_rows_ = this.control_ | 0x27;
this.carriage_return_ = this.control_ | 0x2d; // paint-on mode
this.resume_direct_captioning_ = this.control_ | 0x29; // erasure
this.backspace_ = this.control_ | 0x21;
this.erase_displayed_memory_ = this.control_ | 0x2c;
this.erase_non_displayed_memory_ = this.control_ | 0x2e;
};
/**
* detects if the 2-byte packet data is a special character
*
* special characters have a second byte in the range 0x30 to 0x3f,
* with the first byte being 0x11 (for data channel 1) or 0x19 (for
* data channel 2).
*
* @param {integer} char0 the first byte
* @param {integer} char1 the second byte
* @return {boolean} whether the 2 bytes are an special character
*/
cea608stream.prototype.isspecialcharacter = function (char0, char1) {
return char0 === this.ext_ && char1 >= 0x30 && char1 <= 0x3f;
};
/**
* detects if the 2-byte packet data is an extended character
*
* extended characters have a second byte in the range 0x20 to 0x3f,
* with the first byte being 0x12 or 0x13 (for data channel 1) or
* 0x1a or 0x1b (for data channel 2).
*
* @param {integer} char0 the first byte
* @param {integer} char1 the second byte
* @return {boolean} whether the 2 bytes are an extended character
*/
cea608stream.prototype.isextcharacter = function (char0, char1) {
return (char0 === this.ext_ + 1 || char0 === this.ext_ + 2) && char1 >= 0x20 && char1 <= 0x3f;
};
/**
* detects if the 2-byte packet is a mid-row code
*
* mid-row codes have a second byte in the range 0x20 to 0x2f, with
* the first byte being 0x11 (for data channel 1) or 0x19 (for data
* channel 2).
*
* @param {integer} char0 the first byte
* @param {integer} char1 the second byte
* @return {boolean} whether the 2 bytes are a mid-row code
*/
cea608stream.prototype.ismidrowcode = function (char0, char1) {
return char0 === this.ext_ && char1 >= 0x20 && char1 <= 0x2f;
};
/**
* detects if the 2-byte packet is an offset control code
*
* offset control codes have a second byte in the range 0x21 to 0x23,
* with the first byte being 0x17 (for data channel 1) or 0x1f (for
* data channel 2).
*
* @param {integer} char0 the first byte
* @param {integer} char1 the second byte
* @return {boolean} whether the 2 bytes are an offset control code
*/
cea608stream.prototype.isoffsetcontrolcode = function (char0, char1) {
return char0 === this.offset_ && char1 >= 0x21 && char1 <= 0x23;
};
/**
* detects if the 2-byte packet is a preamble address code
*
* pacs have a first byte in the range 0x10 to 0x17 (for data channel 1)
* or 0x18 to 0x1f (for data channel 2), with the second byte in the
* range 0x40 to 0x7f.
*
* @param {integer} char0 the first byte
* @param {integer} char1 the second byte
* @return {boolean} whether the 2 bytes are a pac
*/
cea608stream.prototype.ispac = function (char0, char1) {
return char0 >= this.base_ && char0 < this.base_ + 8 && char1 >= 0x40 && char1 <= 0x7f;
};
/**
* detects if a packet's second byte is in the range of a pac color code
*
* pac color codes have the second byte be in the range 0x40 to 0x4f, or
* 0x60 to 0x6f.
*
* @param {integer} char1 the second byte
* @return {boolean} whether the byte is a color pac
*/
cea608stream.prototype.iscolorpac = function (char1) {
return char1 >= 0x40 && char1 <= 0x4f || char1 >= 0x60 && char1 <= 0x7f;
};
/**
* detects if a single byte is in the range of a normal character
*
* normal text bytes are in the range 0x20 to 0x7f.
*
* @param {integer} char the byte
* @return {boolean} whether the byte is a normal character
*/
cea608stream.prototype.isnormalchar = function (_char2) {
return _char2 >= 0x20 && _char2 <= 0x7f;
};
/**
* configures roll-up
*
* @param {integer} pts current pts
* @param {integer} newbaserow used by pacs to slide the current window to
* a new position
*/
cea608stream.prototype.setrollup = function (pts, newbaserow) {
// reset the base row to the bottom row when switching modes
if (this.mode_ !== 'rollup') {
this.row_ = bottom_row;
this.mode_ = 'rollup'; // spec says to wipe memories when switching to roll-up
this.flushdisplayed(pts);
this.nondisplayed_ = createdisplaybuffer();
this.displayed_ = createdisplaybuffer();
}
if (newbaserow !== undefined && newbaserow !== this.row_) {
// move currently displayed captions (up or down) to the new base row
for (var i = 0; i < this.rolluprows_; i++) {
this.displayed_[newbaserow - i] = this.displayed_[this.row_ - i];
this.displayed_[this.row_ - i] = '';
}
}
if (newbaserow === undefined) {
newbaserow = this.row_;
}
this.toprow_ = newbaserow - this.rolluprows_ + 1;
}; // adds the opening html tag for the passed character to the caption text,
// and keeps track of it for later closing
cea608stream.prototype.addformatting = function (pts, format) {
this.formatting_ = this.formatting_.concat(format);
var text = format.reduce(function (text, format) {
return text + '<' + format + '>';
}, '');
this[this.mode_](pts, text);
}; // adds html closing tags for current formatting to caption text and
// clears remembered formatting
cea608stream.prototype.clearformatting = function (pts) {
if (!this.formatting_.length) {
return;
}
var text = this.formatting_.reverse().reduce(function (text, format) {
return text + '' + format + '>';
}, '');
this.formatting_ = [];
this[this.mode_](pts, text);
}; // mode implementations
cea608stream.prototype.popon = function (pts, text) {
var baserow = this.nondisplayed_[this.row_]; // buffer characters
baserow += text;
this.nondisplayed_[this.row_] = baserow;
};
cea608stream.prototype.rollup = function (pts, text) {
var baserow = this.displayed_[this.row_];
baserow += text;
this.displayed_[this.row_] = baserow;
};
cea608stream.prototype.shiftrowsup_ = function () {
var i; // clear out inactive rows
for (i = 0; i < this.toprow_; i++) {
this.displayed_[i] = '';
}
for (i = this.row_ + 1; i < bottom_row + 1; i++) {
this.displayed_[i] = '';
} // shift displayed rows up
for (i = this.toprow_; i < this.row_; i++) {
this.displayed_[i] = this.displayed_[i + 1];
} // clear out the bottom row
this.displayed_[this.row_] = '';
};
cea608stream.prototype.painton = function (pts, text) {
var baserow = this.displayed_[this.row_];
baserow += text;
this.displayed_[this.row_] = baserow;
}; // exports
var captionstream = {
captionstream: captionstream$1,
cea608stream: cea608stream,
cea708stream: cea708stream
};
/**
* mux.js
*
* copyright (c) brightcove
* licensed apache-2.0 https://github.com/videojs/mux.js/blob/master/license
*/
var streamtypes = {
h264_stream_type: 0x1b,
adts_stream_type: 0x0f,
metadata_stream_type: 0x15
};
var max_ts = 8589934592;
var ro_thresh = 4294967296;
var type_shared = 'shared';
var handlerollover$1 = function handlerollover(value, reference) {
var direction = 1;
if (value > reference) {
// if the current timestamp value is greater than our reference timestamp and we detect a
// timestamp rollover, this means the roll over is happening in the opposite direction.
// example scenario: enter a long stream/video just after a rollover occurred. the reference
// point will be set to a small number, e.g. 1. the user then seeks backwards over the
// rollover point. in loading this segment, the timestamp values will be very large,
// e.g. 2^33 - 1. since this comes before the data we loaded previously, we want to adjust
// the time stamp to be `value - 2^33`.
direction = -1;
} // note: a seek forwards or back that is greater than the ro_thresh (2^32, ~13 hours) will
// cause an incorrect adjustment.
while (math.abs(reference - value) > ro_thresh) {
value += direction * max_ts;
}
return value;
};
var timestamprolloverstream$1 = function timestamprolloverstream(type) {
var lastdts, referencedts;
timestamprolloverstream.prototype.init.call(this); // the "shared" type is used in cases where a stream will contain muxed
// video and audio. we could use `undefined` here, but having a string
// makes debugging a little clearer.
this.type_ = type || type_shared;
this.push = function (data) {
// any "shared" rollover streams will accept _all_ data. otherwise,
// streams will only accept data that matches their type.
if (this.type_ !== type_shared && data.type !== this.type_) {
return;
}
if (referencedts === undefined) {
referencedts = data.dts;
}
data.dts = handlerollover$1(data.dts, referencedts);
data.pts = handlerollover$1(data.pts, referencedts);
lastdts = data.dts;
this.trigger('data', data);
};
this.flush = function () {
referencedts = lastdts;
this.trigger('done');
};
this.endtimeline = function () {
this.flush();
this.trigger('endedtimeline');
};
this.discontinuity = function () {
referencedts = void 0;
lastdts = void 0;
};
this.reset = function () {
this.discontinuity();
this.trigger('reset');
};
};
timestamprolloverstream$1.prototype = new stream();
var timestamprolloverstream = {
timestamprolloverstream: timestamprolloverstream$1,
handlerollover: handlerollover$1
};
var percentencode$1 = function percentencode(bytes, start, end) {
var i,
result = '';
for (i = start; i < end; i++) {
result += '%' + ('00' + bytes[i].tostring(16)).slice(-2);
}
return result;
},
// return the string representation of the specified byte range,
// interpreted as utf-8.
parseutf8 = function parseutf8(bytes, start, end) {
return decodeuricomponent(percentencode$1(bytes, start, end));
},
// return the string representation of the specified byte range,
// interpreted as iso-8859-1.
parseiso88591$1 = function parseiso88591(bytes, start, end) {
return unescape(percentencode$1(bytes, start, end)); // jshint ignore:line
},
parsesyncsafeinteger$1 = function parsesyncsafeinteger(data) {
return data[0] << 21 | data[1] << 14 | data[2] << 7 | data[3];
},
tagparsers = {
txxx: function txxx(tag) {
var i;
if (tag.data[0] !== 3) {
// ignore frames with unrecognized character encodings
return;
}
for (i = 1; i < tag.data.length; i++) {
if (tag.data[i] === 0) {
// parse the text fields
tag.description = parseutf8(tag.data, 1, i); // do not include the null terminator in the tag value
tag.value = parseutf8(tag.data, i + 1, tag.data.length).replace(/\0*$/, '');
break;
}
}
tag.data = tag.value;
},
wxxx: function wxxx(tag) {
var i;
if (tag.data[0] !== 3) {
// ignore frames with unrecognized character encodings
return;
}
for (i = 1; i < tag.data.length; i++) {
if (tag.data[i] === 0) {
// parse the description and url fields
tag.description = parseutf8(tag.data, 1, i);
tag.url = parseutf8(tag.data, i + 1, tag.data.length);
break;
}
}
},
priv: function priv(tag) {
var i;
for (i = 0; i < tag.data.length; i++) {
if (tag.data[i] === 0) {
// parse the description and url fields
tag.owner = parseiso88591$1(tag.data, 0, i);
break;
}
}
tag.privatedata = tag.data.subarray(i + 1);
tag.data = tag.privatedata;
}
},
_metadatastream;
_metadatastream = function metadatastream(options) {
var settings = {
// the bytes of the program-level descriptor field in mp2t
// see iso/iec 13818-1:2013 (e), section 2.6 "program and
// program element descriptors"
descriptor: options && options.descriptor
},
// the total size in bytes of the id3 tag being parsed
tagsize = 0,
// tag data that is not complete enough to be parsed
buffer = [],
// the total number of bytes currently in the buffer
buffersize = 0,
i;
_metadatastream.prototype.init.call(this); // calculate the text track in-band metadata track dispatch type
// https://html.spec.whatwg.org/multipage/embedded-content.html#steps-to-expose-a-media-resource-specific-text-track
this.dispatchtype = streamtypes.metadata_stream_type.tostring(16);
if (settings.descriptor) {
for (i = 0; i < settings.descriptor.length; i++) {
this.dispatchtype += ('00' + settings.descriptor[i].tostring(16)).slice(-2);
}
}
this.push = function (chunk) {
var tag, framestart, framesize, frame, i, frameheader;
if (chunk.type !== 'timed-metadata') {
return;
} // if data_alignment_indicator is set in the pes header,
// we must have the start of a new id3 tag. assume anything
// remaining in the buffer was malformed and throw it out
if (chunk.dataalignmentindicator) {
buffersize = 0;
buffer.length = 0;
} // ignore events that don't look like id3 data
if (buffer.length === 0 && (chunk.data.length < 10 || chunk.data[0] !== 'i'.charcodeat(0) || chunk.data[1] !== 'd'.charcodeat(0) || chunk.data[2] !== '3'.charcodeat(0))) {
this.trigger('log', {
level: 'warn',
message: 'skipping unrecognized metadata packet'
});
return;
} // add this chunk to the data we've collected so far
buffer.push(chunk);
buffersize += chunk.data.bytelength; // grab the size of the entire frame from the id3 header
if (buffer.length === 1) {
// the frame size is transmitted as a 28-bit integer in the
// last four bytes of the id3 header.
// the most significant bit of each byte is dropped and the
// results concatenated to recover the actual value.
tagsize = parsesyncsafeinteger$1(chunk.data.subarray(6, 10)); // id3 reports the tag size excluding the header but it's more
// convenient for our comparisons to include it
tagsize += 10;
} // if the entire frame has not arrived, wait for more data
if (buffersize < tagsize) {
return;
} // collect the entire frame so it can be parsed
tag = {
data: new uint8array(tagsize),
frames: [],
pts: buffer[0].pts,
dts: buffer[0].dts
};
for (i = 0; i < tagsize;) {
tag.data.set(buffer[0].data.subarray(0, tagsize - i), i);
i += buffer[0].data.bytelength;
buffersize -= buffer[0].data.bytelength;
buffer.shift();
} // find the start of the first frame and the end of the tag
framestart = 10;
if (tag.data[5] & 0x40) {
// advance the frame start past the extended header
framestart += 4; // header size field
framestart += parsesyncsafeinteger$1(tag.data.subarray(10, 14)); // clip any padding off the end
tagsize -= parsesyncsafeinteger$1(tag.data.subarray(16, 20));
} // parse one or more id3 frames
// http://id3.org/id3v2.3.0#id3v2_frame_overview
do {
// determine the number of bytes in this frame
framesize = parsesyncsafeinteger$1(tag.data.subarray(framestart + 4, framestart + 8));
if (framesize < 1) {
this.trigger('log', {
level: 'warn',
message: 'malformed id3 frame encountered. skipping metadata parsing.'
});
return;
}
frameheader = string.fromcharcode(tag.data[framestart], tag.data[framestart + 1], tag.data[framestart + 2], tag.data[framestart + 3]);
frame = {
id: frameheader,
data: tag.data.subarray(framestart + 10, framestart + framesize + 10)
};
frame.key = frame.id;
if (tagparsers[frame.id]) {
tagparsers[frame.id](frame); // handle the special priv frame used to indicate the start
// time for raw aac data
if (frame.owner === 'com.apple.streaming.transportstreamtimestamp') {
var d = frame.data,
size = (d[3] & 0x01) << 30 | d[4] << 22 | d[5] << 14 | d[6] << 6 | d[7] >>> 2;
size *= 4;
size += d[7] & 0x03;
frame.timestamp = size; // in raw aac, all subsequent data will be timestamped based
// on the value of this frame
// we couldn't have known the appropriate pts and dts before
// parsing this id3 tag so set those values now
if (tag.pts === undefined && tag.dts === undefined) {
tag.pts = frame.timestamp;
tag.dts = frame.timestamp;
}
this.trigger('timestamp', frame);
}
}
tag.frames.push(frame);
framestart += 10; // advance past the frame header
framestart += framesize; // advance past the frame body
} while (framestart < tagsize);
this.trigger('data', tag);
};
};
_metadatastream.prototype = new stream();
var metadatastream = _metadatastream;
var timestamprolloverstream = timestamprolloverstream.timestamprolloverstream; // object types
var _transportpacketstream, _transportparsestream, _elementarystream; // constants
var mp2t_packet_length$1 = 188,
// bytes
sync_byte$1 = 0x47;
/**
* splits an incoming stream of binary data into mpeg-2 transport
* stream packets.
*/
_transportpacketstream = function transportpacketstream() {
var buffer = new uint8array(mp2t_packet_length$1),
bytesinbuffer = 0;
_transportpacketstream.prototype.init.call(this); // deliver new bytes to the stream.
/**
* split a stream of data into m2ts packets
**/
this.push = function (bytes) {
var startindex = 0,
endindex = mp2t_packet_length$1,
everything; // if there are bytes remaining from the last segment, prepend them to the
// bytes that were pushed in
if (bytesinbuffer) {
everything = new uint8array(bytes.bytelength + bytesinbuffer);
everything.set(buffer.subarray(0, bytesinbuffer));
everything.set(bytes, bytesinbuffer);
bytesinbuffer = 0;
} else {
everything = bytes;
} // while we have enough data for a packet
while (endindex < everything.bytelength) {
// look for a pair of start and end sync bytes in the data..
if (everything[startindex] === sync_byte$1 && everything[endindex] === sync_byte$1) {
// we found a packet so emit it and jump one whole packet forward in
// the stream
this.trigger('data', everything.subarray(startindex, endindex));
startindex += mp2t_packet_length$1;
endindex += mp2t_packet_length$1;
continue;
} // if we get here, we have somehow become de-synchronized and we need to step
// forward one byte at a time until we find a pair of sync bytes that denote
// a packet
startindex++;
endindex++;
} // if there was some data left over at the end of the segment that couldn't
// possibly be a whole packet, keep it because it might be the start of a packet
// that continues in the next segment
if (startindex < everything.bytelength) {
buffer.set(everything.subarray(startindex), 0);
bytesinbuffer = everything.bytelength - startindex;
}
};
/**
* passes identified m2ts packets to the transportparsestream to be parsed
**/
this.flush = function () {
// if the buffer contains a whole packet when we are being flushed, emit it
// and empty the buffer. otherwise hold onto the data because it may be
// important for decoding the next segment
if (bytesinbuffer === mp2t_packet_length$1 && buffer[0] === sync_byte$1) {
this.trigger('data', buffer);
bytesinbuffer = 0;
}
this.trigger('done');
};
this.endtimeline = function () {
this.flush();
this.trigger('endedtimeline');
};
this.reset = function () {
bytesinbuffer = 0;
this.trigger('reset');
};
};
_transportpacketstream.prototype = new stream();
/**
* accepts an mp2t transportpacketstream and emits data events with parsed
* forms of the individual transport stream packets.
*/
_transportparsestream = function transportparsestream() {
var parsepsi, parsepat, parsepmt, self;
_transportparsestream.prototype.init.call(this);
self = this;
this.packetswaitingforpmt = [];
this.programmaptable = undefined;
parsepsi = function parsepsi(payload, psi) {
var offset = 0; // psi packets may be split into multiple sections and those
// sections may be split into multiple packets. if a psi
// section starts in this packet, the payload_unit_start_indicator
// will be true and the first byte of the payload will indicate
// the offset from the current position to the start of the
// section.
if (psi.payloadunitstartindicator) {
offset += payload[offset] + 1;
}
if (psi.type === 'pat') {
parsepat(payload.subarray(offset), psi);
} else {
parsepmt(payload.subarray(offset), psi);
}
};
parsepat = function parsepat(payload, pat) {
pat.section_number = payload[7]; // eslint-disable-line camelcase
pat.last_section_number = payload[8]; // eslint-disable-line camelcase
// skip the psi header and parse the first pmt entry
self.pmtpid = (payload[10] & 0x1f) << 8 | payload[11];
pat.pmtpid = self.pmtpid;
};
/**
* parse out the relevant fields of a program map table (pmt).
* @param payload {uint8array} the pmt-specific portion of an mp2t
* packet. the first byte in this array should be the table_id
* field.
* @param pmt {object} the object that should be decorated with
* fields parsed from the pmt.
*/
parsepmt = function parsepmt(payload, pmt) {
var sectionlength, tableend, programinfolength, offset; // pmts can be sent ahead of the time when they should actually
// take effect. we don't believe this should ever be the case
// for hls but we'll ignore "forward" pmt declarations if we see
// them. future pmt declarations have the current_next_indicator
// set to zero.
if (!(payload[5] & 0x01)) {
return;
} // overwrite any existing program map table
self.programmaptable = {
video: null,
audio: null,
'timed-metadata': {}
}; // the mapping table ends at the end of the current section
sectionlength = (payload[1] & 0x0f) << 8 | payload[2];
tableend = 3 + sectionlength - 4; // to determine where the table is, we have to figure out how
// long the program info descriptors are
programinfolength = (payload[10] & 0x0f) << 8 | payload[11]; // advance the offset to the first entry in the mapping table
offset = 12 + programinfolength;
while (offset < tableend) {
var streamtype = payload[offset];
var pid = (payload[offset + 1] & 0x1f) << 8 | payload[offset + 2]; // only map a single elementary_pid for audio and video stream types
// todo: should this be done for metadata too? for now maintain behavior of
// multiple metadata streams
if (streamtype === streamtypes.h264_stream_type && self.programmaptable.video === null) {
self.programmaptable.video = pid;
} else if (streamtype === streamtypes.adts_stream_type && self.programmaptable.audio === null) {
self.programmaptable.audio = pid;
} else if (streamtype === streamtypes.metadata_stream_type) {
// map pid to stream type for metadata streams
self.programmaptable['timed-metadata'][pid] = streamtype;
} // move to the next table entry
// skip past the elementary stream descriptors, if present
offset += ((payload[offset + 3] & 0x0f) << 8 | payload[offset + 4]) + 5;
} // record the map on the packet as well
pmt.programmaptable = self.programmaptable;
};
/**
* deliver a new mp2t packet to the next stream in the pipeline.
*/
this.push = function (packet) {
var result = {},
offset = 4;
result.payloadunitstartindicator = !!(packet[1] & 0x40); // pid is a 13-bit field starting at the last bit of packet[1]
result.pid = packet[1] & 0x1f;
result.pid <<= 8;
result.pid |= packet[2]; // if an adaption field is present, its length is specified by the
// fifth byte of the ts packet header. the adaptation field is
// used to add stuffing to pes packets that don't fill a complete
// ts packet, and to specify some forms of timing and control data
// that we do not currently use.
if ((packet[3] & 0x30) >>> 4 > 0x01) {
offset += packet[offset] + 1;
} // parse the rest of the packet based on the type
if (result.pid === 0) {
result.type = 'pat';
parsepsi(packet.subarray(offset), result);
this.trigger('data', result);
} else if (result.pid === this.pmtpid) {
result.type = 'pmt';
parsepsi(packet.subarray(offset), result);
this.trigger('data', result); // if there are any packets waiting for a pmt to be found, process them now
while (this.packetswaitingforpmt.length) {
this.processpes_.apply(this, this.packetswaitingforpmt.shift());
}
} else if (this.programmaptable === undefined) {
// when we have not seen a pmt yet, defer further processing of
// pes packets until one has been parsed
this.packetswaitingforpmt.push([packet, offset, result]);
} else {
this.processpes_(packet, offset, result);
}
};
this.processpes_ = function (packet, offset, result) {
// set the appropriate stream type
if (result.pid === this.programmaptable.video) {
result.streamtype = streamtypes.h264_stream_type;
} else if (result.pid === this.programmaptable.audio) {
result.streamtype = streamtypes.adts_stream_type;
} else {
// if not video or audio, it is timed-metadata or unknown
// if unknown, streamtype will be undefined
result.streamtype = this.programmaptable['timed-metadata'][result.pid];
}
result.type = 'pes';
result.data = packet.subarray(offset);
this.trigger('data', result);
};
};
_transportparsestream.prototype = new stream();
_transportparsestream.stream_types = {
h264: 0x1b,
adts: 0x0f
};
/**
* reconsistutes program elementary stream (pes) packets from parsed
* transport stream packets. that is, if you pipe an
* mp2t.transportparsestream into a mp2t.elementarystream, the output
* events will be events which capture the bytes for individual pes
* packets plus relevant metadata that has been extracted from the
* container.
*/
_elementarystream = function elementarystream() {
var self = this,
segmenthadpmt = false,
// pes packet fragments
video = {
data: [],
size: 0
},
audio = {
data: [],
size: 0
},
timedmetadata = {
data: [],
size: 0
},
programmaptable,
parsepes = function parsepes(payload, pes) {
var ptsdtsflags;
var startprefix = payload[0] << 16 | payload[1] << 8 | payload[2]; // default to an empty array
pes.data = new uint8array(); // in certain live streams, the start of a ts fragment has ts packets
// that are frame data that is continuing from the previous fragment. this
// is to check that the pes data is the start of a new pes payload
if (startprefix !== 1) {
return;
} // get the packet length, this will be 0 for video
pes.packetlength = 6 + (payload[4] << 8 | payload[5]); // find out if this packets starts a new keyframe
pes.dataalignmentindicator = (payload[6] & 0x04) !== 0; // pes packets may be annotated with a pts value, or a pts value
// and a dts value. determine what combination of values is
// available to work with.
ptsdtsflags = payload[7]; // pts and dts are normally stored as a 33-bit number. javascript
// performs all bitwise operations on 32-bit integers but javascript
// supports a much greater range (52-bits) of integer using standard
// mathematical operations.
// we construct a 31-bit value using bitwise operators over the 31
// most significant bits and then multiply by 4 (equal to a left-shift
// of 2) before we add the final 2 least significant bits of the
// timestamp (equal to an or.)
if (ptsdtsflags & 0xc0) {
// the pts and dts are not written out directly. for information
// on how they are encoded, see
// http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
pes.pts = (payload[9] & 0x0e) << 27 | (payload[10] & 0xff) << 20 | (payload[11] & 0xfe) << 12 | (payload[12] & 0xff) << 5 | (payload[13] & 0xfe) >>> 3;
pes.pts *= 4; // left shift by 2
pes.pts += (payload[13] & 0x06) >>> 1; // or by the two lsbs
pes.dts = pes.pts;
if (ptsdtsflags & 0x40) {
pes.dts = (payload[14] & 0x0e) << 27 | (payload[15] & 0xff) << 20 | (payload[16] & 0xfe) << 12 | (payload[17] & 0xff) << 5 | (payload[18] & 0xfe) >>> 3;
pes.dts *= 4; // left shift by 2
pes.dts += (payload[18] & 0x06) >>> 1; // or by the two lsbs
}
} // the data section starts immediately after the pes header.
// pes_header_data_length specifies the number of header bytes
// that follow the last byte of the field.
pes.data = payload.subarray(9 + payload[8]);
},
/**
* pass completely parsed pes packets to the next stream in the pipeline
**/
flushstream = function flushstream(stream, type, forceflush) {
var packetdata = new uint8array(stream.size),
event = {
type: type
},
i = 0,
offset = 0,
packetflushable = false,
fragment; // do nothing if there is not enough buffered data for a complete
// pes header
if (!stream.data.length || stream.size < 9) {
return;
}
event.trackid = stream.data[0].pid; // reassemble the packet
for (i = 0; i < stream.data.length; i++) {
fragment = stream.data[i];
packetdata.set(fragment.data, offset);
offset += fragment.data.bytelength;
} // parse assembled packet's pes header
parsepes(packetdata, event); // non-video pes packets must have a non-zero pes_packet_length
// check that there is enough stream data to fill the packet
packetflushable = type === 'video' || event.packetlength <= stream.size; // flush pending packets if the conditions are right
if (forceflush || packetflushable) {
stream.size = 0;
stream.data.length = 0;
} // only emit packets that are complete. this is to avoid assembling
// incomplete pes packets due to poor segmentation
if (packetflushable) {
self.trigger('data', event);
}
};
_elementarystream.prototype.init.call(this);
/**
* identifies m2ts packet types and parses pes packets using metadata
* parsed from the pmt
**/
this.push = function (data) {
({
pat: function pat() {// we have to wait for the pmt to arrive as well before we
// have any meaningful metadata
},
pes: function pes() {
var stream, streamtype;
switch (data.streamtype) {
case streamtypes.h264_stream_type:
stream = video;
streamtype = 'video';
break;
case streamtypes.adts_stream_type:
stream = audio;
streamtype = 'audio';
break;
case streamtypes.metadata_stream_type:
stream = timedmetadata;
streamtype = 'timed-metadata';
break;
default:
// ignore unknown stream types
return;
} // if a new packet is starting, we can flush the completed
// packet
if (data.payloadunitstartindicator) {
flushstream(stream, streamtype, true);
} // buffer this fragment until we are sure we've received the
// complete payload
stream.data.push(data);
stream.size += data.data.bytelength;
},
pmt: function pmt() {
var event = {
type: 'metadata',
tracks: []
};
programmaptable = data.programmaptable; // translate audio and video streams to tracks
if (programmaptable.video !== null) {
event.tracks.push({
timelinestartinfo: {
basemediadecodetime: 0
},
id: +programmaptable.video,
codec: 'avc',
type: 'video'
});
}
if (programmaptable.audio !== null) {
event.tracks.push({
timelinestartinfo: {
basemediadecodetime: 0
},
id: +programmaptable.audio,
codec: 'adts',
type: 'audio'
});
}
segmenthadpmt = true;
self.trigger('data', event);
}
})[data.type]();
};
this.reset = function () {
video.size = 0;
video.data.length = 0;
audio.size = 0;
audio.data.length = 0;
this.trigger('reset');
};
/**
* flush any remaining input. video pes packets may be of variable
* length. normally, the start of a new video packet can trigger the
* finalization of the previous packet. that is not possible if no
* more video is forthcoming, however. in that case, some other
* mechanism (like the end of the file) has to be employed. when it is
* clear that no additional data is forthcoming, calling this method
* will flush the buffered packets.
*/
this.flushstreams_ = function () {
// !!this order is important!!
// video first then audio
flushstream(video, 'video');
flushstream(audio, 'audio');
flushstream(timedmetadata, 'timed-metadata');
};
this.flush = function () {
// if on flush we haven't had a pmt emitted
// and we have a pmt to emit. emit the pmt
// so that we trigger a trackinfo downstream.
if (!segmenthadpmt && programmaptable) {
var pmt = {
type: 'metadata',
tracks: []
}; // translate audio and video streams to tracks
if (programmaptable.video !== null) {
pmt.tracks.push({
timelinestartinfo: {
basemediadecodetime: 0
},
id: +programmaptable.video,
codec: 'avc',
type: 'video'
});
}
if (programmaptable.audio !== null) {
pmt.tracks.push({
timelinestartinfo: {
basemediadecodetime: 0
},
id: +programmaptable.audio,
codec: 'adts',
type: 'audio'
});
}
self.trigger('data', pmt);
}
segmenthadpmt = false;
this.flushstreams_();
this.trigger('done');
};
};
_elementarystream.prototype = new stream();
var m2ts = {
pat_pid: 0x0000,
mp2t_packet_length: mp2t_packet_length$1,
transportpacketstream: _transportpacketstream,
transportparsestream: _transportparsestream,
elementarystream: _elementarystream,
timestamprolloverstream: timestamprolloverstream,
captionstream: captionstream.captionstream,
cea608stream: captionstream.cea608stream,
cea708stream: captionstream.cea708stream,
metadatastream: metadatastream
};
for (var type in streamtypes) {
if (streamtypes.hasownproperty(type)) {
m2ts[type] = streamtypes[type];
}
}
var m2ts_1 = m2ts;
var one_second_in_ts$2 = clock.one_second_in_ts;
var _adtsstream;
var adts_sampling_frequencies$1 = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
/*
* accepts a elementarystream and emits data events with parsed
* aac audio frames of the individual packets. input audio in adts
* format is unpacked and re-emitted as aac frames.
*
* @see http://wiki.multimedia.cx/index.php?title=adts
* @see http://wiki.multimedia.cx/?title=understanding_aac
*/
_adtsstream = function adtsstream(handlepartialsegments) {
var buffer,
framenum = 0;
_adtsstream.prototype.init.call(this);
this.skipwarn_ = function (start, end) {
this.trigger('log', {
level: 'warn',
message: "adts skiping bytes " + start + " to " + end + " in frame " + framenum + " outside syncword"
});
};
this.push = function (packet) {
var i = 0,
framelength,
protectionskipbytes,
oldbuffer,
samplecount,
adtsframeduration;
if (!handlepartialsegments) {
framenum = 0;
}
if (packet.type !== 'audio') {
// ignore non-audio data
return;
} // prepend any data in the buffer to the input data so that we can parse
// aac frames the cross a pes packet boundary
if (buffer && buffer.length) {
oldbuffer = buffer;
buffer = new uint8array(oldbuffer.bytelength + packet.data.bytelength);
buffer.set(oldbuffer);
buffer.set(packet.data, oldbuffer.bytelength);
} else {
buffer = packet.data;
} // unpack any adts frames which have been fully received
// for details on the adts header, see http://wiki.multimedia.cx/index.php?title=adts
var skip; // we use i + 7 here because we want to be able to parse the entire header.
// if we don't have enough bytes to do that, then we definitely won't have a full frame.
while (i + 7 < buffer.length) {
// look for the start of an adts header..
if (buffer[i] !== 0xff || (buffer[i + 1] & 0xf6) !== 0xf0) {
if (typeof skip !== 'number') {
skip = i;
} // if a valid header was not found, jump one forward and attempt to
// find a valid adts header starting at the next byte
i++;
continue;
}
if (typeof skip === 'number') {
this.skipwarn_(skip, i);
skip = null;
} // the protection skip bit tells us if we have 2 bytes of crc data at the
// end of the adts header
protectionskipbytes = (~buffer[i + 1] & 0x01) * 2; // frame length is a 13 bit integer starting 16 bits from the
// end of the sync sequence
// note: frame length includes the size of the header
framelength = (buffer[i + 3] & 0x03) << 11 | buffer[i + 4] << 3 | (buffer[i + 5] & 0xe0) >> 5;
samplecount = ((buffer[i + 6] & 0x03) + 1) * 1024;
adtsframeduration = samplecount * one_second_in_ts$2 / adts_sampling_frequencies$1[(buffer[i + 2] & 0x3c) >>> 2]; // if we don't have enough data to actually finish this adts frame,
// then we have to wait for more data
if (buffer.bytelength - i < framelength) {
break;
} // otherwise, deliver the complete aac frame
this.trigger('data', {
pts: packet.pts + framenum * adtsframeduration,
dts: packet.dts + framenum * adtsframeduration,
samplecount: samplecount,
audioobjecttype: (buffer[i + 2] >>> 6 & 0x03) + 1,
channelcount: (buffer[i + 2] & 1) << 2 | (buffer[i + 3] & 0xc0) >>> 6,
samplerate: adts_sampling_frequencies$1[(buffer[i + 2] & 0x3c) >>> 2],
samplingfrequencyindex: (buffer[i + 2] & 0x3c) >>> 2,
// assume iso/iec 14496-12 audiosampleentry default of 16
samplesize: 16,
// data is the frame without it's header
data: buffer.subarray(i + 7 + protectionskipbytes, i + framelength)
});
framenum++;
i += framelength;
}
if (typeof skip === 'number') {
this.skipwarn_(skip, i);
skip = null;
} // remove processed bytes from the buffer.
buffer = buffer.subarray(i);
};
this.flush = function () {
framenum = 0;
this.trigger('done');
};
this.reset = function () {
buffer = void 0;
this.trigger('reset');
};
this.endtimeline = function () {
buffer = void 0;
this.trigger('endedtimeline');
};
};
_adtsstream.prototype = new stream();
var adts = _adtsstream;
/**
* mux.js
*
* copyright (c) brightcove
* licensed apache-2.0 https://github.com/videojs/mux.js/blob/master/license
*/
var expgolomb;
/**
* parser for exponential golomb codes, a variable-bitwidth number encoding
* scheme used by h264.
*/
expgolomb = function expgolomb(workingdata) {
var // the number of bytes left to examine in workingdata
workingbytesavailable = workingdata.bytelength,
// the current word being examined
workingword = 0,
// :uint
// the number of bits left to examine in the current word
workingbitsavailable = 0; // :uint;
// ():uint
this.length = function () {
return 8 * workingbytesavailable;
}; // ():uint
this.bitsavailable = function () {
return 8 * workingbytesavailable + workingbitsavailable;
}; // ():void
this.loadword = function () {
var position = workingdata.bytelength - workingbytesavailable,
workingbytes = new uint8array(4),
availablebytes = math.min(4, workingbytesavailable);
if (availablebytes === 0) {
throw new error('no bytes available');
}
workingbytes.set(workingdata.subarray(position, position + availablebytes));
workingword = new dataview(workingbytes.buffer).getuint32(0); // track the amount of workingdata that has been processed
workingbitsavailable = availablebytes * 8;
workingbytesavailable -= availablebytes;
}; // (count:int):void
this.skipbits = function (count) {
var skipbytes; // :int
if (workingbitsavailable > count) {
workingword <<= count;
workingbitsavailable -= count;
} else {
count -= workingbitsavailable;
skipbytes = math.floor(count / 8);
count -= skipbytes * 8;
workingbytesavailable -= skipbytes;
this.loadword();
workingword <<= count;
workingbitsavailable -= count;
}
}; // (size:int):uint
this.readbits = function (size) {
var bits = math.min(workingbitsavailable, size),
// :uint
valu = workingword >>> 32 - bits; // :uint
// if size > 31, handle error
workingbitsavailable -= bits;
if (workingbitsavailable > 0) {
workingword <<= bits;
} else if (workingbytesavailable > 0) {
this.loadword();
}
bits = size - bits;
if (bits > 0) {
return valu << bits | this.readbits(bits);
}
return valu;
}; // ():uint
this.skipleadingzeros = function () {
var leadingzerocount; // :uint
for (leadingzerocount = 0; leadingzerocount < workingbitsavailable; ++leadingzerocount) {
if ((workingword & 0x80000000 >>> leadingzerocount) !== 0) {
// the first bit of working word is 1
workingword <<= leadingzerocount;
workingbitsavailable -= leadingzerocount;
return leadingzerocount;
}
} // we exhausted workingword and still have not found a 1
this.loadword();
return leadingzerocount + this.skipleadingzeros();
}; // ():void
this.skipunsignedexpgolomb = function () {
this.skipbits(1 + this.skipleadingzeros());
}; // ():void
this.skipexpgolomb = function () {
this.skipbits(1 + this.skipleadingzeros());
}; // ():uint
this.readunsignedexpgolomb = function () {
var clz = this.skipleadingzeros(); // :uint
return this.readbits(clz + 1) - 1;
}; // ():int
this.readexpgolomb = function () {
var valu = this.readunsignedexpgolomb(); // :int
if (0x01 & valu) {
// the number is odd if the low order bit is set
return 1 + valu >>> 1; // add 1 to make it even, and divide by 2
}
return -1 * (valu >>> 1); // divide by two then make it negative
}; // some convenience functions
// :boolean
this.readboolean = function () {
return this.readbits(1) === 1;
}; // ():int
this.readunsignedbyte = function () {
return this.readbits(8);
};
this.loadword();
};
var expgolomb = expgolomb;
var _h264stream, _nalbytestream;
var profiles_with_optional_sps_data;
/**
* accepts a nal unit byte stream and unpacks the embedded nal units.
*/
_nalbytestream = function nalbytestream() {
var syncpoint = 0,
i,
buffer;
_nalbytestream.prototype.init.call(this);
/*
* scans a byte stream and triggers a data event with the nal units found.
* @param {object} data event received from h264stream
* @param {uint8array} data.data the h264 byte stream to be scanned
*
* @see h264stream.push
*/
this.push = function (data) {
var swapbuffer;
if (!buffer) {
buffer = data.data;
} else {
swapbuffer = new uint8array(buffer.bytelength + data.data.bytelength);
swapbuffer.set(buffer);
swapbuffer.set(data.data, buffer.bytelength);
buffer = swapbuffer;
}
var len = buffer.bytelength; // rec. itu-t h.264, annex b
// scan for nal unit boundaries
// a match looks like this:
// 0 0 1 .. nal .. 0 0 1
// ^ sync point ^ i
// or this:
// 0 0 1 .. nal .. 0 0 0
// ^ sync point ^ i
// advance the sync point to a nal start, if necessary
for (; syncpoint < len - 3; syncpoint++) {
if (buffer[syncpoint + 2] === 1) {
// the sync point is properly aligned
i = syncpoint + 5;
break;
}
}
while (i < len) {
// look at the current byte to determine if we've hit the end of
// a nal unit boundary
switch (buffer[i]) {
case 0:
// skip past non-sync sequences
if (buffer[i - 1] !== 0) {
i += 2;
break;
} else if (buffer[i - 2] !== 0) {
i++;
break;
} // deliver the nal unit if it isn't empty
if (syncpoint + 3 !== i - 2) {
this.trigger('data', buffer.subarray(syncpoint + 3, i - 2));
} // drop trailing zeroes
do {
i++;
} while (buffer[i] !== 1 && i < len);
syncpoint = i - 2;
i += 3;
break;
case 1:
// skip past non-sync sequences
if (buffer[i - 1] !== 0 || buffer[i - 2] !== 0) {
i += 3;
break;
} // deliver the nal unit
this.trigger('data', buffer.subarray(syncpoint + 3, i - 2));
syncpoint = i - 2;
i += 3;
break;
default:
// the current byte isn't a one or zero, so it cannot be part
// of a sync sequence
i += 3;
break;
}
} // filter out the nal units that were delivered
buffer = buffer.subarray(syncpoint);
i -= syncpoint;
syncpoint = 0;
};
this.reset = function () {
buffer = null;
syncpoint = 0;
this.trigger('reset');
};
this.flush = function () {
// deliver the last buffered nal unit
if (buffer && buffer.bytelength > 3) {
this.trigger('data', buffer.subarray(syncpoint + 3));
} // reset the stream state
buffer = null;
syncpoint = 0;
this.trigger('done');
};
this.endtimeline = function () {
this.flush();
this.trigger('endedtimeline');
};
};
_nalbytestream.prototype = new stream(); // values of profile_idc that indicate additional fields are included in the sps
// see recommendation itu-t h.264 (4/2013),
// 7.3.2.1.1 sequence parameter set data syntax
profiles_with_optional_sps_data = {
100: true,
110: true,
122: true,
244: true,
44: true,
83: true,
86: true,
118: true,
128: true,
// todo: the three profiles below don't
// appear to have sps data in the specificiation anymore?
138: true,
139: true,
134: true
};
/**
* accepts input from a elementarystream and produces h.264 nal unit data
* events.
*/
_h264stream = function h264stream() {
var nalbytestream = new _nalbytestream(),
self,
trackid,
currentpts,
currentdts,
discardemulationpreventionbytes,
readsequenceparameterset,
skipscalinglist;
_h264stream.prototype.init.call(this);
self = this;
/*
* pushes a packet from a stream onto the nalbytestream
*
* @param {object} packet - a packet received from a stream
* @param {uint8array} packet.data - the raw bytes of the packet
* @param {number} packet.dts - decode timestamp of the packet
* @param {number} packet.pts - presentation timestamp of the packet
* @param {number} packet.trackid - the id of the h264 track this packet came from
* @param {('video'|'audio')} packet.type - the type of packet
*
*/
this.push = function (packet) {
if (packet.type !== 'video') {
return;
}
trackid = packet.trackid;
currentpts = packet.pts;
currentdts = packet.dts;
nalbytestream.push(packet);
};
/*
* identify nal unit types and pass on the nalu, trackid, presentation and decode timestamps
* for the nalus to the next stream component.
* also, preprocess caption and sequence parameter nalus.
*
* @param {uint8array} data - a nal unit identified by `nalbytestream.push`
* @see nalbytestream.push
*/
nalbytestream.on('data', function (data) {
var event = {
trackid: trackid,
pts: currentpts,
dts: currentdts,
data: data,
nalunittypecode: data[0] & 0x1f
};
switch (event.nalunittypecode) {
case 0x05:
event.nalunittype = 'slice_layer_without_partitioning_rbsp_idr';
break;
case 0x06:
event.nalunittype = 'sei_rbsp';
event.escapedrbsp = discardemulationpreventionbytes(data.subarray(1));
break;
case 0x07:
event.nalunittype = 'seq_parameter_set_rbsp';
event.escapedrbsp = discardemulationpreventionbytes(data.subarray(1));
event.config = readsequenceparameterset(event.escapedrbsp);
break;
case 0x08:
event.nalunittype = 'pic_parameter_set_rbsp';
break;
case 0x09:
event.nalunittype = 'access_unit_delimiter_rbsp';
break;
} // this triggers data on the h264stream
self.trigger('data', event);
});
nalbytestream.on('done', function () {
self.trigger('done');
});
nalbytestream.on('partialdone', function () {
self.trigger('partialdone');
});
nalbytestream.on('reset', function () {
self.trigger('reset');
});
nalbytestream.on('endedtimeline', function () {
self.trigger('endedtimeline');
});
this.flush = function () {
nalbytestream.flush();
};
this.partialflush = function () {
nalbytestream.partialflush();
};
this.reset = function () {
nalbytestream.reset();
};
this.endtimeline = function () {
nalbytestream.endtimeline();
};
/**
* advance the expgolomb decoder past a scaling list. the scaling
* list is optionally transmitted as part of a sequence parameter
* set and is not relevant to transmuxing.
* @param count {number} the number of entries in this scaling list
* @param expgolombdecoder {object} an expgolomb pointed to the
* start of a scaling list
* @see recommendation itu-t h.264, section 7.3.2.1.1.1
*/
skipscalinglist = function skipscalinglist(count, expgolombdecoder) {
var lastscale = 8,
nextscale = 8,
j,
deltascale;
for (j = 0; j < count; j++) {
if (nextscale !== 0) {
deltascale = expgolombdecoder.readexpgolomb();
nextscale = (lastscale + deltascale + 256) % 256;
}
lastscale = nextscale === 0 ? lastscale : nextscale;
}
};
/**
* expunge any "emulation prevention" bytes from a "raw byte
* sequence payload"
* @param data {uint8array} the bytes of a rbsp from a nal
* unit
* @return {uint8array} the rbsp without any emulation
* prevention bytes
*/
discardemulationpreventionbytes = function discardemulationpreventionbytes(data) {
var length = data.bytelength,
emulationpreventionbytespositions = [],
i = 1,
newlength,
newdata; // find all `emulation prevention bytes`
while (i < length - 2) {
if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
emulationpreventionbytespositions.push(i + 2);
i += 2;
} else {
i++;
}
} // if no emulation prevention bytes were found just return the original
// array
if (emulationpreventionbytespositions.length === 0) {
return data;
} // create a new array to hold the nal unit data
newlength = length - emulationpreventionbytespositions.length;
newdata = new uint8array(newlength);
var sourceindex = 0;
for (i = 0; i < newlength; sourceindex++, i++) {
if (sourceindex === emulationpreventionbytespositions[0]) {
// skip this byte
sourceindex++; // remove this position index
emulationpreventionbytespositions.shift();
}
newdata[i] = data[sourceindex];
}
return newdata;
};
/**
* read a sequence parameter set and return some interesting video
* properties. a sequence parameter set is the h264 metadata that
* describes the properties of upcoming video frames.
* @param data {uint8array} the bytes of a sequence parameter set
* @return {object} an object with configuration parsed from the
* sequence parameter set, including the dimensions of the
* associated video frames.
*/
readsequenceparameterset = function readsequenceparameterset(data) {
var framecropleftoffset = 0,
framecroprightoffset = 0,
framecroptopoffset = 0,
framecropbottomoffset = 0,
expgolombdecoder,
profileidc,
levelidc,
profilecompatibility,
chromaformatidc,
picordercnttype,
numrefframesinpicordercntcycle,
picwidthinmbsminus1,
picheightinmapunitsminus1,
framembsonlyflag,
scalinglistcount,
sarratio = [1, 1],
aspectratioidc,
i;
expgolombdecoder = new expgolomb(data);
profileidc = expgolombdecoder.readunsignedbyte(); // profile_idc
profilecompatibility = expgolombdecoder.readunsignedbyte(); // constraint_set[0-5]_flag
levelidc = expgolombdecoder.readunsignedbyte(); // level_idc u(8)
expgolombdecoder.skipunsignedexpgolomb(); // seq_parameter_set_id
// some profiles have more optional data we don't need
if (profiles_with_optional_sps_data[profileidc]) {
chromaformatidc = expgolombdecoder.readunsignedexpgolomb();
if (chromaformatidc === 3) {
expgolombdecoder.skipbits(1); // separate_colour_plane_flag
}
expgolombdecoder.skipunsignedexpgolomb(); // bit_depth_luma_minus8
expgolombdecoder.skipunsignedexpgolomb(); // bit_depth_chroma_minus8
expgolombdecoder.skipbits(1); // qpprime_y_zero_transform_bypass_flag
if (expgolombdecoder.readboolean()) {
// seq_scaling_matrix_present_flag
scalinglistcount = chromaformatidc !== 3 ? 8 : 12;
for (i = 0; i < scalinglistcount; i++) {
if (expgolombdecoder.readboolean()) {
// seq_scaling_list_present_flag[ i ]
if (i < 6) {
skipscalinglist(16, expgolombdecoder);
} else {
skipscalinglist(64, expgolombdecoder);
}
}
}
}
}
expgolombdecoder.skipunsignedexpgolomb(); // log2_max_frame_num_minus4
picordercnttype = expgolombdecoder.readunsignedexpgolomb();
if (picordercnttype === 0) {
expgolombdecoder.readunsignedexpgolomb(); // log2_max_pic_order_cnt_lsb_minus4
} else if (picordercnttype === 1) {
expgolombdecoder.skipbits(1); // delta_pic_order_always_zero_flag
expgolombdecoder.skipexpgolomb(); // offset_for_non_ref_pic
expgolombdecoder.skipexpgolomb(); // offset_for_top_to_bottom_field
numrefframesinpicordercntcycle = expgolombdecoder.readunsignedexpgolomb();
for (i = 0; i < numrefframesinpicordercntcycle; i++) {
expgolombdecoder.skipexpgolomb(); // offset_for_ref_frame[ i ]
}
}
expgolombdecoder.skipunsignedexpgolomb(); // max_num_ref_frames
expgolombdecoder.skipbits(1); // gaps_in_frame_num_value_allowed_flag
picwidthinmbsminus1 = expgolombdecoder.readunsignedexpgolomb();
picheightinmapunitsminus1 = expgolombdecoder.readunsignedexpgolomb();
framembsonlyflag = expgolombdecoder.readbits(1);
if (framembsonlyflag === 0) {
expgolombdecoder.skipbits(1); // mb_adaptive_frame_field_flag
}
expgolombdecoder.skipbits(1); // direct_8x8_inference_flag
if (expgolombdecoder.readboolean()) {
// frame_cropping_flag
framecropleftoffset = expgolombdecoder.readunsignedexpgolomb();
framecroprightoffset = expgolombdecoder.readunsignedexpgolomb();
framecroptopoffset = expgolombdecoder.readunsignedexpgolomb();
framecropbottomoffset = expgolombdecoder.readunsignedexpgolomb();
}
if (expgolombdecoder.readboolean()) {
// vui_parameters_present_flag
if (expgolombdecoder.readboolean()) {
// aspect_ratio_info_present_flag
aspectratioidc = expgolombdecoder.readunsignedbyte();
switch (aspectratioidc) {
case 1:
sarratio = [1, 1];
break;
case 2:
sarratio = [12, 11];
break;
case 3:
sarratio = [10, 11];
break;
case 4:
sarratio = [16, 11];
break;
case 5:
sarratio = [40, 33];
break;
case 6:
sarratio = [24, 11];
break;
case 7:
sarratio = [20, 11];
break;
case 8:
sarratio = [32, 11];
break;
case 9:
sarratio = [80, 33];
break;
case 10:
sarratio = [18, 11];
break;
case 11:
sarratio = [15, 11];
break;
case 12:
sarratio = [64, 33];
break;
case 13:
sarratio = [160, 99];
break;
case 14:
sarratio = [4, 3];
break;
case 15:
sarratio = [3, 2];
break;
case 16:
sarratio = [2, 1];
break;
case 255:
{
sarratio = [expgolombdecoder.readunsignedbyte() << 8 | expgolombdecoder.readunsignedbyte(), expgolombdecoder.readunsignedbyte() << 8 | expgolombdecoder.readunsignedbyte()];
break;
}
}
if (sarratio) {
sarratio[0] / sarratio[1];
}
}
}
return {
profileidc: profileidc,
levelidc: levelidc,
profilecompatibility: profilecompatibility,
width: (picwidthinmbsminus1 + 1) * 16 - framecropleftoffset * 2 - framecroprightoffset * 2,
height: (2 - framembsonlyflag) * (picheightinmapunitsminus1 + 1) * 16 - framecroptopoffset * 2 - framecropbottomoffset * 2,
// sar is sample aspect ratio
sarratio: sarratio
};
};
};
_h264stream.prototype = new stream();
var h264 = {
h264stream: _h264stream,
nalbytestream: _nalbytestream
};
/**
* mux.js
*
* copyright (c) brightcove
* licensed apache-2.0 https://github.com/videojs/mux.js/blob/master/license
*
* utilities to detect basic properties and metadata about aac data.
*/
var adts_sampling_frequencies = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
var parseid3tagsize = function parseid3tagsize(header, byteindex) {
var returnsize = header[byteindex + 6] << 21 | header[byteindex + 7] << 14 | header[byteindex + 8] << 7 | header[byteindex + 9],
flags = header[byteindex + 5],
footerpresent = (flags & 16) >> 4; // if we get a negative returnsize clamp it to 0
returnsize = returnsize >= 0 ? returnsize : 0;
if (footerpresent) {
return returnsize + 20;
}
return returnsize + 10;
};
var getid3offset = function getid3offset(data, offset) {
if (data.length - offset < 10 || data[offset] !== 'i'.charcodeat(0) || data[offset + 1] !== 'd'.charcodeat(0) || data[offset + 2] !== '3'.charcodeat(0)) {
return offset;
}
offset += parseid3tagsize(data, offset);
return getid3offset(data, offset);
}; // todo: use vhs-utils
var islikelyaacdata$1 = function islikelyaacdata(data) {
var offset = getid3offset(data, 0);
return data.length >= offset + 2 && (data[offset] & 0xff) === 0xff && (data[offset + 1] & 0xf0) === 0xf0 && // verify that the 2 layer bits are 0, aka this
// is not mp3 data but aac data.
(data[offset + 1] & 0x16) === 0x10;
};
var parsesyncsafeinteger = function parsesyncsafeinteger(data) {
return data[0] << 21 | data[1] << 14 | data[2] << 7 | data[3];
}; // return a percent-encoded representation of the specified byte range
// @see http://en.wikipedia.org/wiki/percent-encoding
var percentencode = function percentencode(bytes, start, end) {
var i,
result = '';
for (i = start; i < end; i++) {
result += '%' + ('00' + bytes[i].tostring(16)).slice(-2);
}
return result;
}; // return the string representation of the specified byte range,
// interpreted as iso-8859-1.
var parseiso88591 = function parseiso88591(bytes, start, end) {
return unescape(percentencode(bytes, start, end)); // jshint ignore:line
};
var parseadtssize = function parseadtssize(header, byteindex) {
var lowthree = (header[byteindex + 5] & 0xe0) >> 5,
middle = header[byteindex + 4] << 3,
hightwo = header[byteindex + 3] & 0x3 << 11;
return hightwo | middle | lowthree;
};
var parsetype$2 = function parsetype(header, byteindex) {
if (header[byteindex] === 'i'.charcodeat(0) && header[byteindex + 1] === 'd'.charcodeat(0) && header[byteindex + 2] === '3'.charcodeat(0)) {
return 'timed-metadata';
} else if (header[byteindex] & 0xff === 0xff && (header[byteindex + 1] & 0xf0) === 0xf0) {
return 'audio';
}
return null;
};
var parsesamplerate = function parsesamplerate(packet) {
var i = 0;
while (i + 5 < packet.length) {
if (packet[i] !== 0xff || (packet[i + 1] & 0xf6) !== 0xf0) {
// if a valid header was not found, jump one forward and attempt to
// find a valid adts header starting at the next byte
i++;
continue;
}
return adts_sampling_frequencies[(packet[i + 2] & 0x3c) >>> 2];
}
return null;
};
var parseaactimestamp = function parseaactimestamp(packet) {
var framestart, framesize, frame, frameheader; // find the start of the first frame and the end of the tag
framestart = 10;
if (packet[5] & 0x40) {
// advance the frame start past the extended header
framestart += 4; // header size field
framestart += parsesyncsafeinteger(packet.subarray(10, 14));
} // parse one or more id3 frames
// http://id3.org/id3v2.3.0#id3v2_frame_overview
do {
// determine the number of bytes in this frame
framesize = parsesyncsafeinteger(packet.subarray(framestart + 4, framestart + 8));
if (framesize < 1) {
return null;
}
frameheader = string.fromcharcode(packet[framestart], packet[framestart + 1], packet[framestart + 2], packet[framestart + 3]);
if (frameheader === 'priv') {
frame = packet.subarray(framestart + 10, framestart + framesize + 10);
for (var i = 0; i < frame.bytelength; i++) {
if (frame[i] === 0) {
var owner = parseiso88591(frame, 0, i);
if (owner === 'com.apple.streaming.transportstreamtimestamp') {
var d = frame.subarray(i + 1);
var size = (d[3] & 0x01) << 30 | d[4] << 22 | d[5] << 14 | d[6] << 6 | d[7] >>> 2;
size *= 4;
size += d[7] & 0x03;
return size;
}
break;
}
}
}
framestart += 10; // advance past the frame header
framestart += framesize; // advance past the frame body
} while (framestart < packet.bytelength);
return null;
};
var utils = {
islikelyaacdata: islikelyaacdata$1,
parseid3tagsize: parseid3tagsize,
parseadtssize: parseadtssize,
parsetype: parsetype$2,
parsesamplerate: parsesamplerate,
parseaactimestamp: parseaactimestamp
};
var _aacstream;
/**
* splits an incoming stream of binary data into adts and id3 frames.
*/
_aacstream = function aacstream() {
var everything = new uint8array(),
timestamp = 0;
_aacstream.prototype.init.call(this);
this.settimestamp = function (timestamp) {
timestamp = timestamp;
};
this.push = function (bytes) {
var framesize = 0,
byteindex = 0,
bytesleft,
chunk,
packet,
templength; // if there are bytes remaining from the last segment, prepend them to the
// bytes that were pushed in
if (everything.length) {
templength = everything.length;
everything = new uint8array(bytes.bytelength + templength);
everything.set(everything.subarray(0, templength));
everything.set(bytes, templength);
} else {
everything = bytes;
}
while (everything.length - byteindex >= 3) {
if (everything[byteindex] === 'i'.charcodeat(0) && everything[byteindex + 1] === 'd'.charcodeat(0) && everything[byteindex + 2] === '3'.charcodeat(0)) {
// exit early because we don't have enough to parse
// the id3 tag header
if (everything.length - byteindex < 10) {
break;
} // check framesize
framesize = utils.parseid3tagsize(everything, byteindex); // exit early if we don't have enough in the buffer
// to emit a full packet
// add to byteindex to support multiple id3 tags in sequence
if (byteindex + framesize > everything.length) {
break;
}
chunk = {
type: 'timed-metadata',
data: everything.subarray(byteindex, byteindex + framesize)
};
this.trigger('data', chunk);
byteindex += framesize;
continue;
} else if ((everything[byteindex] & 0xff) === 0xff && (everything[byteindex + 1] & 0xf0) === 0xf0) {
// exit early because we don't have enough to parse
// the adts frame header
if (everything.length - byteindex < 7) {
break;
}
framesize = utils.parseadtssize(everything, byteindex); // exit early if we don't have enough in the buffer
// to emit a full packet
if (byteindex + framesize > everything.length) {
break;
}
packet = {
type: 'audio',
data: everything.subarray(byteindex, byteindex + framesize),
pts: timestamp,
dts: timestamp
};
this.trigger('data', packet);
byteindex += framesize;
continue;
}
byteindex++;
}
bytesleft = everything.length - byteindex;
if (bytesleft > 0) {
everything = everything.subarray(byteindex);
} else {
everything = new uint8array();
}
};
this.reset = function () {
everything = new uint8array();
this.trigger('reset');
};
this.endtimeline = function () {
everything = new uint8array();
this.trigger('endedtimeline');
};
};
_aacstream.prototype = new stream();
var aac = _aacstream; // constants
var audio_properties = ['audioobjecttype', 'channelcount', 'samplerate', 'samplingfrequencyindex', 'samplesize'];
var audioproperties = audio_properties;
var video_properties = ['width', 'height', 'profileidc', 'levelidc', 'profilecompatibility', 'sarratio'];
var videoproperties = video_properties;
var h264stream = h264.h264stream;
var islikelyaacdata = utils.islikelyaacdata;
var one_second_in_ts$1 = clock.one_second_in_ts; // object types
var _videosegmentstream, _audiosegmentstream, _transmuxer, _coalescestream;
var retriggerforstream = function retriggerforstream(key, event) {
event.stream = key;
this.trigger('log', event);
};
var addpipelinelogretriggers = function addpipelinelogretriggers(transmuxer, pipeline) {
var keys = object.keys(pipeline);
for (var i = 0; i < keys.length; i++) {
var key = keys[i]; // skip non-stream keys and headofpipeline
// which is just a duplicate
if (key === 'headofpipeline' || !pipeline[key].on) {
continue;
}
pipeline[key].on('log', retriggerforstream.bind(transmuxer, key));
}
};
/**
* compare two arrays (even typed) for same-ness
*/
var arrayequals = function arrayequals(a, b) {
var i;
if (a.length !== b.length) {
return false;
} // compare the value of each element in the array
for (i = 0; i < a.length; i++) {
if (a[i] !== b[i]) {
return false;
}
}
return true;
};
var generatesegmenttiminginfo = function generatesegmenttiminginfo(basemediadecodetime, startdts, startpts, enddts, endpts, prependedcontentduration) {
var ptsoffsetfromdts = startpts - startdts,
decodeduration = enddts - startdts,
presentationduration = endpts - startpts; // the pts and dts values are based on the actual stream times from the segment,
// however, the player time values will reflect a start from the basemediadecodetime.
// in order to provide relevant values for the player times, base timing info on the
// basemediadecodetime and the dts and pts durations of the segment.
return {
start: {
dts: basemediadecodetime,
pts: basemediadecodetime + ptsoffsetfromdts
},
end: {
dts: basemediadecodetime + decodeduration,
pts: basemediadecodetime + presentationduration
},
prependedcontentduration: prependedcontentduration,
basemediadecodetime: basemediadecodetime
};
};
/**
* constructs a single-track, iso bmff media segment from aac data
* events. the output of this stream can be fed to a sourcebuffer
* configured with a suitable initialization segment.
* @param track {object} track metadata configuration
* @param options {object} transmuxer options object
* @param options.keeporiginaltimestamps {boolean} if true, keep the timestamps
* in the source; false to adjust the first segment to start at 0.
*/
_audiosegmentstream = function audiosegmentstream(track, options) {
var adtsframes = [],
sequencenumber,
earliestalloweddts = 0,
audioappendstartts = 0,
videobasemediadecodetime = infinity;
options = options || {};
sequencenumber = options.firstsequencenumber || 0;
_audiosegmentstream.prototype.init.call(this);
this.push = function (data) {
trackdecodeinfo.collectdtsinfo(track, data);
if (track) {
audioproperties.foreach(function (prop) {
track[prop] = data[prop];
});
} // buffer audio data until end() is called
adtsframes.push(data);
};
this.setearliestdts = function (earliestdts) {
earliestalloweddts = earliestdts;
};
this.setvideobasemediadecodetime = function (basemediadecodetime) {
videobasemediadecodetime = basemediadecodetime;
};
this.setaudioappendstart = function (timestamp) {
audioappendstartts = timestamp;
};
this.flush = function () {
var frames, moof, mdat, boxes, frameduration, segmentduration, videoclockcyclesofsilenceprefixed; // return early if no audio data has been observed
if (adtsframes.length === 0) {
this.trigger('done', 'audiosegmentstream');
return;
}
frames = audioframeutils.trimadtsframesbyearliestdts(adtsframes, track, earliestalloweddts);
track.basemediadecodetime = trackdecodeinfo.calculatetrackbasemediadecodetime(track, options.keeporiginaltimestamps); // amount of audio filled but the value is in video clock rather than audio clock
videoclockcyclesofsilenceprefixed = audioframeutils.prefixwithsilence(track, frames, audioappendstartts, videobasemediadecodetime); // we have to build the index from byte locations to
// samples (that is, adts frames) in the audio data
track.samples = audioframeutils.generatesampletable(frames); // concatenate the audio data to constuct the mdat
mdat = mp4generator.mdat(audioframeutils.concatenateframedata(frames));
adtsframes = [];
moof = mp4generator.moof(sequencenumber, [track]);
boxes = new uint8array(moof.bytelength + mdat.bytelength); // bump the sequence number for next time
sequencenumber++;
boxes.set(moof);
boxes.set(mdat, moof.bytelength);
trackdecodeinfo.cleardtsinfo(track);
frameduration = math.ceil(one_second_in_ts$1 * 1024 / track.samplerate); // todo this check was added to maintain backwards compatibility (particularly with
// tests) on adding the timinginfo event. however, it seems unlikely that there's a
// valid use-case where an init segment/data should be triggered without associated
// frames. leaving for now, but should be looked into.
if (frames.length) {
segmentduration = frames.length * frameduration;
this.trigger('segmenttiminginfo', generatesegmenttiminginfo( // the audio track's basemediadecodetime is in audio clock cycles, but the
// frame info is in video clock cycles. convert to match expectation of
// listeners (that all timestamps will be based on video clock cycles).
clock.audiotstovideots(track.basemediadecodetime, track.samplerate), // frame times are already in video clock, as is segment duration
frames[0].dts, frames[0].pts, frames[0].dts + segmentduration, frames[0].pts + segmentduration, videoclockcyclesofsilenceprefixed || 0));
this.trigger('timinginfo', {
start: frames[0].pts,
end: frames[0].pts + segmentduration
});
}
this.trigger('data', {
track: track,
boxes: boxes
});
this.trigger('done', 'audiosegmentstream');
};
this.reset = function () {
trackdecodeinfo.cleardtsinfo(track);
adtsframes = [];
this.trigger('reset');
};
};
_audiosegmentstream.prototype = new stream();
/**
* constructs a single-track, iso bmff media segment from h264 data
* events. the output of this stream can be fed to a sourcebuffer
* configured with a suitable initialization segment.
* @param track {object} track metadata configuration
* @param options {object} transmuxer options object
* @param options.aligngopsatend {boolean} if true, start from the end of the
* gopstoalignwith list when attempting to align gop pts
* @param options.keeporiginaltimestamps {boolean} if true, keep the timestamps
* in the source; false to adjust the first segment to start at 0.
*/
_videosegmentstream = function videosegmentstream(track, options) {
var sequencenumber,
nalunits = [],
gopstoalignwith = [],
config,
pps;
options = options || {};
sequencenumber = options.firstsequencenumber || 0;
_videosegmentstream.prototype.init.call(this);
delete track.minpts;
this.gopcache_ = [];
/**
* constructs a iso bmff segment given h264 nalunits
* @param {object} nalunit a data event representing a nalunit
* @param {string} nalunit.nalunittype
* @param {object} nalunit.config properties for a mp4 track
* @param {uint8array} nalunit.data the nalunit bytes
* @see lib/codecs/h264.js
**/
this.push = function (nalunit) {
trackdecodeinfo.collectdtsinfo(track, nalunit); // record the track config
if (nalunit.nalunittype === 'seq_parameter_set_rbsp' && !config) {
config = nalunit.config;
track.sps = [nalunit.data];
videoproperties.foreach(function (prop) {
track[prop] = config[prop];
}, this);
}
if (nalunit.nalunittype === 'pic_parameter_set_rbsp' && !pps) {
pps = nalunit.data;
track.pps = [nalunit.data];
} // buffer video until flush() is called
nalunits.push(nalunit);
};
/**
* pass constructed iso bmff track and boxes on to the
* next stream in the pipeline
**/
this.flush = function () {
var frames,
gopforfusion,
gops,
moof,
mdat,
boxes,
prependedcontentduration = 0,
firstgop,
lastgop; // throw away nalunits at the start of the byte stream until
// we find the first aud
while (nalunits.length) {
if (nalunits[0].nalunittype === 'access_unit_delimiter_rbsp') {
break;
}
nalunits.shift();
} // return early if no video data has been observed
if (nalunits.length === 0) {
this.resetstream_();
this.trigger('done', 'videosegmentstream');
return;
} // organize the raw nal-units into arrays that represent
// higher-level constructs such as frames and gops
// (group-of-pictures)
frames = frameutils.groupnalsintoframes(nalunits);
gops = frameutils.groupframesintogops(frames); // if the first frame of this fragment is not a keyframe we have
// a problem since mse (on chrome) requires a leading keyframe.
//
// we have two approaches to repairing this situation:
// 1) gop-fusion:
// this is where we keep track of the gops (group-of-pictures)
// from previous fragments and attempt to find one that we can
// prepend to the current fragment in order to create a valid
// fragment.
// 2) keyframe-pulling:
// here we search for the first keyframe in the fragment and
// throw away all the frames between the start of the fragment
// and that keyframe. we then extend the duration and pull the
// pts of the keyframe forward so that it covers the time range
// of the frames that were disposed of.
//
// #1 is far prefereable over #2 which can cause "stuttering" but
// requires more things to be just right.
if (!gops[0][0].keyframe) {
// search for a gop for fusion from our gopcache
gopforfusion = this.getgopforfusion_(nalunits[0], track);
if (gopforfusion) {
// in order to provide more accurate timing information about the segment, save
// the number of seconds prepended to the original segment due to gop fusion
prependedcontentduration = gopforfusion.duration;
gops.unshift(gopforfusion); // adjust gops' metadata to account for the inclusion of the
// new gop at the beginning
gops.bytelength += gopforfusion.bytelength;
gops.nalcount += gopforfusion.nalcount;
gops.pts = gopforfusion.pts;
gops.dts = gopforfusion.dts;
gops.duration += gopforfusion.duration;
} else {
// if we didn't find a candidate gop fall back to keyframe-pulling
gops = frameutils.extendfirstkeyframe(gops);
}
} // trim gops to align with gopstoalignwith
if (gopstoalignwith.length) {
var alignedgops;
if (options.aligngopsatend) {
alignedgops = this.aligngopsatend_(gops);
} else {
alignedgops = this.aligngopsatstart_(gops);
}
if (!alignedgops) {
// save all the nals in the last gop into the gop cache
this.gopcache_.unshift({
gop: gops.pop(),
pps: track.pps,
sps: track.sps
}); // keep a maximum of 6 gops in the cache
this.gopcache_.length = math.min(6, this.gopcache_.length); // clear nalunits
nalunits = []; // return early no gops can be aligned with desired gopstoalignwith
this.resetstream_();
this.trigger('done', 'videosegmentstream');
return;
} // some gops were trimmed. clear dts info so minsegmentdts and pts are correct
// when recalculated before sending off to coalescestream
trackdecodeinfo.cleardtsinfo(track);
gops = alignedgops;
}
trackdecodeinfo.collectdtsinfo(track, gops); // first, we have to build the index from byte locations to
// samples (that is, frames) in the video data
track.samples = frameutils.generatesampletable(gops); // concatenate the video data and construct the mdat
mdat = mp4generator.mdat(frameutils.concatenatenaldata(gops));
track.basemediadecodetime = trackdecodeinfo.calculatetrackbasemediadecodetime(track, options.keeporiginaltimestamps);
this.trigger('processedgopsinfo', gops.map(function (gop) {
return {
pts: gop.pts,
dts: gop.dts,
bytelength: gop.bytelength
};
}));
firstgop = gops[0];
lastgop = gops[gops.length - 1];
this.trigger('segmenttiminginfo', generatesegmenttiminginfo(track.basemediadecodetime, firstgop.dts, firstgop.pts, lastgop.dts + lastgop.duration, lastgop.pts + lastgop.duration, prependedcontentduration));
this.trigger('timinginfo', {
start: gops[0].pts,
end: gops[gops.length - 1].pts + gops[gops.length - 1].duration
}); // save all the nals in the last gop into the gop cache
this.gopcache_.unshift({
gop: gops.pop(),
pps: track.pps,
sps: track.sps
}); // keep a maximum of 6 gops in the cache
this.gopcache_.length = math.min(6, this.gopcache_.length); // clear nalunits
nalunits = [];
this.trigger('basemediadecodetime', track.basemediadecodetime);
this.trigger('timelinestartinfo', track.timelinestartinfo);
moof = mp4generator.moof(sequencenumber, [track]); // it would be great to allocate this array up front instead of
// throwing away hundreds of media segment fragments
boxes = new uint8array(moof.bytelength + mdat.bytelength); // bump the sequence number for next time
sequencenumber++;
boxes.set(moof);
boxes.set(mdat, moof.bytelength);
this.trigger('data', {
track: track,
boxes: boxes
});
this.resetstream_(); // continue with the flush process now
this.trigger('done', 'videosegmentstream');
};
this.reset = function () {
this.resetstream_();
nalunits = [];
this.gopcache_.length = 0;
gopstoalignwith.length = 0;
this.trigger('reset');
};
this.resetstream_ = function () {
trackdecodeinfo.cleardtsinfo(track); // reset config and pps because they may differ across segments
// for instance, when we are rendition switching
config = undefined;
pps = undefined;
}; // search for a candidate gop for gop-fusion from the gop cache and
// return it or return null if no good candidate was found
this.getgopforfusion_ = function (nalunit) {
var halfsecond = 45000,
// half-a-second in a 90khz clock
allowableoverlap = 10000,
// about 3 frames @ 30fps
nearestdistance = infinity,
dtsdistance,
nearestgopobj,
currentgop,
currentgopobj,
i; // search for the gop nearest to the beginning of this nal unit
for (i = 0; i < this.gopcache_.length; i++) {
currentgopobj = this.gopcache_[i];
currentgop = currentgopobj.gop; // reject gops with different sps or pps
if (!(track.pps && arrayequals(track.pps[0], currentgopobj.pps[0])) || !(track.sps && arrayequals(track.sps[0], currentgopobj.sps[0]))) {
continue;
} // reject gops that would require a negative basemediadecodetime
if (currentgop.dts < track.timelinestartinfo.dts) {
continue;
} // the distance between the end of the gop and the start of the nalunit
dtsdistance = nalunit.dts - currentgop.dts - currentgop.duration; // only consider gops that start before the nal unit and end within
// a half-second of the nal unit
if (dtsdistance >= -allowableoverlap && dtsdistance <= halfsecond) {
// always use the closest gop we found if there is more than
// one candidate
if (!nearestgopobj || nearestdistance > dtsdistance) {
nearestgopobj = currentgopobj;
nearestdistance = dtsdistance;
}
}
}
if (nearestgopobj) {
return nearestgopobj.gop;
}
return null;
}; // trim gop list to the first gop found that has a matching pts with a gop in the list
// of gopstoalignwith starting from the start of the list
this.aligngopsatstart_ = function (gops) {
var alignindex, gopindex, align, gop, bytelength, nalcount, duration, alignedgops;
bytelength = gops.bytelength;
nalcount = gops.nalcount;
duration = gops.duration;
alignindex = gopindex = 0;
while (alignindex < gopstoalignwith.length && gopindex < gops.length) {
align = gopstoalignwith[alignindex];
gop = gops[gopindex];
if (align.pts === gop.pts) {
break;
}
if (gop.pts > align.pts) {
// this current gop starts after the current gop we want to align on, so increment
// align index
alignindex++;
continue;
} // current gop starts before the current gop we want to align on. so increment gop
// index
gopindex++;
bytelength -= gop.bytelength;
nalcount -= gop.nalcount;
duration -= gop.duration;
}
if (gopindex === 0) {
// no gops to trim
return gops;
}
if (gopindex === gops.length) {
// all gops trimmed, skip appending all gops
return null;
}
alignedgops = gops.slice(gopindex);
alignedgops.bytelength = bytelength;
alignedgops.duration = duration;
alignedgops.nalcount = nalcount;
alignedgops.pts = alignedgops[0].pts;
alignedgops.dts = alignedgops[0].dts;
return alignedgops;
}; // trim gop list to the first gop found that has a matching pts with a gop in the list
// of gopstoalignwith starting from the end of the list
this.aligngopsatend_ = function (gops) {
var alignindex, gopindex, align, gop, alignendindex, matchfound;
alignindex = gopstoalignwith.length - 1;
gopindex = gops.length - 1;
alignendindex = null;
matchfound = false;
while (alignindex >= 0 && gopindex >= 0) {
align = gopstoalignwith[alignindex];
gop = gops[gopindex];
if (align.pts === gop.pts) {
matchfound = true;
break;
}
if (align.pts > gop.pts) {
alignindex--;
continue;
}
if (alignindex === gopstoalignwith.length - 1) {
// gop.pts is greater than the last alignment candidate. if no match is found
// by the end of this loop, we still want to append gops that come after this
// point
alignendindex = gopindex;
}
gopindex--;
}
if (!matchfound && alignendindex === null) {
return null;
}
var trimindex;
if (matchfound) {
trimindex = gopindex;
} else {
trimindex = alignendindex;
}
if (trimindex === 0) {
return gops;
}
var alignedgops = gops.slice(trimindex);
var metadata = alignedgops.reduce(function (total, gop) {
total.bytelength += gop.bytelength;
total.duration += gop.duration;
total.nalcount += gop.nalcount;
return total;
}, {
bytelength: 0,
duration: 0,
nalcount: 0
});
alignedgops.bytelength = metadata.bytelength;
alignedgops.duration = metadata.duration;
alignedgops.nalcount = metadata.nalcount;
alignedgops.pts = alignedgops[0].pts;
alignedgops.dts = alignedgops[0].dts;
return alignedgops;
};
this.aligngopswith = function (newgopstoalignwith) {
gopstoalignwith = newgopstoalignwith;
};
};
_videosegmentstream.prototype = new stream();
/**
* a stream that can combine multiple streams (ie. audio & video)
* into a single output segment for mse. also supports audio-only
* and video-only streams.
* @param options {object} transmuxer options object
* @param options.keeporiginaltimestamps {boolean} if true, keep the timestamps
* in the source; false to adjust the first segment to start at media timeline start.
*/
_coalescestream = function coalescestream(options, metadatastream) {
// number of tracks per output segment
// if greater than 1, we combine multiple
// tracks into a single segment
this.numberoftracks = 0;
this.metadatastream = metadatastream;
options = options || {};
if (typeof options.remux !== 'undefined') {
this.remuxtracks = !!options.remux;
} else {
this.remuxtracks = true;
}
if (typeof options.keeporiginaltimestamps === 'boolean') {
this.keeporiginaltimestamps = options.keeporiginaltimestamps;
} else {
this.keeporiginaltimestamps = false;
}
this.pendingtracks = [];
this.videotrack = null;
this.pendingboxes = [];
this.pendingcaptions = [];
this.pendingmetadata = [];
this.pendingbytes = 0;
this.emittedtracks = 0;
_coalescestream.prototype.init.call(this); // take output from multiple
this.push = function (output) {
// buffer incoming captions until the associated video segment
// finishes
if (output.text) {
return this.pendingcaptions.push(output);
} // buffer incoming id3 tags until the final flush
if (output.frames) {
return this.pendingmetadata.push(output);
} // add this track to the list of pending tracks and store
// important information required for the construction of
// the final segment
this.pendingtracks.push(output.track);
this.pendingbytes += output.boxes.bytelength; // todo: is there an issue for this against chrome?
// we unshift audio and push video because
// as of chrome 75 when switching from
// one init segment to another if the video
// mdat does not appear after the audio mdat
// only audio will play for the duration of our transmux.
if (output.track.type === 'video') {
this.videotrack = output.track;
this.pendingboxes.push(output.boxes);
}
if (output.track.type === 'audio') {
this.audiotrack = output.track;
this.pendingboxes.unshift(output.boxes);
}
};
};
_coalescestream.prototype = new stream();
_coalescestream.prototype.flush = function (flushsource) {
var offset = 0,
event = {
captions: [],
captionstreams: {},
metadata: [],
info: {}
},
caption,
id3,
initsegment,
timelinestartpts = 0,
i;
if (this.pendingtracks.length < this.numberoftracks) {
if (flushsource !== 'videosegmentstream' && flushsource !== 'audiosegmentstream') {
// return because we haven't received a flush from a data-generating
// portion of the segment (meaning that we have only recieved meta-data
// or captions.)
return;
} else if (this.remuxtracks) {
// return until we have enough tracks from the pipeline to remux (if we
// are remuxing audio and video into a single mp4)
return;
} else if (this.pendingtracks.length === 0) {
// in the case where we receive a flush without any data having been
// received we consider it an emitted track for the purposes of coalescing
// `done` events.
// we do this for the case where there is an audio and video track in the
// segment but no audio data. (seen in several playlists with alternate
// audio tracks and no audio present in the main ts segments.)
this.emittedtracks++;
if (this.emittedtracks >= this.numberoftracks) {
this.trigger('done');
this.emittedtracks = 0;
}
return;
}
}
if (this.videotrack) {
timelinestartpts = this.videotrack.timelinestartinfo.pts;
videoproperties.foreach(function (prop) {
event.info[prop] = this.videotrack[prop];
}, this);
} else if (this.audiotrack) {
timelinestartpts = this.audiotrack.timelinestartinfo.pts;
audioproperties.foreach(function (prop) {
event.info[prop] = this.audiotrack[prop];
}, this);
}
if (this.videotrack || this.audiotrack) {
if (this.pendingtracks.length === 1) {
event.type = this.pendingtracks[0].type;
} else {
event.type = 'combined';
}
this.emittedtracks += this.pendingtracks.length;
initsegment = mp4generator.initsegment(this.pendingtracks); // create a new typed array to hold the init segment
event.initsegment = new uint8array(initsegment.bytelength); // create an init segment containing a moov
// and track definitions
event.initsegment.set(initsegment); // create a new typed array to hold the moof+mdats
event.data = new uint8array(this.pendingbytes); // append each moof+mdat (one per track) together
for (i = 0; i < this.pendingboxes.length; i++) {
event.data.set(this.pendingboxes[i], offset);
offset += this.pendingboxes[i].bytelength;
} // translate caption pts times into second offsets to match the
// video timeline for the segment, and add track info
for (i = 0; i < this.pendingcaptions.length; i++) {
caption = this.pendingcaptions[i];
caption.starttime = clock.metadatatstoseconds(caption.startpts, timelinestartpts, this.keeporiginaltimestamps);
caption.endtime = clock.metadatatstoseconds(caption.endpts, timelinestartpts, this.keeporiginaltimestamps);
event.captionstreams[caption.stream] = true;
event.captions.push(caption);
} // translate id3 frame pts times into second offsets to match the
// video timeline for the segment
for (i = 0; i < this.pendingmetadata.length; i++) {
id3 = this.pendingmetadata[i];
id3.cuetime = clock.metadatatstoseconds(id3.pts, timelinestartpts, this.keeporiginaltimestamps);
event.metadata.push(id3);
} // we add this to every single emitted segment even though we only need
// it for the first
event.metadata.dispatchtype = this.metadatastream.dispatchtype; // reset stream state
this.pendingtracks.length = 0;
this.videotrack = null;
this.pendingboxes.length = 0;
this.pendingcaptions.length = 0;
this.pendingbytes = 0;
this.pendingmetadata.length = 0; // emit the built segment
// we include captions and id3 tags for backwards compatibility,
// ideally we should send only video and audio in the data event
this.trigger('data', event); // emit each caption to the outside world
// ideally, this would happen immediately on parsing captions,
// but we need to ensure that video data is sent back first
// so that caption timing can be adjusted to match video timing
for (i = 0; i < event.captions.length; i++) {
caption = event.captions[i];
this.trigger('caption', caption);
} // emit each id3 tag to the outside world
// ideally, this would happen immediately on parsing the tag,
// but we need to ensure that video data is sent back first
// so that id3 frame timing can be adjusted to match video timing
for (i = 0; i < event.metadata.length; i++) {
id3 = event.metadata[i];
this.trigger('id3frame', id3);
}
} // only emit `done` if all tracks have been flushed and emitted
if (this.emittedtracks >= this.numberoftracks) {
this.trigger('done');
this.emittedtracks = 0;
}
};
_coalescestream.prototype.setremux = function (val) {
this.remuxtracks = val;
};
/**
* a stream that expects mp2t binary data as input and produces
* corresponding media segments, suitable for use with media source
* extension (mse) implementations that support the iso bmff byte
* stream format, like chrome.
*/
_transmuxer = function transmuxer(options) {
var self = this,
hasflushed = true,
videotrack,
audiotrack;
_transmuxer.prototype.init.call(this);
options = options || {};
this.basemediadecodetime = options.basemediadecodetime || 0;
this.transmuxpipeline_ = {};
this.setupaacpipeline = function () {
var pipeline = {};
this.transmuxpipeline_ = pipeline;
pipeline.type = 'aac';
pipeline.metadatastream = new m2ts_1.metadatastream(); // set up the parsing pipeline
pipeline.aacstream = new aac();
pipeline.audiotimestamprolloverstream = new m2ts_1.timestamprolloverstream('audio');
pipeline.timedmetadatatimestamprolloverstream = new m2ts_1.timestamprolloverstream('timed-metadata');
pipeline.adtsstream = new adts();
pipeline.coalescestream = new _coalescestream(options, pipeline.metadatastream);
pipeline.headofpipeline = pipeline.aacstream;
pipeline.aacstream.pipe(pipeline.audiotimestamprolloverstream).pipe(pipeline.adtsstream);
pipeline.aacstream.pipe(pipeline.timedmetadatatimestamprolloverstream).pipe(pipeline.metadatastream).pipe(pipeline.coalescestream);
pipeline.metadatastream.on('timestamp', function (frame) {
pipeline.aacstream.settimestamp(frame.timestamp);
});
pipeline.aacstream.on('data', function (data) {
if (data.type !== 'timed-metadata' && data.type !== 'audio' || pipeline.audiosegmentstream) {
return;
}
audiotrack = audiotrack || {
timelinestartinfo: {
basemediadecodetime: self.basemediadecodetime
},
codec: 'adts',
type: 'audio'
}; // hook up the audio segment stream to the first track with aac data
pipeline.coalescestream.numberoftracks++;
pipeline.audiosegmentstream = new _audiosegmentstream(audiotrack, options);
pipeline.audiosegmentstream.on('log', self.getlogtrigger_('audiosegmentstream'));
pipeline.audiosegmentstream.on('timinginfo', self.trigger.bind(self, 'audiotiminginfo')); // set up the final part of the audio pipeline
pipeline.adtsstream.pipe(pipeline.audiosegmentstream).pipe(pipeline.coalescestream); // emit pmt info
self.trigger('trackinfo', {
hasaudio: !!audiotrack,
hasvideo: !!videotrack
});
}); // re-emit any data coming from the coalesce stream to the outside world
pipeline.coalescestream.on('data', this.trigger.bind(this, 'data')); // let the consumer know we have finished flushing the entire pipeline
pipeline.coalescestream.on('done', this.trigger.bind(this, 'done'));
addpipelinelogretriggers(this, pipeline);
};
this.setuptspipeline = function () {
var pipeline = {};
this.transmuxpipeline_ = pipeline;
pipeline.type = 'ts';
pipeline.metadatastream = new m2ts_1.metadatastream(); // set up the parsing pipeline
pipeline.packetstream = new m2ts_1.transportpacketstream();
pipeline.parsestream = new m2ts_1.transportparsestream();
pipeline.elementarystream = new m2ts_1.elementarystream();
pipeline.timestamprolloverstream = new m2ts_1.timestamprolloverstream();
pipeline.adtsstream = new adts();
pipeline.h264stream = new h264stream();
pipeline.captionstream = new m2ts_1.captionstream(options);
pipeline.coalescestream = new _coalescestream(options, pipeline.metadatastream);
pipeline.headofpipeline = pipeline.packetstream; // disassemble mpeg2-ts packets into elementary streams
pipeline.packetstream.pipe(pipeline.parsestream).pipe(pipeline.elementarystream).pipe(pipeline.timestamprolloverstream); // !!this order is important!!
// demux the streams
pipeline.timestamprolloverstream.pipe(pipeline.h264stream);
pipeline.timestamprolloverstream.pipe(pipeline.adtsstream);
pipeline.timestamprolloverstream.pipe(pipeline.metadatastream).pipe(pipeline.coalescestream); // hook up cea-608/708 caption stream
pipeline.h264stream.pipe(pipeline.captionstream).pipe(pipeline.coalescestream);
pipeline.elementarystream.on('data', function (data) {
var i;
if (data.type === 'metadata') {
i = data.tracks.length; // scan the tracks listed in the metadata
while (i--) {
if (!videotrack && data.tracks[i].type === 'video') {
videotrack = data.tracks[i];
videotrack.timelinestartinfo.basemediadecodetime = self.basemediadecodetime;
} else if (!audiotrack && data.tracks[i].type === 'audio') {
audiotrack = data.tracks[i];
audiotrack.timelinestartinfo.basemediadecodetime = self.basemediadecodetime;
}
} // hook up the video segment stream to the first track with h264 data
if (videotrack && !pipeline.videosegmentstream) {
pipeline.coalescestream.numberoftracks++;
pipeline.videosegmentstream = new _videosegmentstream(videotrack, options);
pipeline.videosegmentstream.on('log', self.getlogtrigger_('videosegmentstream'));
pipeline.videosegmentstream.on('timelinestartinfo', function (timelinestartinfo) {
// when video emits timelinestartinfo data after a flush, we forward that
// info to the audiosegmentstream, if it exists, because video timeline
// data takes precedence. do not do this if keeporiginaltimestamps is set,
// because this is a particularly subtle form of timestamp alteration.
if (audiotrack && !options.keeporiginaltimestamps) {
audiotrack.timelinestartinfo = timelinestartinfo; // on the first segment we trim aac frames that exist before the
// very earliest dts we have seen in video because chrome will
// interpret any video track with a basemediadecodetime that is
// non-zero as a gap.
pipeline.audiosegmentstream.setearliestdts(timelinestartinfo.dts - self.basemediadecodetime);
}
});
pipeline.videosegmentstream.on('processedgopsinfo', self.trigger.bind(self, 'gopinfo'));
pipeline.videosegmentstream.on('segmenttiminginfo', self.trigger.bind(self, 'videosegmenttiminginfo'));
pipeline.videosegmentstream.on('basemediadecodetime', function (basemediadecodetime) {
if (audiotrack) {
pipeline.audiosegmentstream.setvideobasemediadecodetime(basemediadecodetime);
}
});
pipeline.videosegmentstream.on('timinginfo', self.trigger.bind(self, 'videotiminginfo')); // set up the final part of the video pipeline
pipeline.h264stream.pipe(pipeline.videosegmentstream).pipe(pipeline.coalescestream);
}
if (audiotrack && !pipeline.audiosegmentstream) {
// hook up the audio segment stream to the first track with aac data
pipeline.coalescestream.numberoftracks++;
pipeline.audiosegmentstream = new _audiosegmentstream(audiotrack, options);
pipeline.audiosegmentstream.on('log', self.getlogtrigger_('audiosegmentstream'));
pipeline.audiosegmentstream.on('timinginfo', self.trigger.bind(self, 'audiotiminginfo'));
pipeline.audiosegmentstream.on('segmenttiminginfo', self.trigger.bind(self, 'audiosegmenttiminginfo')); // set up the final part of the audio pipeline
pipeline.adtsstream.pipe(pipeline.audiosegmentstream).pipe(pipeline.coalescestream);
} // emit pmt info
self.trigger('trackinfo', {
hasaudio: !!audiotrack,
hasvideo: !!videotrack
});
}
}); // re-emit any data coming from the coalesce stream to the outside world
pipeline.coalescestream.on('data', this.trigger.bind(this, 'data'));
pipeline.coalescestream.on('id3frame', function (id3frame) {
id3frame.dispatchtype = pipeline.metadatastream.dispatchtype;
self.trigger('id3frame', id3frame);
});
pipeline.coalescestream.on('caption', this.trigger.bind(this, 'caption')); // let the consumer know we have finished flushing the entire pipeline
pipeline.coalescestream.on('done', this.trigger.bind(this, 'done'));
addpipelinelogretriggers(this, pipeline);
}; // hook up the segment streams once track metadata is delivered
this.setbasemediadecodetime = function (basemediadecodetime) {
var pipeline = this.transmuxpipeline_;
if (!options.keeporiginaltimestamps) {
this.basemediadecodetime = basemediadecodetime;
}
if (audiotrack) {
audiotrack.timelinestartinfo.dts = undefined;
audiotrack.timelinestartinfo.pts = undefined;
trackdecodeinfo.cleardtsinfo(audiotrack);
if (pipeline.audiotimestamprolloverstream) {
pipeline.audiotimestamprolloverstream.discontinuity();
}
}
if (videotrack) {
if (pipeline.videosegmentstream) {
pipeline.videosegmentstream.gopcache_ = [];
}
videotrack.timelinestartinfo.dts = undefined;
videotrack.timelinestartinfo.pts = undefined;
trackdecodeinfo.cleardtsinfo(videotrack);
pipeline.captionstream.reset();
}
if (pipeline.timestamprolloverstream) {
pipeline.timestamprolloverstream.discontinuity();
}
};
this.setaudioappendstart = function (timestamp) {
if (audiotrack) {
this.transmuxpipeline_.audiosegmentstream.setaudioappendstart(timestamp);
}
};
this.setremux = function (val) {
var pipeline = this.transmuxpipeline_;
options.remux = val;
if (pipeline && pipeline.coalescestream) {
pipeline.coalescestream.setremux(val);
}
};
this.aligngopswith = function (gopstoalignwith) {
if (videotrack && this.transmuxpipeline_.videosegmentstream) {
this.transmuxpipeline_.videosegmentstream.aligngopswith(gopstoalignwith);
}
};
this.getlogtrigger_ = function (key) {
var self = this;
return function (event) {
event.stream = key;
self.trigger('log', event);
};
}; // feed incoming data to the front of the parsing pipeline
this.push = function (data) {
if (hasflushed) {
var isaac = islikelyaacdata(data);
if (isaac && this.transmuxpipeline_.type !== 'aac') {
this.setupaacpipeline();
} else if (!isaac && this.transmuxpipeline_.type !== 'ts') {
this.setuptspipeline();
}
hasflushed = false;
}
this.transmuxpipeline_.headofpipeline.push(data);
}; // flush any buffered data
this.flush = function () {
hasflushed = true; // start at the top of the pipeline and flush all pending work
this.transmuxpipeline_.headofpipeline.flush();
};
this.endtimeline = function () {
this.transmuxpipeline_.headofpipeline.endtimeline();
};
this.reset = function () {
if (this.transmuxpipeline_.headofpipeline) {
this.transmuxpipeline_.headofpipeline.reset();
}
}; // caption data has to be reset when seeking outside buffered range
this.resetcaptions = function () {
if (this.transmuxpipeline_.captionstream) {
this.transmuxpipeline_.captionstream.reset();
}
};
};
_transmuxer.prototype = new stream();
var transmuxer = {
transmuxer: _transmuxer,
videosegmentstream: _videosegmentstream,
audiosegmentstream: _audiosegmentstream,
audio_properties: audioproperties,
video_properties: videoproperties,
// exported for testing
generatesegmenttiminginfo: generatesegmenttiminginfo
};
/**
* mux.js
*
* copyright (c) brightcove
* licensed apache-2.0 https://github.com/videojs/mux.js/blob/master/license
*/
var tounsigned$3 = function tounsigned(value) {
return value >>> 0;
};
var tohexstring$1 = function tohexstring(value) {
return ('00' + value.tostring(16)).slice(-2);
};
var bin = {
tounsigned: tounsigned$3,
tohexstring: tohexstring$1
};
var parsetype$1 = function parsetype(buffer) {
var result = '';
result += string.fromcharcode(buffer[0]);
result += string.fromcharcode(buffer[1]);
result += string.fromcharcode(buffer[2]);
result += string.fromcharcode(buffer[3]);
return result;
};
var parsetype_1 = parsetype$1;
var tounsigned$2 = bin.tounsigned;
var findbox = function findbox(data, path) {
var results = [],
i,
size,
type,
end,
subresults;
if (!path.length) {
// short-circuit the search for empty paths
return null;
}
for (i = 0; i < data.bytelength;) {
size = tounsigned$2(data[i] << 24 | data[i + 1] << 16 | data[i + 2] << 8 | data[i + 3]);
type = parsetype_1(data.subarray(i + 4, i + 8));
end = size > 1 ? i + size : data.bytelength;
if (type === path[0]) {
if (path.length === 1) {
// this is the end of the path and we've found the box we were
// looking for
results.push(data.subarray(i + 8, end));
} else {
// recursively search for the next box along the path
subresults = findbox(data.subarray(i + 8, end), path.slice(1));
if (subresults.length) {
results = results.concat(subresults);
}
}
}
i = end;
} // we've finished searching all of data
return results;
};
var findbox_1 = findbox;
var tounsigned$1 = bin.tounsigned;
var getuint64$1 = numbers.getuint64;
var tfdt = function tfdt(data) {
var result = {
version: data[0],
flags: new uint8array(data.subarray(1, 4))
};
if (result.version === 1) {
result.basemediadecodetime = getuint64$1(data.subarray(4));
} else {
result.basemediadecodetime = tounsigned$1(data[4] << 24 | data[5] << 16 | data[6] << 8 | data[7]);
}
return result;
};
var parsetfdt = tfdt;
var parsesampleflags = function parsesampleflags(flags) {
return {
isleading: (flags[0] & 0x0c) >>> 2,
dependson: flags[0] & 0x03,
isdependedon: (flags[1] & 0xc0) >>> 6,
hasredundancy: (flags[1] & 0x30) >>> 4,
paddingvalue: (flags[1] & 0x0e) >>> 1,
isnonsyncsample: flags[1] & 0x01,
degradationpriority: flags[2] << 8 | flags[3]
};
};
var parsesampleflags_1 = parsesampleflags;
var trun = function trun(data) {
var result = {
version: data[0],
flags: new uint8array(data.subarray(1, 4)),
samples: []
},
view = new dataview(data.buffer, data.byteoffset, data.bytelength),
// flag interpretation
dataoffsetpresent = result.flags[2] & 0x01,
// compare with 2nd byte of 0x1
firstsampleflagspresent = result.flags[2] & 0x04,
// compare with 2nd byte of 0x4
sampledurationpresent = result.flags[1] & 0x01,
// compare with 2nd byte of 0x100
samplesizepresent = result.flags[1] & 0x02,
// compare with 2nd byte of 0x200
sampleflagspresent = result.flags[1] & 0x04,
// compare with 2nd byte of 0x400
samplecompositiontimeoffsetpresent = result.flags[1] & 0x08,
// compare with 2nd byte of 0x800
samplecount = view.getuint32(4),
offset = 8,
sample;
if (dataoffsetpresent) {
// 32 bit signed integer
result.dataoffset = view.getint32(offset);
offset += 4;
} // overrides the flags for the first sample only. the order of
// optional values will be: duration, size, compositiontimeoffset
if (firstsampleflagspresent && samplecount) {
sample = {
flags: parsesampleflags_1(data.subarray(offset, offset + 4))
};
offset += 4;
if (sampledurationpresent) {
sample.duration = view.getuint32(offset);
offset += 4;
}
if (samplesizepresent) {
sample.size = view.getuint32(offset);
offset += 4;
}
if (samplecompositiontimeoffsetpresent) {
if (result.version === 1) {
sample.compositiontimeoffset = view.getint32(offset);
} else {
sample.compositiontimeoffset = view.getuint32(offset);
}
offset += 4;
}
result.samples.push(sample);
samplecount--;
}
while (samplecount--) {
sample = {};
if (sampledurationpresent) {
sample.duration = view.getuint32(offset);
offset += 4;
}
if (samplesizepresent) {
sample.size = view.getuint32(offset);
offset += 4;
}
if (sampleflagspresent) {
sample.flags = parsesampleflags_1(data.subarray(offset, offset + 4));
offset += 4;
}
if (samplecompositiontimeoffsetpresent) {
if (result.version === 1) {
sample.compositiontimeoffset = view.getint32(offset);
} else {
sample.compositiontimeoffset = view.getuint32(offset);
}
offset += 4;
}
result.samples.push(sample);
}
return result;
};
var parsetrun = trun;
var tfhd = function tfhd(data) {
var view = new dataview(data.buffer, data.byteoffset, data.bytelength),
result = {
version: data[0],
flags: new uint8array(data.subarray(1, 4)),
trackid: view.getuint32(4)
},
basedataoffsetpresent = result.flags[2] & 0x01,
sampledescriptionindexpresent = result.flags[2] & 0x02,
defaultsampledurationpresent = result.flags[2] & 0x08,
defaultsamplesizepresent = result.flags[2] & 0x10,
defaultsampleflagspresent = result.flags[2] & 0x20,
durationisempty = result.flags[0] & 0x010000,
defaultbaseismoof = result.flags[0] & 0x020000,
i;
i = 8;
if (basedataoffsetpresent) {
i += 4; // truncate top 4 bytes
// fixme: should we read the full 64 bits?
result.basedataoffset = view.getuint32(12);
i += 4;
}
if (sampledescriptionindexpresent) {
result.sampledescriptionindex = view.getuint32(i);
i += 4;
}
if (defaultsampledurationpresent) {
result.defaultsampleduration = view.getuint32(i);
i += 4;
}
if (defaultsamplesizepresent) {
result.defaultsamplesize = view.getuint32(i);
i += 4;
}
if (defaultsampleflagspresent) {
result.defaultsampleflags = view.getuint32(i);
}
if (durationisempty) {
result.durationisempty = true;
}
if (!basedataoffsetpresent && defaultbaseismoof) {
result.basedataoffsetismoof = true;
}
return result;
};
var parsetfhd = tfhd;
var commonjsglobal = typeof globalthis !== 'undefined' ? globalthis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
var win;
if (typeof window !== "undefined") {
win = window;
} else if (typeof commonjsglobal !== "undefined") {
win = commonjsglobal;
} else if (typeof self !== "undefined") {
win = self;
} else {
win = {};
}
var window_1 = win;
var discardemulationpreventionbytes = captionpacketparser.discardemulationpreventionbytes;
var captionstream = captionstream.captionstream;
/**
* maps an offset in the mdat to a sample based on the the size of the samples.
* assumes that `parsesamples` has been called first.
*
* @param {number} offset - the offset into the mdat
* @param {object[]} samples - an array of samples, parsed using `parsesamples`
* @return {?object} the matching sample, or null if no match was found.
*
* @see iso-bmff-12/2015, section 8.8.8
**/
var maptosample = function maptosample(offset, samples) {
var approximateoffset = offset;
for (var i = 0; i < samples.length; i++) {
var sample = samples[i];
if (approximateoffset < sample.size) {
return sample;
}
approximateoffset -= sample.size;
}
return null;
};
/**
* finds sei nal units contained in a media data box.
* assumes that `parsesamples` has been called first.
*
* @param {uint8array} avcstream - the bytes of the mdat
* @param {object[]} samples - the samples parsed out by `parsesamples`
* @param {number} trackid - the trackid of this video track
* @return {object[]} seinals - the parsed sei nalus found.
* the contents of the seinal should match what is expected by
* captionstream.push (nalunittype, size, data, escapedrbsp, pts, dts)
*
* @see iso-bmff-12/2015, section 8.1.1
* @see rec. itu-t h.264, 7.3.2.3.1
**/
var findseinals = function findseinals(avcstream, samples, trackid) {
var avcview = new dataview(avcstream.buffer, avcstream.byteoffset, avcstream.bytelength),
result = {
logs: [],
seinals: []
},
seinal,
i,
length,
lastmatchedsample;
for (i = 0; i + 4 < avcstream.length; i += length) {
length = avcview.getuint32(i);
i += 4; // bail if this doesn't appear to be an h264 stream
if (length <= 0) {
continue;
}
switch (avcstream[i] & 0x1f) {
case 0x06:
var data = avcstream.subarray(i + 1, i + 1 + length);
var matchingsample = maptosample(i, samples);
seinal = {
nalunittype: 'sei_rbsp',
size: length,
data: data,
escapedrbsp: discardemulationpreventionbytes(data),
trackid: trackid
};
if (matchingsample) {
seinal.pts = matchingsample.pts;
seinal.dts = matchingsample.dts;
lastmatchedsample = matchingsample;
} else if (lastmatchedsample) {
// if a matching sample cannot be found, use the last
// sample's values as they should be as close as possible
seinal.pts = lastmatchedsample.pts;
seinal.dts = lastmatchedsample.dts;
} else {
result.logs.push({
level: 'warn',
message: 'we\'ve encountered a nal unit without data at ' + i + ' for trackid ' + trackid + '. see mux.js#223.'
});
break;
}
result.seinals.push(seinal);
break;
}
}
return result;
};
/**
* parses sample information out of track run boxes and calculates
* the absolute presentation and decode timestamps of each sample.
*
* @param {array} truns - the trun run boxes to be parsed
* @param {number|bigint} basemediadecodetime - base media decode time from tfdt
@see iso-bmff-12/2015, section 8.8.12
* @param {object} tfhd - the parsed track fragment header
* @see inspect.parsetfhd
* @return {object[]} the parsed samples
*
* @see iso-bmff-12/2015, section 8.8.8
**/
var parsesamples = function parsesamples(truns, basemediadecodetime, tfhd) {
var currentdts = basemediadecodetime;
var defaultsampleduration = tfhd.defaultsampleduration || 0;
var defaultsamplesize = tfhd.defaultsamplesize || 0;
var trackid = tfhd.trackid;
var allsamples = [];
truns.foreach(function (trun) {
// note: we currently do not parse the sample table as well
// as the trun. it's possible some sources will require this.
// moov > trak > mdia > minf > stbl
var trackrun = parsetrun(trun);
var samples = trackrun.samples;
samples.foreach(function (sample) {
if (sample.duration === undefined) {
sample.duration = defaultsampleduration;
}
if (sample.size === undefined) {
sample.size = defaultsamplesize;
}
sample.trackid = trackid;
sample.dts = currentdts;
if (sample.compositiontimeoffset === undefined) {
sample.compositiontimeoffset = 0;
}
if (typeof currentdts === 'bigint') {
sample.pts = currentdts + window_1.bigint(sample.compositiontimeoffset);
currentdts += window_1.bigint(sample.duration);
} else {
sample.pts = currentdts + sample.compositiontimeoffset;
currentdts += sample.duration;
}
});
allsamples = allsamples.concat(samples);
});
return allsamples;
};
/**
* parses out caption nals from an fmp4 segment's video tracks.
*
* @param {uint8array} segment - the bytes of a single segment
* @param {number} videotrackid - the trackid of a video track in the segment
* @return {object.} a mapping of video trackid to
* a list of seinals found in that track
**/
var parsecaptionnals = function parsecaptionnals(segment, videotrackid) {
// to get the samples
var trafs = findbox_1(segment, ['moof', 'traf']); // to get sei nal units
var mdats = findbox_1(segment, ['mdat']);
var captionnals = {};
var mdattrafpairs = []; // pair up each traf with a mdat as moofs and mdats are in pairs
mdats.foreach(function (mdat, index) {
var matchingtraf = trafs[index];
mdattrafpairs.push({
mdat: mdat,
traf: matchingtraf
});
});
mdattrafpairs.foreach(function (pair) {
var mdat = pair.mdat;
var traf = pair.traf;
var tfhd = findbox_1(traf, ['tfhd']); // exactly 1 tfhd per traf
var headerinfo = parsetfhd(tfhd[0]);
var trackid = headerinfo.trackid;
var tfdt = findbox_1(traf, ['tfdt']); // either 0 or 1 tfdt per traf
var basemediadecodetime = tfdt.length > 0 ? parsetfdt(tfdt[0]).basemediadecodetime : 0;
var truns = findbox_1(traf, ['trun']);
var samples;
var result; // only parse video data for the chosen video track
if (videotrackid === trackid && truns.length > 0) {
samples = parsesamples(truns, basemediadecodetime, headerinfo);
result = findseinals(mdat, samples, trackid);
if (!captionnals[trackid]) {
captionnals[trackid] = {
seinals: [],
logs: []
};
}
captionnals[trackid].seinals = captionnals[trackid].seinals.concat(result.seinals);
captionnals[trackid].logs = captionnals[trackid].logs.concat(result.logs);
}
});
return captionnals;
};
/**
* parses out inband captions from an mp4 container and returns
* caption objects that can be used by webvtt and the texttrack api.
* @see https://developer.mozilla.org/en-us/docs/web/api/vttcue
* @see https://developer.mozilla.org/en-us/docs/web/api/texttrack
* assumes that `probe.getvideotrackids` and `probe.timescale` have been called first
*
* @param {uint8array} segment - the fmp4 segment containing embedded captions
* @param {number} trackid - the id of the video track to parse
* @param {number} timescale - the timescale for the video track from the init segment
*
* @return {?object[]} parsedcaptions - a list of captions or null if no video tracks
* @return {number} parsedcaptions[].starttime - the time to show the caption in seconds
* @return {number} parsedcaptions[].endtime - the time to stop showing the caption in seconds
* @return {string} parsedcaptions[].text - the visible content of the caption
**/
var parseembeddedcaptions = function parseembeddedcaptions(segment, trackid, timescale) {
var captionnals; // the iso-bmff spec says that trackid can't be zero, but there's some broken content out there
if (trackid === null) {
return null;
}
captionnals = parsecaptionnals(segment, trackid);
var tracknals = captionnals[trackid] || {};
return {
seinals: tracknals.seinals,
logs: tracknals.logs,
timescale: timescale
};
};
/**
* converts sei nalus into captions that can be used by video.js
**/
var captionparser = function captionparser() {
var isinitialized = false;
var captionstream; // stores segments seen before trackid and timescale are set
var segmentcache; // stores video track id of the track being parsed
var trackid; // stores the timescale of the track being parsed
var timescale; // stores captions parsed so far
var parsedcaptions; // stores whether we are receiving partial data or not
var parsingpartial;
/**
* a method to indicate whether a captionparser has been initalized
* @returns {boolean}
**/
this.isinitialized = function () {
return isinitialized;
};
/**
* initializes the underlying captionstream, sei nal parsing
* and management, and caption collection
**/
this.init = function (options) {
captionstream = new captionstream();
isinitialized = true;
parsingpartial = options ? options.ispartial : false; // collect dispatched captions
captionstream.on('data', function (event) {
// convert to seconds in the source's timescale
event.starttime = event.startpts / timescale;
event.endtime = event.endpts / timescale;
parsedcaptions.captions.push(event);
parsedcaptions.captionstreams[event.stream] = true;
});
captionstream.on('log', function (log) {
parsedcaptions.logs.push(log);
});
};
/**
* determines if a new video track will be selected
* or if the timescale changed
* @return {boolean}
**/
this.isnewinit = function (videotrackids, timescales) {
if (videotrackids && videotrackids.length === 0 || timescales && typeof timescales === 'object' && object.keys(timescales).length === 0) {
return false;
}
return trackid !== videotrackids[0] || timescale !== timescales[trackid];
};
/**
* parses out sei captions and interacts with underlying
* captionstream to return dispatched captions
*
* @param {uint8array} segment - the fmp4 segment containing embedded captions
* @param {number[]} videotrackids - a list of video tracks found in the init segment
* @param {object.} timescales - the timescales found in the init segment
* @see parseembeddedcaptions
* @see m2ts/caption-stream.js
**/
this.parse = function (segment, videotrackids, timescales) {
var parseddata;
if (!this.isinitialized()) {
return null; // this is not likely to be a video segment
} else if (!videotrackids || !timescales) {
return null;
} else if (this.isnewinit(videotrackids, timescales)) {
// use the first video track only as there is no
// mechanism to switch to other video tracks
trackid = videotrackids[0];
timescale = timescales[trackid]; // if an init segment has not been seen yet, hold onto segment
// data until we have one.
// the iso-bmff spec says that trackid can't be zero, but there's some broken content out there
} else if (trackid === null || !timescale) {
segmentcache.push(segment);
return null;
} // now that a timescale and trackid is set, parse cached segments
while (segmentcache.length > 0) {
var cachedsegment = segmentcache.shift();
this.parse(cachedsegment, videotrackids, timescales);
}
parseddata = parseembeddedcaptions(segment, trackid, timescale);
if (parseddata && parseddata.logs) {
parsedcaptions.logs = parsedcaptions.logs.concat(parseddata.logs);
}
if (parseddata === null || !parseddata.seinals) {
if (parsedcaptions.logs.length) {
return {
logs: parsedcaptions.logs,
captions: [],
captionstreams: []
};
}
return null;
}
this.pushnals(parseddata.seinals); // force the parsed captions to be dispatched
this.flushstream();
return parsedcaptions;
};
/**
* pushes sei nalus onto captionstream
* @param {object[]} nals - a list of sei nals parsed using `parsecaptionnals`
* assumes that `parsecaptionnals` has been called first
* @see m2ts/caption-stream.js
**/
this.pushnals = function (nals) {
if (!this.isinitialized() || !nals || nals.length === 0) {
return null;
}
nals.foreach(function (nal) {
captionstream.push(nal);
});
};
/**
* flushes underlying captionstream to dispatch processed, displayable captions
* @see m2ts/caption-stream.js
**/
this.flushstream = function () {
if (!this.isinitialized()) {
return null;
}
if (!parsingpartial) {
captionstream.flush();
} else {
captionstream.partialflush();
}
};
/**
* reset caption buckets for new data
**/
this.clearparsedcaptions = function () {
parsedcaptions.captions = [];
parsedcaptions.captionstreams = {};
parsedcaptions.logs = [];
};
/**
* resets underlying captionstream
* @see m2ts/caption-stream.js
**/
this.resetcaptionstream = function () {
if (!this.isinitialized()) {
return null;
}
captionstream.reset();
};
/**
* convenience method to clear all captions flushed from the
* captionstream and still being parsed
* @see m2ts/caption-stream.js
**/
this.clearallcaptions = function () {
this.clearparsedcaptions();
this.resetcaptionstream();
};
/**
* reset caption parser
**/
this.reset = function () {
segmentcache = [];
trackid = null;
timescale = null;
if (!parsedcaptions) {
parsedcaptions = {
captions: [],
// cc1, cc2, cc3, cc4
captionstreams: {},
logs: []
};
} else {
this.clearparsedcaptions();
}
this.resetcaptionstream();
};
this.reset();
};
var captionparser = captionparser;
var tounsigned = bin.tounsigned;
var tohexstring = bin.tohexstring;
var getuint64 = numbers.getuint64;
var timescale, starttime, compositionstarttime, getvideotrackids, gettracks, gettimescalefrommediaheader;
/**
* parses an mp4 initialization segment and extracts the timescale
* values for any declared tracks. timescale values indicate the
* number of clock ticks per second to assume for time-based values
* elsewhere in the mp4.
*
* to determine the start time of an mp4, you need two pieces of
* information: the timescale unit and the earliest base media decode
* time. multiple timescales can be specified within an mp4 but the
* base media decode time is always expressed in the timescale from
* the media header box for the track:
* ```
* moov > trak > mdia > mdhd.timescale
* ```
* @param init {uint8array} the bytes of the init segment
* @return {object} a hash of track ids to timescale values or null if
* the init segment is malformed.
*/
timescale = function timescale(init) {
var result = {},
traks = findbox_1(init, ['moov', 'trak']); // mdhd timescale
return traks.reduce(function (result, trak) {
var tkhd, version, index, id, mdhd;
tkhd = findbox_1(trak, ['tkhd'])[0];
if (!tkhd) {
return null;
}
version = tkhd[0];
index = version === 0 ? 12 : 20;
id = tounsigned(tkhd[index] << 24 | tkhd[index + 1] << 16 | tkhd[index + 2] << 8 | tkhd[index + 3]);
mdhd = findbox_1(trak, ['mdia', 'mdhd'])[0];
if (!mdhd) {
return null;
}
version = mdhd[0];
index = version === 0 ? 12 : 20;
result[id] = tounsigned(mdhd[index] << 24 | mdhd[index + 1] << 16 | mdhd[index + 2] << 8 | mdhd[index + 3]);
return result;
}, result);
};
/**
* determine the base media decode start time, in seconds, for an mp4
* fragment. if multiple fragments are specified, the earliest time is
* returned.
*
* the base media decode time can be parsed from track fragment
* metadata:
* ```
* moof > traf > tfdt.basemediadecodetime
* ```
* it requires the timescale value from the mdhd to interpret.
*
* @param timescale {object} a hash of track ids to timescale values.
* @return {number} the earliest base media decode start time for the
* fragment, in seconds
*/
starttime = function starttime(timescale, fragment) {
var trafs; // we need info from two childrend of each track fragment box
trafs = findbox_1(fragment, ['moof', 'traf']); // determine the start times for each track
var lowesttime = trafs.reduce(function (acc, traf) {
var tfhd = findbox_1(traf, ['tfhd'])[0]; // get the track id from the tfhd
var id = tounsigned(tfhd[4] << 24 | tfhd[5] << 16 | tfhd[6] << 8 | tfhd[7]); // assume a 90khz clock if no timescale was specified
var scale = timescale[id] || 90e3; // get the base media decode time from the tfdt
var tfdt = findbox_1(traf, ['tfdt'])[0];
var dv = new dataview(tfdt.buffer, tfdt.byteoffset, tfdt.bytelength);
var basetime; // version 1 is 64 bit
if (tfdt[0] === 1) {
basetime = getuint64(tfdt.subarray(4, 12));
} else {
basetime = dv.getuint32(4);
} // convert base time to seconds if it is a valid number.
var seconds;
if (typeof basetime === 'bigint') {
seconds = basetime / window_1.bigint(scale);
} else if (typeof basetime === 'number' && !isnan(basetime)) {
seconds = basetime / scale;
}
if (seconds < number.max_safe_integer) {
seconds = number(seconds);
}
if (seconds < acc) {
acc = seconds;
}
return acc;
}, infinity);
return typeof lowesttime === 'bigint' || isfinite(lowesttime) ? lowesttime : 0;
};
/**
* determine the composition start, in seconds, for an mp4
* fragment.
*
* the composition start time of a fragment can be calculated using the base
* media decode time, composition time offset, and timescale, as follows:
*
* compositionstarttime = (basemediadecodetime + compositiontimeoffset) / timescale
*
* all of the aforementioned information is contained within a media fragment's
* `traf` box, except for timescale info, which comes from the initialization
* segment, so a track id (also contained within a `traf`) is also necessary to
* associate it with a timescale
*
*
* @param timescales {object} - a hash of track ids to timescale values.
* @param fragment {unit8array} - the bytes of a media segment
* @return {number} the composition start time for the fragment, in seconds
**/
compositionstarttime = function compositionstarttime(timescales, fragment) {
var trafboxes = findbox_1(fragment, ['moof', 'traf']);
var basemediadecodetime = 0;
var compositiontimeoffset = 0;
var trackid;
if (trafboxes && trafboxes.length) {
// the spec states that track run samples contained within a `traf` box are contiguous, but
// it does not explicitly state whether the `traf` boxes themselves are contiguous.
// we will assume that they are, so we only need the first to calculate start time.
var tfhd = findbox_1(trafboxes[0], ['tfhd'])[0];
var trun = findbox_1(trafboxes[0], ['trun'])[0];
var tfdt = findbox_1(trafboxes[0], ['tfdt'])[0];
if (tfhd) {
var parsedtfhd = parsetfhd(tfhd);
trackid = parsedtfhd.trackid;
}
if (tfdt) {
var parsedtfdt = parsetfdt(tfdt);
basemediadecodetime = parsedtfdt.basemediadecodetime;
}
if (trun) {
var parsedtrun = parsetrun(trun);
if (parsedtrun.samples && parsedtrun.samples.length) {
compositiontimeoffset = parsedtrun.samples[0].compositiontimeoffset || 0;
}
}
} // get timescale for this specific track. assume a 90khz clock if no timescale was
// specified.
var timescale = timescales[trackid] || 90e3; // return the composition start time, in seconds
if (typeof basemediadecodetime === 'bigint') {
compositiontimeoffset = window_1.bigint(compositiontimeoffset);
timescale = window_1.bigint(timescale);
}
var result = (basemediadecodetime + compositiontimeoffset) / timescale;
if (typeof result === 'bigint' && result < number.max_safe_integer) {
result = number(result);
}
return result;
};
/**
* find the trackids of the video tracks in this source.
* found by parsing the handler reference and track header boxes:
* moov > trak > mdia > hdlr
* moov > trak > tkhd
*
* @param {uint8array} init - the bytes of the init segment for this source
* @return {number[]} a list of trackids
*
* @see iso-bmff-12/2015, section 8.4.3
**/
getvideotrackids = function getvideotrackids(init) {
var traks = findbox_1(init, ['moov', 'trak']);
var videotrackids = [];
traks.foreach(function (trak) {
var hdlrs = findbox_1(trak, ['mdia', 'hdlr']);
var tkhds = findbox_1(trak, ['tkhd']);
hdlrs.foreach(function (hdlr, index) {
var handlertype = parsetype_1(hdlr.subarray(8, 12));
var tkhd = tkhds[index];
var view;
var version;
var trackid;
if (handlertype === 'vide') {
view = new dataview(tkhd.buffer, tkhd.byteoffset, tkhd.bytelength);
version = view.getuint8(0);
trackid = version === 0 ? view.getuint32(12) : view.getuint32(20);
videotrackids.push(trackid);
}
});
});
return videotrackids;
};
gettimescalefrommediaheader = function gettimescalefrommediaheader(mdhd) {
// mdhd is a fullbox, meaning it will have its own version as the first byte
var version = mdhd[0];
var index = version === 0 ? 12 : 20;
return tounsigned(mdhd[index] << 24 | mdhd[index + 1] << 16 | mdhd[index + 2] << 8 | mdhd[index + 3]);
};
/**
* get all the video, audio, and hint tracks from a non fragmented
* mp4 segment
*/
gettracks = function gettracks(init) {
var traks = findbox_1(init, ['moov', 'trak']);
var tracks = [];
traks.foreach(function (trak) {
var track = {};
var tkhd = findbox_1(trak, ['tkhd'])[0];
var view, tkhdversion; // id
if (tkhd) {
view = new dataview(tkhd.buffer, tkhd.byteoffset, tkhd.bytelength);
tkhdversion = view.getuint8(0);
track.id = tkhdversion === 0 ? view.getuint32(12) : view.getuint32(20);
}
var hdlr = findbox_1(trak, ['mdia', 'hdlr'])[0]; // type
if (hdlr) {
var type = parsetype_1(hdlr.subarray(8, 12));
if (type === 'vide') {
track.type = 'video';
} else if (type === 'soun') {
track.type = 'audio';
} else {
track.type = type;
}
} // codec
var stsd = findbox_1(trak, ['mdia', 'minf', 'stbl', 'stsd'])[0];
if (stsd) {
var sampledescriptions = stsd.subarray(8); // gives the codec type string
track.codec = parsetype_1(sampledescriptions.subarray(4, 8));
var codecbox = findbox_1(sampledescriptions, [track.codec])[0];
var codecconfig, codecconfigtype;
if (codecbox) {
// https://tools.ietf.org/html/rfc6381#section-3.3
if (/^[asm]vc[1-9]$/i.test(track.codec)) {
// we don't need anything but the "config" parameter of the
// avc1 codecbox
codecconfig = codecbox.subarray(78);
codecconfigtype = parsetype_1(codecconfig.subarray(4, 8));
if (codecconfigtype === 'avcc' && codecconfig.length > 11) {
track.codec += '.'; // left padded with zeroes for single digit hex
// profile idc
track.codec += tohexstring(codecconfig[9]); // the byte containing the constraint_set flags
track.codec += tohexstring(codecconfig[10]); // level idc
track.codec += tohexstring(codecconfig[11]);
} else {
// todo: show a warning that we couldn't parse the codec
// and are using the default
track.codec = 'avc1.4d400d';
}
} else if (/^mp4[a,v]$/i.test(track.codec)) {
// we do not need anything but the streamdescriptor of the mp4a codecbox
codecconfig = codecbox.subarray(28);
codecconfigtype = parsetype_1(codecconfig.subarray(4, 8));
if (codecconfigtype === 'esds' && codecconfig.length > 20 && codecconfig[19] !== 0) {
track.codec += '.' + tohexstring(codecconfig[19]); // this value is only a single digit
track.codec += '.' + tohexstring(codecconfig[20] >>> 2 & 0x3f).replace(/^0/, '');
} else {
// todo: show a warning that we couldn't parse the codec
// and are using the default
track.codec = 'mp4a.40.2';
}
} else {
// flac, opus, etc
track.codec = track.codec.tolowercase();
}
}
}
var mdhd = findbox_1(trak, ['mdia', 'mdhd'])[0];
if (mdhd) {
track.timescale = gettimescalefrommediaheader(mdhd);
}
tracks.push(track);
});
return tracks;
};
var probe$2 = {
// export mp4 inspector's findbox and parsetype for backwards compatibility
findbox: findbox_1,
parsetype: parsetype_1,
timescale: timescale,
starttime: starttime,
compositionstarttime: compositionstarttime,
videotrackids: getvideotrackids,
tracks: gettracks,
gettimescalefrommediaheader: gettimescalefrommediaheader
};
var parsepid = function parsepid(packet) {
var pid = packet[1] & 0x1f;
pid <<= 8;
pid |= packet[2];
return pid;
};
var parsepayloadunitstartindicator = function parsepayloadunitstartindicator(packet) {
return !!(packet[1] & 0x40);
};
var parseadaptionfield = function parseadaptionfield(packet) {
var offset = 0; // if an adaption field is present, its length is specified by the
// fifth byte of the ts packet header. the adaptation field is
// used to add stuffing to pes packets that don't fill a complete
// ts packet, and to specify some forms of timing and control data
// that we do not currently use.
if ((packet[3] & 0x30) >>> 4 > 0x01) {
offset += packet[4] + 1;
}
return offset;
};
var parsetype = function parsetype(packet, pmtpid) {
var pid = parsepid(packet);
if (pid === 0) {
return 'pat';
} else if (pid === pmtpid) {
return 'pmt';
} else if (pmtpid) {
return 'pes';
}
return null;
};
var parsepat = function parsepat(packet) {
var pusi = parsepayloadunitstartindicator(packet);
var offset = 4 + parseadaptionfield(packet);
if (pusi) {
offset += packet[offset] + 1;
}
return (packet[offset + 10] & 0x1f) << 8 | packet[offset + 11];
};
var parsepmt = function parsepmt(packet) {
var programmaptable = {};
var pusi = parsepayloadunitstartindicator(packet);
var payloadoffset = 4 + parseadaptionfield(packet);
if (pusi) {
payloadoffset += packet[payloadoffset] + 1;
} // pmts can be sent ahead of the time when they should actually
// take effect. we don't believe this should ever be the case
// for hls but we'll ignore "forward" pmt declarations if we see
// them. future pmt declarations have the current_next_indicator
// set to zero.
if (!(packet[payloadoffset + 5] & 0x01)) {
return;
}
var sectionlength, tableend, programinfolength; // the mapping table ends at the end of the current section
sectionlength = (packet[payloadoffset + 1] & 0x0f) << 8 | packet[payloadoffset + 2];
tableend = 3 + sectionlength - 4; // to determine where the table is, we have to figure out how
// long the program info descriptors are
programinfolength = (packet[payloadoffset + 10] & 0x0f) << 8 | packet[payloadoffset + 11]; // advance the offset to the first entry in the mapping table
var offset = 12 + programinfolength;
while (offset < tableend) {
var i = payloadoffset + offset; // add an entry that maps the elementary_pid to the stream_type
programmaptable[(packet[i + 1] & 0x1f) << 8 | packet[i + 2]] = packet[i]; // move to the next table entry
// skip past the elementary stream descriptors, if present
offset += ((packet[i + 3] & 0x0f) << 8 | packet[i + 4]) + 5;
}
return programmaptable;
};
var parsepestype = function parsepestype(packet, programmaptable) {
var pid = parsepid(packet);
var type = programmaptable[pid];
switch (type) {
case streamtypes.h264_stream_type:
return 'video';
case streamtypes.adts_stream_type:
return 'audio';
case streamtypes.metadata_stream_type:
return 'timed-metadata';
default:
return null;
}
};
var parsepestime = function parsepestime(packet) {
var pusi = parsepayloadunitstartindicator(packet);
if (!pusi) {
return null;
}
var offset = 4 + parseadaptionfield(packet);
if (offset >= packet.bytelength) {
// from the h 222.0 mpeg-ts spec
// "for transport stream packets carrying pes packets, stuffing is needed when there
// is insufficient pes packet data to completely fill the transport stream packet
// payload bytes. stuffing is accomplished by defining an adaptation field longer than
// the sum of the lengths of the data elements in it, so that the payload bytes
// remaining after the adaptation field exactly accommodates the available pes packet
// data."
//
// if the offset is >= the length of the packet, then the packet contains no data
// and instead is just adaption field stuffing bytes
return null;
}
var pes = null;
var ptsdtsflags; // pes packets may be annotated with a pts value, or a pts value
// and a dts value. determine what combination of values is
// available to work with.
ptsdtsflags = packet[offset + 7]; // pts and dts are normally stored as a 33-bit number. javascript
// performs all bitwise operations on 32-bit integers but javascript
// supports a much greater range (52-bits) of integer using standard
// mathematical operations.
// we construct a 31-bit value using bitwise operators over the 31
// most significant bits and then multiply by 4 (equal to a left-shift
// of 2) before we add the final 2 least significant bits of the
// timestamp (equal to an or.)
if (ptsdtsflags & 0xc0) {
pes = {}; // the pts and dts are not written out directly. for information
// on how they are encoded, see
// http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
pes.pts = (packet[offset + 9] & 0x0e) << 27 | (packet[offset + 10] & 0xff) << 20 | (packet[offset + 11] & 0xfe) << 12 | (packet[offset + 12] & 0xff) << 5 | (packet[offset + 13] & 0xfe) >>> 3;
pes.pts *= 4; // left shift by 2
pes.pts += (packet[offset + 13] & 0x06) >>> 1; // or by the two lsbs
pes.dts = pes.pts;
if (ptsdtsflags & 0x40) {
pes.dts = (packet[offset + 14] & 0x0e) << 27 | (packet[offset + 15] & 0xff) << 20 | (packet[offset + 16] & 0xfe) << 12 | (packet[offset + 17] & 0xff) << 5 | (packet[offset + 18] & 0xfe) >>> 3;
pes.dts *= 4; // left shift by 2
pes.dts += (packet[offset + 18] & 0x06) >>> 1; // or by the two lsbs
}
}
return pes;
};
var parsenalunittype = function parsenalunittype(type) {
switch (type) {
case 0x05:
return 'slice_layer_without_partitioning_rbsp_idr';
case 0x06:
return 'sei_rbsp';
case 0x07:
return 'seq_parameter_set_rbsp';
case 0x08:
return 'pic_parameter_set_rbsp';
case 0x09:
return 'access_unit_delimiter_rbsp';
default:
return null;
}
};
var videopacketcontainskeyframe = function videopacketcontainskeyframe(packet) {
var offset = 4 + parseadaptionfield(packet);
var framebuffer = packet.subarray(offset);
var framei = 0;
var framesyncpoint = 0;
var foundkeyframe = false;
var naltype; // advance the sync point to a nal start, if necessary
for (; framesyncpoint < framebuffer.bytelength - 3; framesyncpoint++) {
if (framebuffer[framesyncpoint + 2] === 1) {
// the sync point is properly aligned
framei = framesyncpoint + 5;
break;
}
}
while (framei < framebuffer.bytelength) {
// look at the current byte to determine if we've hit the end of
// a nal unit boundary
switch (framebuffer[framei]) {
case 0:
// skip past non-sync sequences
if (framebuffer[framei - 1] !== 0) {
framei += 2;
break;
} else if (framebuffer[framei - 2] !== 0) {
framei++;
break;
}
if (framesyncpoint + 3 !== framei - 2) {
naltype = parsenalunittype(framebuffer[framesyncpoint + 3] & 0x1f);
if (naltype === 'slice_layer_without_partitioning_rbsp_idr') {
foundkeyframe = true;
}
} // drop trailing zeroes
do {
framei++;
} while (framebuffer[framei] !== 1 && framei < framebuffer.length);
framesyncpoint = framei - 2;
framei += 3;
break;
case 1:
// skip past non-sync sequences
if (framebuffer[framei - 1] !== 0 || framebuffer[framei - 2] !== 0) {
framei += 3;
break;
}
naltype = parsenalunittype(framebuffer[framesyncpoint + 3] & 0x1f);
if (naltype === 'slice_layer_without_partitioning_rbsp_idr') {
foundkeyframe = true;
}
framesyncpoint = framei - 2;
framei += 3;
break;
default:
// the current byte isn't a one or zero, so it cannot be part
// of a sync sequence
framei += 3;
break;
}
}
framebuffer = framebuffer.subarray(framesyncpoint);
framei -= framesyncpoint;
framesyncpoint = 0; // parse the final nal
if (framebuffer && framebuffer.bytelength > 3) {
naltype = parsenalunittype(framebuffer[framesyncpoint + 3] & 0x1f);
if (naltype === 'slice_layer_without_partitioning_rbsp_idr') {
foundkeyframe = true;
}
}
return foundkeyframe;
};
var probe$1 = {
parsetype: parsetype,
parsepat: parsepat,
parsepmt: parsepmt,
parsepayloadunitstartindicator: parsepayloadunitstartindicator,
parsepestype: parsepestype,
parsepestime: parsepestime,
videopacketcontainskeyframe: videopacketcontainskeyframe
};
var handlerollover = timestamprolloverstream.handlerollover;
var probe = {};
probe.ts = probe$1;
probe.aac = utils;
var one_second_in_ts = clock.one_second_in_ts;
var mp2t_packet_length = 188,
// bytes
sync_byte = 0x47;
/**
* walks through segment data looking for pat and pmt packets to parse out
* program map table information
*/
var parsepsi_ = function parsepsi_(bytes, pmt) {
var startindex = 0,
endindex = mp2t_packet_length,
packet,
type;
while (endindex < bytes.bytelength) {
// look for a pair of start and end sync bytes in the data..
if (bytes[startindex] === sync_byte && bytes[endindex] === sync_byte) {
// we found a packet
packet = bytes.subarray(startindex, endindex);
type = probe.ts.parsetype(packet, pmt.pid);
switch (type) {
case 'pat':
pmt.pid = probe.ts.parsepat(packet);
break;
case 'pmt':
var table = probe.ts.parsepmt(packet);
pmt.table = pmt.table || {};
object.keys(table).foreach(function (key) {
pmt.table[key] = table[key];
});
break;
}
startindex += mp2t_packet_length;
endindex += mp2t_packet_length;
continue;
} // if we get here, we have somehow become de-synchronized and we need to step
// forward one byte at a time until we find a pair of sync bytes that denote
// a packet
startindex++;
endindex++;
}
};
/**
* walks through the segment data from the start and end to get timing information
* for the first and last audio pes packets
*/
var parseaudiopes_ = function parseaudiopes_(bytes, pmt, result) {
var startindex = 0,
endindex = mp2t_packet_length,
packet,
type,
pestype,
pusi,
parsed;
var endloop = false; // start walking from start of segment to get first audio packet
while (endindex <= bytes.bytelength) {
// look for a pair of start and end sync bytes in the data..
if (bytes[startindex] === sync_byte && (bytes[endindex] === sync_byte || endindex === bytes.bytelength)) {
// we found a packet
packet = bytes.subarray(startindex, endindex);
type = probe.ts.parsetype(packet, pmt.pid);
switch (type) {
case 'pes':
pestype = probe.ts.parsepestype(packet, pmt.table);
pusi = probe.ts.parsepayloadunitstartindicator(packet);
if (pestype === 'audio' && pusi) {
parsed = probe.ts.parsepestime(packet);
if (parsed) {
parsed.type = 'audio';
result.audio.push(parsed);
endloop = true;
}
}
break;
}
if (endloop) {
break;
}
startindex += mp2t_packet_length;
endindex += mp2t_packet_length;
continue;
} // if we get here, we have somehow become de-synchronized and we need to step
// forward one byte at a time until we find a pair of sync bytes that denote
// a packet
startindex++;
endindex++;
} // start walking from end of segment to get last audio packet
endindex = bytes.bytelength;
startindex = endindex - mp2t_packet_length;
endloop = false;
while (startindex >= 0) {
// look for a pair of start and end sync bytes in the data..
if (bytes[startindex] === sync_byte && (bytes[endindex] === sync_byte || endindex === bytes.bytelength)) {
// we found a packet
packet = bytes.subarray(startindex, endindex);
type = probe.ts.parsetype(packet, pmt.pid);
switch (type) {
case 'pes':
pestype = probe.ts.parsepestype(packet, pmt.table);
pusi = probe.ts.parsepayloadunitstartindicator(packet);
if (pestype === 'audio' && pusi) {
parsed = probe.ts.parsepestime(packet);
if (parsed) {
parsed.type = 'audio';
result.audio.push(parsed);
endloop = true;
}
}
break;
}
if (endloop) {
break;
}
startindex -= mp2t_packet_length;
endindex -= mp2t_packet_length;
continue;
} // if we get here, we have somehow become de-synchronized and we need to step
// forward one byte at a time until we find a pair of sync bytes that denote
// a packet
startindex--;
endindex--;
}
};
/**
* walks through the segment data from the start and end to get timing information
* for the first and last video pes packets as well as timing information for the first
* key frame.
*/
var parsevideopes_ = function parsevideopes_(bytes, pmt, result) {
var startindex = 0,
endindex = mp2t_packet_length,
packet,
type,
pestype,
pusi,
parsed,
frame,
i,
pes;
var endloop = false;
var currentframe = {
data: [],
size: 0
}; // start walking from start of segment to get first video packet
while (endindex < bytes.bytelength) {
// look for a pair of start and end sync bytes in the data..
if (bytes[startindex] === sync_byte && bytes[endindex] === sync_byte) {
// we found a packet
packet = bytes.subarray(startindex, endindex);
type = probe.ts.parsetype(packet, pmt.pid);
switch (type) {
case 'pes':
pestype = probe.ts.parsepestype(packet, pmt.table);
pusi = probe.ts.parsepayloadunitstartindicator(packet);
if (pestype === 'video') {
if (pusi && !endloop) {
parsed = probe.ts.parsepestime(packet);
if (parsed) {
parsed.type = 'video';
result.video.push(parsed);
endloop = true;
}
}
if (!result.firstkeyframe) {
if (pusi) {
if (currentframe.size !== 0) {
frame = new uint8array(currentframe.size);
i = 0;
while (currentframe.data.length) {
pes = currentframe.data.shift();
frame.set(pes, i);
i += pes.bytelength;
}
if (probe.ts.videopacketcontainskeyframe(frame)) {
var firstkeyframe = probe.ts.parsepestime(frame); // pts/dts may not be available. simply *not* setting
// the keyframe seems to work fine with hls playback
// and definitely preferable to a crash with typeerror...
if (firstkeyframe) {
result.firstkeyframe = firstkeyframe;
result.firstkeyframe.type = 'video';
} else {
// eslint-disable-next-line
console.warn('failed to extract pts/dts from pes at first keyframe. ' + 'this could be an unusual ts segment, or else mux.js did not ' + 'parse your ts segment correctly. if you know your ts ' + 'segments do contain pts/dts on keyframes please file a bug ' + 'report! you can try ffprobe to double check for yourself.');
}
}
currentframe.size = 0;
}
}
currentframe.data.push(packet);
currentframe.size += packet.bytelength;
}
}
break;
}
if (endloop && result.firstkeyframe) {
break;
}
startindex += mp2t_packet_length;
endindex += mp2t_packet_length;
continue;
} // if we get here, we have somehow become de-synchronized and we need to step
// forward one byte at a time until we find a pair of sync bytes that denote
// a packet
startindex++;
endindex++;
} // start walking from end of segment to get last video packet
endindex = bytes.bytelength;
startindex = endindex - mp2t_packet_length;
endloop = false;
while (startindex >= 0) {
// look for a pair of start and end sync bytes in the data..
if (bytes[startindex] === sync_byte && bytes[endindex] === sync_byte) {
// we found a packet
packet = bytes.subarray(startindex, endindex);
type = probe.ts.parsetype(packet, pmt.pid);
switch (type) {
case 'pes':
pestype = probe.ts.parsepestype(packet, pmt.table);
pusi = probe.ts.parsepayloadunitstartindicator(packet);
if (pestype === 'video' && pusi) {
parsed = probe.ts.parsepestime(packet);
if (parsed) {
parsed.type = 'video';
result.video.push(parsed);
endloop = true;
}
}
break;
}
if (endloop) {
break;
}
startindex -= mp2t_packet_length;
endindex -= mp2t_packet_length;
continue;
} // if we get here, we have somehow become de-synchronized and we need to step
// forward one byte at a time until we find a pair of sync bytes that denote
// a packet
startindex--;
endindex--;
}
};
/**
* adjusts the timestamp information for the segment to account for
* rollover and convert to seconds based on pes packet timescale (90khz clock)
*/
var adjusttimestamp_ = function adjusttimestamp_(segmentinfo, basetimestamp) {
if (segmentinfo.audio && segmentinfo.audio.length) {
var audiobasetimestamp = basetimestamp;
if (typeof audiobasetimestamp === 'undefined' || isnan(audiobasetimestamp)) {
audiobasetimestamp = segmentinfo.audio[0].dts;
}
segmentinfo.audio.foreach(function (info) {
info.dts = handlerollover(info.dts, audiobasetimestamp);
info.pts = handlerollover(info.pts, audiobasetimestamp); // time in seconds
info.dtstime = info.dts / one_second_in_ts;
info.ptstime = info.pts / one_second_in_ts;
});
}
if (segmentinfo.video && segmentinfo.video.length) {
var videobasetimestamp = basetimestamp;
if (typeof videobasetimestamp === 'undefined' || isnan(videobasetimestamp)) {
videobasetimestamp = segmentinfo.video[0].dts;
}
segmentinfo.video.foreach(function (info) {
info.dts = handlerollover(info.dts, videobasetimestamp);
info.pts = handlerollover(info.pts, videobasetimestamp); // time in seconds
info.dtstime = info.dts / one_second_in_ts;
info.ptstime = info.pts / one_second_in_ts;
});
if (segmentinfo.firstkeyframe) {
var frame = segmentinfo.firstkeyframe;
frame.dts = handlerollover(frame.dts, videobasetimestamp);
frame.pts = handlerollover(frame.pts, videobasetimestamp); // time in seconds
frame.dtstime = frame.dts / one_second_in_ts;
frame.ptstime = frame.pts / one_second_in_ts;
}
}
};
/**
* inspects the aac data stream for start and end time information
*/
var inspectaac_ = function inspectaac_(bytes) {
var endloop = false,
audiocount = 0,
samplerate = null,
timestamp = null,
framesize = 0,
byteindex = 0,
packet;
while (bytes.length - byteindex >= 3) {
var type = probe.aac.parsetype(bytes, byteindex);
switch (type) {
case 'timed-metadata':
// exit early because we don't have enough to parse
// the id3 tag header
if (bytes.length - byteindex < 10) {
endloop = true;
break;
}
framesize = probe.aac.parseid3tagsize(bytes, byteindex); // exit early if we don't have enough in the buffer
// to emit a full packet
if (framesize > bytes.length) {
endloop = true;
break;
}
if (timestamp === null) {
packet = bytes.subarray(byteindex, byteindex + framesize);
timestamp = probe.aac.parseaactimestamp(packet);
}
byteindex += framesize;
break;
case 'audio':
// exit early because we don't have enough to parse
// the adts frame header
if (bytes.length - byteindex < 7) {
endloop = true;
break;
}
framesize = probe.aac.parseadtssize(bytes, byteindex); // exit early if we don't have enough in the buffer
// to emit a full packet
if (framesize > bytes.length) {
endloop = true;
break;
}
if (samplerate === null) {
packet = bytes.subarray(byteindex, byteindex + framesize);
samplerate = probe.aac.parsesamplerate(packet);
}
audiocount++;
byteindex += framesize;
break;
default:
byteindex++;
break;
}
if (endloop) {
return null;
}
}
if (samplerate === null || timestamp === null) {
return null;
}
var audiotimescale = one_second_in_ts / samplerate;
var result = {
audio: [{
type: 'audio',
dts: timestamp,
pts: timestamp
}, {
type: 'audio',
dts: timestamp + audiocount * 1024 * audiotimescale,
pts: timestamp + audiocount * 1024 * audiotimescale
}]
};
return result;
};
/**
* inspects the transport stream segment data for start and end time information
* of the audio and video tracks (when present) as well as the first key frame's
* start time.
*/
var inspectts_ = function inspectts_(bytes) {
var pmt = {
pid: null,
table: null
};
var result = {};
parsepsi_(bytes, pmt);
for (var pid in pmt.table) {
if (pmt.table.hasownproperty(pid)) {
var type = pmt.table[pid];
switch (type) {
case streamtypes.h264_stream_type:
result.video = [];
parsevideopes_(bytes, pmt, result);
if (result.video.length === 0) {
delete result.video;
}
break;
case streamtypes.adts_stream_type:
result.audio = [];
parseaudiopes_(bytes, pmt, result);
if (result.audio.length === 0) {
delete result.audio;
}
break;
}
}
}
return result;
};
/**
* inspects segment byte data and returns an object with start and end timing information
*
* @param {uint8array} bytes the segment byte data
* @param {number} basetimestamp relative reference timestamp used when adjusting frame
* timestamps for rollover. this value must be in 90khz clock.
* @return {object} object containing start and end frame timing info of segment.
*/
var inspect = function inspect(bytes, basetimestamp) {
var isaacdata = probe.aac.islikelyaacdata(bytes);
var result;
if (isaacdata) {
result = inspectaac_(bytes);
} else {
result = inspectts_(bytes);
}
if (!result || !result.audio && !result.video) {
return null;
}
adjusttimestamp_(result, basetimestamp);
return result;
};
var tsinspector = {
inspect: inspect,
parseaudiopes_: parseaudiopes_
};
/* global self */
/**
* re-emits transmuxer events by converting them into messages to the
* world outside the worker.
*
* @param {object} transmuxer the transmuxer to wire events on
* @private
*/
var wiretransmuxerevents = function wiretransmuxerevents(self, transmuxer) {
transmuxer.on('data', function (segment) {
// transfer ownership of the underlying arraybuffer
// instead of doing a copy to save memory
// arraybuffers are transferable but generic typedarrays are not
// @link https://developer.mozilla.org/en-us/docs/web/api/web_workers_api/using_web_workers#passing_data_by_transferring_ownership_(transferable_objects)
var initarray = segment.initsegment;
segment.initsegment = {
data: initarray.buffer,
byteoffset: initarray.byteoffset,
bytelength: initarray.bytelength
};
var typedarray = segment.data;
segment.data = typedarray.buffer;
self.postmessage({
action: 'data',
segment: segment,
byteoffset: typedarray.byteoffset,
bytelength: typedarray.bytelength
}, [segment.data]);
});
transmuxer.on('done', function (data) {
self.postmessage({
action: 'done'
});
});
transmuxer.on('gopinfo', function (gopinfo) {
self.postmessage({
action: 'gopinfo',
gopinfo: gopinfo
});
});
transmuxer.on('videosegmenttiminginfo', function (timinginfo) {
var videosegmenttiminginfo = {
start: {
decode: clock.videotstoseconds(timinginfo.start.dts),
presentation: clock.videotstoseconds(timinginfo.start.pts)
},
end: {
decode: clock.videotstoseconds(timinginfo.end.dts),
presentation: clock.videotstoseconds(timinginfo.end.pts)
},
basemediadecodetime: clock.videotstoseconds(timinginfo.basemediadecodetime)
};
if (timinginfo.prependedcontentduration) {
videosegmenttiminginfo.prependedcontentduration = clock.videotstoseconds(timinginfo.prependedcontentduration);
}
self.postmessage({
action: 'videosegmenttiminginfo',
videosegmenttiminginfo: videosegmenttiminginfo
});
});
transmuxer.on('audiosegmenttiminginfo', function (timinginfo) {
// note that all times for [audio/video]segmenttiminginfo events are in video clock
var audiosegmenttiminginfo = {
start: {
decode: clock.videotstoseconds(timinginfo.start.dts),
presentation: clock.videotstoseconds(timinginfo.start.pts)
},
end: {
decode: clock.videotstoseconds(timinginfo.end.dts),
presentation: clock.videotstoseconds(timinginfo.end.pts)
},
basemediadecodetime: clock.videotstoseconds(timinginfo.basemediadecodetime)
};
if (timinginfo.prependedcontentduration) {
audiosegmenttiminginfo.prependedcontentduration = clock.videotstoseconds(timinginfo.prependedcontentduration);
}
self.postmessage({
action: 'audiosegmenttiminginfo',
audiosegmenttiminginfo: audiosegmenttiminginfo
});
});
transmuxer.on('id3frame', function (id3frame) {
self.postmessage({
action: 'id3frame',
id3frame: id3frame
});
});
transmuxer.on('caption', function (caption) {
self.postmessage({
action: 'caption',
caption: caption
});
});
transmuxer.on('trackinfo', function (trackinfo) {
self.postmessage({
action: 'trackinfo',
trackinfo: trackinfo
});
});
transmuxer.on('audiotiminginfo', function (audiotiminginfo) {
// convert to video ts since we prioritize video time over audio
self.postmessage({
action: 'audiotiminginfo',
audiotiminginfo: {
start: clock.videotstoseconds(audiotiminginfo.start),
end: clock.videotstoseconds(audiotiminginfo.end)
}
});
});
transmuxer.on('videotiminginfo', function (videotiminginfo) {
self.postmessage({
action: 'videotiminginfo',
videotiminginfo: {
start: clock.videotstoseconds(videotiminginfo.start),
end: clock.videotstoseconds(videotiminginfo.end)
}
});
});
transmuxer.on('log', function (log) {
self.postmessage({
action: 'log',
log: log
});
});
};
/**
* all incoming messages route through this hash. if no function exists
* to handle an incoming message, then we ignore the message.
*
* @class messagehandlers
* @param {object} options the options to initialize with
*/
var messagehandlers = /*#__pure__*/function () {
function messagehandlers(self, options) {
this.options = options || {};
this.self = self;
this.init();
}
/**
* initialize our web worker and wire all the events.
*/
var _proto = messagehandlers.prototype;
_proto.init = function init() {
if (this.transmuxer) {
this.transmuxer.dispose();
}
this.transmuxer = new transmuxer.transmuxer(this.options);
wiretransmuxerevents(this.self, this.transmuxer);
};
_proto.pushmp4captions = function pushmp4captions(data) {
if (!this.captionparser) {
this.captionparser = new captionparser();
this.captionparser.init();
}
var segment = new uint8array(data.data, data.byteoffset, data.bytelength);
var parsed = this.captionparser.parse(segment, data.trackids, data.timescales);
this.self.postmessage({
action: 'mp4captions',
captions: parsed && parsed.captions || [],
logs: parsed && parsed.logs || [],
data: segment.buffer
}, [segment.buffer]);
};
_proto.probemp4starttime = function probemp4starttime(_ref) {
var timescales = _ref.timescales,
data = _ref.data;
var starttime = probe$2.starttime(timescales, data);
this.self.postmessage({
action: 'probemp4starttime',
starttime: starttime,
data: data
}, [data.buffer]);
};
_proto.probemp4tracks = function probemp4tracks(_ref2) {
var data = _ref2.data;
var tracks = probe$2.tracks(data);
this.self.postmessage({
action: 'probemp4tracks',
tracks: tracks,
data: data
}, [data.buffer]);
}
/**
* probe an mpeg2-ts segment to determine the start time of the segment in it's
* internal "media time," as well as whether it contains video and/or audio.
*
* @private
* @param {uint8array} bytes - segment bytes
* @param {number} basestarttime
* relative reference timestamp used when adjusting frame timestamps for rollover.
* this value should be in seconds, as it's converted to a 90khz clock within the
* function body.
* @return {object} the start time of the current segment in "media time" as well as
* whether it contains video and/or audio
*/
;
_proto.probets = function probets(_ref3) {
var data = _ref3.data,
basestarttime = _ref3.basestarttime;
var tsstarttime = typeof basestarttime === 'number' && !isnan(basestarttime) ? basestarttime * clock.one_second_in_ts : void 0;
var timeinfo = tsinspector.inspect(data, tsstarttime);
var result = null;
if (timeinfo) {
result = {
// each type's time info comes back as an array of 2 times, start and end
hasvideo: timeinfo.video && timeinfo.video.length === 2 || false,
hasaudio: timeinfo.audio && timeinfo.audio.length === 2 || false
};
if (result.hasvideo) {
result.videostart = timeinfo.video[0].ptstime;
}
if (result.hasaudio) {
result.audiostart = timeinfo.audio[0].ptstime;
}
}
this.self.postmessage({
action: 'probets',
result: result,
data: data
}, [data.buffer]);
};
_proto.clearallmp4captions = function clearallmp4captions() {
if (this.captionparser) {
this.captionparser.clearallcaptions();
}
};
_proto.clearparsedmp4captions = function clearparsedmp4captions() {
if (this.captionparser) {
this.captionparser.clearparsedcaptions();
}
}
/**
* adds data (a ts segment) to the start of the transmuxer pipeline for
* processing.
*
* @param {arraybuffer} data data to push into the muxer
*/
;
_proto.push = function push(data) {
// cast array buffer to correct type for transmuxer
var segment = new uint8array(data.data, data.byteoffset, data.bytelength);
this.transmuxer.push(segment);
}
/**
* recreate the transmuxer so that the next segment added via `push`
* start with a fresh transmuxer.
*/
;
_proto.reset = function reset() {
this.transmuxer.reset();
}
/**
* set the value that will be used as the `basemediadecodetime` time for the
* next segment pushed in. subsequent segments will have their `basemediadecodetime`
* set relative to the first based on the pts values.
*
* @param {object} data used to set the timestamp offset in the muxer
*/
;
_proto.settimestampoffset = function settimestampoffset(data) {
var timestampoffset = data.timestampoffset || 0;
this.transmuxer.setbasemediadecodetime(math.round(clock.secondstovideots(timestampoffset)));
};
_proto.setaudioappendstart = function setaudioappendstart(data) {
this.transmuxer.setaudioappendstart(math.ceil(clock.secondstovideots(data.appendstart)));
};
_proto.setremux = function setremux(data) {
this.transmuxer.setremux(data.remux);
}
/**
* forces the pipeline to finish processing the last segment and emit it's
* results.
*
* @param {object} data event data, not really used
*/
;
_proto.flush = function flush(data) {
this.transmuxer.flush(); // transmuxed done action is fired after both audio/video pipelines are flushed
self.postmessage({
action: 'done',
type: 'transmuxed'
});
};
_proto.endtimeline = function endtimeline() {
this.transmuxer.endtimeline(); // transmuxed endedtimeline action is fired after both audio/video pipelines end their
// timelines
self.postmessage({
action: 'endedtimeline',
type: 'transmuxed'
});
};
_proto.aligngopswith = function aligngopswith(data) {
this.transmuxer.aligngopswith(data.gopstoalignwith.slice());
};
return messagehandlers;
}();
/**
* our web worker interface so that things can talk to mux.js
* that will be running in a web worker. the scope is passed to this by
* webworkify.
*
* @param {object} self the scope for the web worker
*/
self.onmessage = function (event) {
if (event.data.action === 'init' && event.data.options) {
this.messagehandlers = new messagehandlers(self, event.data.options);
return;
}
if (!this.messagehandlers) {
this.messagehandlers = new messagehandlers(self);
}
if (event.data && event.data.action && event.data.action !== 'init') {
if (this.messagehandlers[event.data.action]) {
this.messagehandlers[event.data.action](event.data);
}
}
};
}));
var transmuxworker = factory(workercode$1);
/* rollup-plugin-worker-factory end for worker!/home/runner/work/http-streaming/http-streaming/src/transmuxer-worker.js */
var handledata_ = function handledata_(event, transmuxeddata, callback) {
var _event$data$segment = event.data.segment,
type = _event$data$segment.type,
initsegment = _event$data$segment.initsegment,
captions = _event$data$segment.captions,
captionstreams = _event$data$segment.captionstreams,
metadata = _event$data$segment.metadata,
videoframedtstime = _event$data$segment.videoframedtstime,
videoframeptstime = _event$data$segment.videoframeptstime;
transmuxeddata.buffer.push({
captions: captions,
captionstreams: captionstreams,
metadata: metadata
});
var boxes = event.data.segment.boxes || {
data: event.data.segment.data
};
var result = {
type: type,
// cast arraybuffer to typedarray
data: new uint8array(boxes.data, boxes.data.byteoffset, boxes.data.bytelength),
initsegment: new uint8array(initsegment.data, initsegment.byteoffset, initsegment.bytelength)
};
if (typeof videoframedtstime !== 'undefined') {
result.videoframedtstime = videoframedtstime;
}
if (typeof videoframeptstime !== 'undefined') {
result.videoframeptstime = videoframeptstime;
}
callback(result);
};
var handledone_ = function handledone_(_ref) {
var transmuxeddata = _ref.transmuxeddata,
callback = _ref.callback; // previously we only returned data on data events,
// not on done events. clear out the buffer to keep that consistent.
transmuxeddata.buffer = []; // all buffers should have been flushed from the muxer, so start processing anything we
// have received
callback(transmuxeddata);
};
var handlegopinfo_ = function handlegopinfo_(event, transmuxeddata) {
transmuxeddata.gopinfo = event.data.gopinfo;
};
var processtransmux = function processtransmux(options) {
var transmuxer = options.transmuxer,
bytes = options.bytes,
audioappendstart = options.audioappendstart,
gopstoalignwith = options.gopstoalignwith,
remux = options.remux,
ondata = options.ondata,
ontrackinfo = options.ontrackinfo,
onaudiotiminginfo = options.onaudiotiminginfo,
onvideotiminginfo = options.onvideotiminginfo,
onvideosegmenttiminginfo = options.onvideosegmenttiminginfo,
onaudiosegmenttiminginfo = options.onaudiosegmenttiminginfo,
onid3 = options.onid3,
oncaptions = options.oncaptions,
ondone = options.ondone,
onendedtimeline = options.onendedtimeline,
ontransmuxerlog = options.ontransmuxerlog,
isendoftimeline = options.isendoftimeline;
var transmuxeddata = {
buffer: []
};
var waitforendedtimelineevent = isendoftimeline;
var handlemessage = function handlemessage(event) {
if (transmuxer.currenttransmux !== options) {
// disposed
return;
}
if (event.data.action === 'data') {
handledata_(event, transmuxeddata, ondata);
}
if (event.data.action === 'trackinfo') {
ontrackinfo(event.data.trackinfo);
}
if (event.data.action === 'gopinfo') {
handlegopinfo_(event, transmuxeddata);
}
if (event.data.action === 'audiotiminginfo') {
onaudiotiminginfo(event.data.audiotiminginfo);
}
if (event.data.action === 'videotiminginfo') {
onvideotiminginfo(event.data.videotiminginfo);
}
if (event.data.action === 'videosegmenttiminginfo') {
onvideosegmenttiminginfo(event.data.videosegmenttiminginfo);
}
if (event.data.action === 'audiosegmenttiminginfo') {
onaudiosegmenttiminginfo(event.data.audiosegmenttiminginfo);
}
if (event.data.action === 'id3frame') {
onid3([event.data.id3frame], event.data.id3frame.dispatchtype);
}
if (event.data.action === 'caption') {
oncaptions(event.data.caption);
}
if (event.data.action === 'endedtimeline') {
waitforendedtimelineevent = false;
onendedtimeline();
}
if (event.data.action === 'log') {
ontransmuxerlog(event.data.log);
} // wait for the transmuxed event since we may have audio and video
if (event.data.type !== 'transmuxed') {
return;
} // if the "endedtimeline" event has not yet fired, and this segment represents the end
// of a timeline, that means there may still be data events before the segment
// processing can be considerred complete. in that case, the final event should be
// an "endedtimeline" event with the type "transmuxed."
if (waitforendedtimelineevent) {
return;
}
transmuxer.onmessage = null;
handledone_({
transmuxeddata: transmuxeddata,
callback: ondone
});
/* eslint-disable no-use-before-define */
dequeue(transmuxer);
/* eslint-enable */
};
transmuxer.onmessage = handlemessage;
if (audioappendstart) {
transmuxer.postmessage({
action: 'setaudioappendstart',
appendstart: audioappendstart
});
} // allow empty arrays to be passed to clear out gops
if (array.isarray(gopstoalignwith)) {
transmuxer.postmessage({
action: 'aligngopswith',
gopstoalignwith: gopstoalignwith
});
}
if (typeof remux !== 'undefined') {
transmuxer.postmessage({
action: 'setremux',
remux: remux
});
}
if (bytes.bytelength) {
var buffer = bytes instanceof arraybuffer ? bytes : bytes.buffer;
var byteoffset = bytes instanceof arraybuffer ? 0 : bytes.byteoffset;
transmuxer.postmessage({
action: 'push',
// send the typed-array of data as an arraybuffer so that
// it can be sent as a "transferable" and avoid the costly
// memory copy
data: buffer,
// to recreate the original typed-array, we need information
// about what portion of the arraybuffer it was a view into
byteoffset: byteoffset,
bytelength: bytes.bytelength
}, [buffer]);
}
if (isendoftimeline) {
transmuxer.postmessage({
action: 'endtimeline'
});
} // even if we didn't push any bytes, we have to make sure we flush in case we reached
// the end of the segment
transmuxer.postmessage({
action: 'flush'
});
};
var dequeue = function dequeue(transmuxer) {
transmuxer.currenttransmux = null;
if (transmuxer.transmuxqueue.length) {
transmuxer.currenttransmux = transmuxer.transmuxqueue.shift();
if (typeof transmuxer.currenttransmux === 'function') {
transmuxer.currenttransmux();
} else {
processtransmux(transmuxer.currenttransmux);
}
}
};
var processaction = function processaction(transmuxer, action) {
transmuxer.postmessage({
action: action
});
dequeue(transmuxer);
};
var enqueueaction = function enqueueaction(action, transmuxer) {
if (!transmuxer.currenttransmux) {
transmuxer.currenttransmux = action;
processaction(transmuxer, action);
return;
}
transmuxer.transmuxqueue.push(processaction.bind(null, transmuxer, action));
};
var reset = function reset(transmuxer) {
enqueueaction('reset', transmuxer);
};
var endtimeline = function endtimeline(transmuxer) {
enqueueaction('endtimeline', transmuxer);
};
var transmux = function transmux(options) {
if (!options.transmuxer.currenttransmux) {
options.transmuxer.currenttransmux = options;
processtransmux(options);
return;
}
options.transmuxer.transmuxqueue.push(options);
};
var createtransmuxer = function createtransmuxer(options) {
var transmuxer = new transmuxworker();
transmuxer.currenttransmux = null;
transmuxer.transmuxqueue = [];
var term = transmuxer.terminate;
transmuxer.terminate = function () {
transmuxer.currenttransmux = null;
transmuxer.transmuxqueue.length = 0;
return term.call(transmuxer);
};
transmuxer.postmessage({
action: 'init',
options: options
});
return transmuxer;
};
var segmenttransmuxer = {
reset: reset,
endtimeline: endtimeline,
transmux: transmux,
createtransmuxer: createtransmuxer
};
var workercallback = function workercallback(options) {
var transmuxer = options.transmuxer;
var endaction = options.endaction || options.action;
var callback = options.callback;
var message = _babel_runtime_helpers_extends__webpack_imported_module_2___default()({}, options, {
endaction: null,
transmuxer: null,
callback: null
});
var listenforendevent = function listenforendevent(event) {
if (event.data.action !== endaction) {
return;
}
transmuxer.removeeventlistener('message', listenforendevent); // transfer ownership of bytes back to us.
if (event.data.data) {
event.data.data = new uint8array(event.data.data, options.byteoffset || 0, options.bytelength || event.data.data.bytelength);
if (options.data) {
options.data = event.data.data;
}
}
callback(event.data);
};
transmuxer.addeventlistener('message', listenforendevent);
if (options.data) {
var isarraybuffer = options.data instanceof arraybuffer;
message.byteoffset = isarraybuffer ? 0 : options.data.byteoffset;
message.bytelength = options.data.bytelength;
var transfers = [isarraybuffer ? options.data : options.data.buffer];
transmuxer.postmessage(message, transfers);
} else {
transmuxer.postmessage(message);
}
};
var request_errors = {
failure: 2,
timeout: -101,
aborted: -102
};
/**
* abort all requests
*
* @param {object} activexhrs - an object that tracks all xhr requests
*/
var abortall = function abortall(activexhrs) {
activexhrs.foreach(function (xhr) {
xhr.abort();
});
};
/**
* gather important bandwidth stats once a request has completed
*
* @param {object} request - the xhr request from which to gather stats
*/
var getrequeststats = function getrequeststats(request) {
return {
bandwidth: request.bandwidth,
bytesreceived: request.bytesreceived || 0,
roundtriptime: request.roundtriptime || 0
};
};
/**
* if possible gather bandwidth stats as a request is in
* progress
*
* @param {event} progressevent - an event object from an xhr's progress event
*/
var getprogressstats = function getprogressstats(progressevent) {
var request = progressevent.target;
var roundtriptime = date.now() - request.requesttime;
var stats = {
bandwidth: infinity,
bytesreceived: 0,
roundtriptime: roundtriptime || 0
};
stats.bytesreceived = progressevent.loaded; // this can result in infinity if stats.roundtriptime is 0 but that is ok
// because we should only use bandwidth stats on progress to determine when
// abort a request early due to insufficient bandwidth
stats.bandwidth = math.floor(stats.bytesreceived / stats.roundtriptime * 8 * 1000);
return stats;
};
/**
* handle all error conditions in one place and return an object
* with all the information
*
* @param {error|null} error - if non-null signals an error occured with the xhr
* @param {object} request - the xhr request that possibly generated the error
*/
var handleerrors = function handleerrors(error, request) {
if (request.timedout) {
return {
status: request.status,
message: 'hls request timed-out at url: ' + request.uri,
code: request_errors.timeout,
xhr: request
};
}
if (request.aborted) {
return {
status: request.status,
message: 'hls request aborted at url: ' + request.uri,
code: request_errors.aborted,
xhr: request
};
}
if (error) {
return {
status: request.status,
message: 'hls request errored at url: ' + request.uri,
code: request_errors.failure,
xhr: request
};
}
if (request.responsetype === 'arraybuffer' && request.response.bytelength === 0) {
return {
status: request.status,
message: 'empty hls response at url: ' + request.uri,
code: request_errors.failure,
xhr: request
};
}
return null;
};
/**
* handle responses for key data and convert the key data to the correct format
* for the decryption step later
*
* @param {object} segment - a simplified copy of the segmentinfo object
* from segmentloader
* @param {array} objects - objects to add the key bytes to.
* @param {function} finishprocessingfn - a callback to execute to continue processing
* this request
*/
var handlekeyresponse = function handlekeyresponse(segment, objects, finishprocessingfn) {
return function (error, request) {
var response = request.response;
var errorobj = handleerrors(error, request);
if (errorobj) {
return finishprocessingfn(errorobj, segment);
}
if (response.bytelength !== 16) {
return finishprocessingfn({
status: request.status,
message: 'invalid hls key at url: ' + request.uri,
code: request_errors.failure,
xhr: request
}, segment);
}
var view = new dataview(response);
var bytes = new uint32array([view.getuint32(0), view.getuint32(4), view.getuint32(8), view.getuint32(12)]);
for (var i = 0; i < objects.length; i++) {
objects[i].bytes = bytes;
}
return finishprocessingfn(null, segment);
};
};
var parseinitsegment = function parseinitsegment(segment, _callback) {
var type = object(_videojs_vhs_utils_es_containers__webpack_imported_module_19__[/* detectcontainerforbytes */ "a"])(segment.map.bytes); // todo: we should also handle ts init segments here, but we
// only know how to parse mp4 init segments at the moment
if (type !== 'mp4') {
var uri = segment.map.resolveduri || segment.map.uri;
return _callback({
internal: true,
message: "found unsupported " + (type || 'unknown') + " container for initialization segment at url: " + uri,
code: request_errors.failure
});
}
workercallback({
action: 'probemp4tracks',
data: segment.map.bytes,
transmuxer: segment.transmuxer,
callback: function callback(_ref) {
var tracks = _ref.tracks,
data = _ref.data; // transfer bytes back to us
segment.map.bytes = data;
tracks.foreach(function (track) {
segment.map.tracks = segment.map.tracks || {}; // only support one track of each type for now
if (segment.map.tracks[track.type]) {
return;
}
segment.map.tracks[track.type] = track;
if (typeof track.id === 'number' && track.timescale) {
segment.map.timescales = segment.map.timescales || {};
segment.map.timescales[track.id] = track.timescale;
}
});
return _callback(null);
}
});
};
/**
* handle init-segment responses
*
* @param {object} segment - a simplified copy of the segmentinfo object
* from segmentloader
* @param {function} finishprocessingfn - a callback to execute to continue processing
* this request
*/
var handleinitsegmentresponse = function handleinitsegmentresponse(_ref2) {
var segment = _ref2.segment,
finishprocessingfn = _ref2.finishprocessingfn;
return function (error, request) {
var errorobj = handleerrors(error, request);
if (errorobj) {
return finishprocessingfn(errorobj, segment);
}
var bytes = new uint8array(request.response); // init segment is encypted, we will have to wait
// until the key request is done to decrypt.
if (segment.map.key) {
segment.map.encryptedbytes = bytes;
return finishprocessingfn(null, segment);
}
segment.map.bytes = bytes;
parseinitsegment(segment, function (parseerror) {
if (parseerror) {
parseerror.xhr = request;
parseerror.status = request.status;
return finishprocessingfn(parseerror, segment);
}
finishprocessingfn(null, segment);
});
};
};
/**
* response handler for segment-requests being sure to set the correct
* property depending on whether the segment is encryped or not
* also records and keeps track of stats that are used for abr purposes
*
* @param {object} segment - a simplified copy of the segmentinfo object
* from segmentloader
* @param {function} finishprocessingfn - a callback to execute to continue processing
* this request
*/
var handlesegmentresponse = function handlesegmentresponse(_ref3) {
var segment = _ref3.segment,
finishprocessingfn = _ref3.finishprocessingfn,
responsetype = _ref3.responsetype;
return function (error, request) {
var errorobj = handleerrors(error, request);
if (errorobj) {
return finishprocessingfn(errorobj, segment);
}
var newbytes = // although responsetext "should" exist, this guard serves to prevent an error being
// thrown for two primary cases:
// 1. the mime type override stops working, or is not implemented for a specific
// browser
// 2. when using mock xhr libraries like sinon that do not allow the override behavior
responsetype === 'arraybuffer' || !request.responsetext ? request.response : stringtoarraybuffer(request.responsetext.substring(segment.lastreachedchar || 0));
segment.stats = getrequeststats(request);
if (segment.key) {
segment.encryptedbytes = new uint8array(newbytes);
} else {
segment.bytes = new uint8array(newbytes);
}
return finishprocessingfn(null, segment);
};
};
var transmuxandnotify = function transmuxandnotify(_ref4) {
var segment = _ref4.segment,
bytes = _ref4.bytes,
trackinfofn = _ref4.trackinfofn,
timinginfofn = _ref4.timinginfofn,
videosegmenttiminginfofn = _ref4.videosegmenttiminginfofn,
audiosegmenttiminginfofn = _ref4.audiosegmenttiminginfofn,
id3fn = _ref4.id3fn,
captionsfn = _ref4.captionsfn,
isendoftimeline = _ref4.isendoftimeline,
endedtimelinefn = _ref4.endedtimelinefn,
datafn = _ref4.datafn,
donefn = _ref4.donefn,
ontransmuxerlog = _ref4.ontransmuxerlog;
var fmp4tracks = segment.map && segment.map.tracks || {};
var ismuxed = boolean(fmp4tracks.audio && fmp4tracks.video); // keep references to each function so we can null them out after we're done with them.
// one reason for this is that in the case of full segments, we want to trust start
// times from the probe, rather than the transmuxer.
var audiostartfn = timinginfofn.bind(null, segment, 'audio', 'start');
var audioendfn = timinginfofn.bind(null, segment, 'audio', 'end');
var videostartfn = timinginfofn.bind(null, segment, 'video', 'start');
var videoendfn = timinginfofn.bind(null, segment, 'video', 'end');
var finish = function finish() {
return transmux({
bytes: bytes,
transmuxer: segment.transmuxer,
audioappendstart: segment.audioappendstart,
gopstoalignwith: segment.gopstoalignwith,
remux: ismuxed,
ondata: function ondata(result) {
result.type = result.type === 'combined' ? 'video' : result.type;
datafn(segment, result);
},
ontrackinfo: function ontrackinfo(trackinfo) {
if (trackinfofn) {
if (ismuxed) {
trackinfo.ismuxed = true;
}
trackinfofn(segment, trackinfo);
}
},
onaudiotiminginfo: function onaudiotiminginfo(audiotiminginfo) {
// we only want the first start value we encounter
if (audiostartfn && typeof audiotiminginfo.start !== 'undefined') {
audiostartfn(audiotiminginfo.start);
audiostartfn = null;
} // we want to continually update the end time
if (audioendfn && typeof audiotiminginfo.end !== 'undefined') {
audioendfn(audiotiminginfo.end);
}
},
onvideotiminginfo: function onvideotiminginfo(videotiminginfo) {
// we only want the first start value we encounter
if (videostartfn && typeof videotiminginfo.start !== 'undefined') {
videostartfn(videotiminginfo.start);
videostartfn = null;
} // we want to continually update the end time
if (videoendfn && typeof videotiminginfo.end !== 'undefined') {
videoendfn(videotiminginfo.end);
}
},
onvideosegmenttiminginfo: function onvideosegmenttiminginfo(videosegmenttiminginfo) {
videosegmenttiminginfofn(videosegmenttiminginfo);
},
onaudiosegmenttiminginfo: function onaudiosegmenttiminginfo(audiosegmenttiminginfo) {
audiosegmenttiminginfofn(audiosegmenttiminginfo);
},
onid3: function onid3(id3frames, dispatchtype) {
id3fn(segment, id3frames, dispatchtype);
},
oncaptions: function oncaptions(captions) {
captionsfn(segment, [captions]);
},
isendoftimeline: isendoftimeline,
onendedtimeline: function onendedtimeline() {
endedtimelinefn();
},
ontransmuxerlog: ontransmuxerlog,
ondone: function ondone(result) {
if (!donefn) {
return;
}
result.type = result.type === 'combined' ? 'video' : result.type;
donefn(null, segment, result);
}
});
}; // in the transmuxer, we don't yet have the ability to extract a "proper" start time.
// meaning cached frame data may corrupt our notion of where this segment
// really starts. to get around this, probe for the info needed.
workercallback({
action: 'probets',
transmuxer: segment.transmuxer,
data: bytes,
basestarttime: segment.basestarttime,
callback: function callback(data) {
segment.bytes = bytes = data.data;
var proberesult = data.result;
if (proberesult) {
trackinfofn(segment, {
hasaudio: proberesult.hasaudio,
hasvideo: proberesult.hasvideo,
ismuxed: ismuxed
});
trackinfofn = null;
if (proberesult.hasaudio && !ismuxed) {
audiostartfn(proberesult.audiostart);
}
if (proberesult.hasvideo) {
videostartfn(proberesult.videostart);
}
audiostartfn = null;
videostartfn = null;
}
finish();
}
});
};
var handlesegmentbytes = function handlesegmentbytes(_ref5) {
var segment = _ref5.segment,
bytes = _ref5.bytes,
trackinfofn = _ref5.trackinfofn,
timinginfofn = _ref5.timinginfofn,
videosegmenttiminginfofn = _ref5.videosegmenttiminginfofn,
audiosegmenttiminginfofn = _ref5.audiosegmenttiminginfofn,
id3fn = _ref5.id3fn,
captionsfn = _ref5.captionsfn,
isendoftimeline = _ref5.isendoftimeline,
endedtimelinefn = _ref5.endedtimelinefn,
datafn = _ref5.datafn,
donefn = _ref5.donefn,
ontransmuxerlog = _ref5.ontransmuxerlog;
var bytesasuint8array = new uint8array(bytes); // todo:
// we should have a handler that fetches the number of bytes required
// to check if something is fmp4. this will allow us to save bandwidth
// because we can only blacklist a playlist and abort requests
// by codec after trackinfo triggers.
if (object(_videojs_vhs_utils_es_containers__webpack_imported_module_19__[/* islikelyfmp4mediasegment */ "b"])(bytesasuint8array)) {
segment.isfmp4 = true;
var tracks = segment.map.tracks;
var trackinfo = {
isfmp4: true,
hasvideo: !!tracks.video,
hasaudio: !!tracks.audio
}; // if we have a audio track, with a codec that is not set to
// encrypted audio
if (tracks.audio && tracks.audio.codec && tracks.audio.codec !== 'enca') {
trackinfo.audiocodec = tracks.audio.codec;
} // if we have a video track, with a codec that is not set to
// encrypted video
if (tracks.video && tracks.video.codec && tracks.video.codec !== 'encv') {
trackinfo.videocodec = tracks.video.codec;
}
if (tracks.video && tracks.audio) {
trackinfo.ismuxed = true;
} // since we don't support appending fmp4 data on progress, we know we have the full
// segment here
trackinfofn(segment, trackinfo); // the probe doesn't provide the segment end time, so only callback with the start
// time. the end time can be roughly calculated by the receiver using the duration.
//
// note that the start time returned by the probe reflects the basemediadecodetime, as
// that is the true start of the segment (where the playback engine should begin
// decoding).
var finishloading = function finishloading(captions) {
// if the track still has audio at this point it is only possible
// for it to be audio only. see `tracks.video && tracks.audio` if statement
// above.
// we make sure to use segment.bytes here as that
datafn(segment, {
data: bytesasuint8array,
type: trackinfo.hasaudio && !trackinfo.ismuxed ? 'audio' : 'video'
});
if (captions && captions.length) {
captionsfn(segment, captions);
}
donefn(null, segment, {});
};
workercallback({
action: 'probemp4starttime',
timescales: segment.map.timescales,
data: bytesasuint8array,
transmuxer: segment.transmuxer,
callback: function callback(_ref6) {
var data = _ref6.data,
starttime = _ref6.starttime; // transfer bytes back to us
bytes = data.buffer;
segment.bytes = bytesasuint8array = data;
if (trackinfo.hasaudio && !trackinfo.ismuxed) {
timinginfofn(segment, 'audio', 'start', starttime);
}
if (trackinfo.hasvideo) {
timinginfofn(segment, 'video', 'start', starttime);
} // run through the captionparser in case there are captions.
// initialize captionparser if it hasn't been yet
if (!tracks.video || !data.bytelength || !segment.transmuxer) {
finishloading();
return;
}
workercallback({
action: 'pushmp4captions',
endaction: 'mp4captions',
transmuxer: segment.transmuxer,
data: bytesasuint8array,
timescales: segment.map.timescales,
trackids: [tracks.video.id],
callback: function callback(message) {
// transfer bytes back to us
bytes = message.data.buffer;
segment.bytes = bytesasuint8array = message.data;
message.logs.foreach(function (log) {
ontransmuxerlog(videojs.mergeoptions(log, {
stream: 'mp4captionparser'
}));
});
finishloading(message.captions);
}
});
}
});
return;
} // vtt or other segments that don't need processing
if (!segment.transmuxer) {
donefn(null, segment, {});
return;
}
if (typeof segment.container === 'undefined') {
segment.container = object(_videojs_vhs_utils_es_containers__webpack_imported_module_19__[/* detectcontainerforbytes */ "a"])(bytesasuint8array);
}
if (segment.container !== 'ts' && segment.container !== 'aac') {
trackinfofn(segment, {
hasaudio: false,
hasvideo: false
});
donefn(null, segment, {});
return;
} // ts or aac
transmuxandnotify({
segment: segment,
bytes: bytes,
trackinfofn: trackinfofn,
timinginfofn: timinginfofn,
videosegmenttiminginfofn: videosegmenttiminginfofn,
audiosegmenttiminginfofn: audiosegmenttiminginfofn,
id3fn: id3fn,
captionsfn: captionsfn,
isendoftimeline: isendoftimeline,
endedtimelinefn: endedtimelinefn,
datafn: datafn,
donefn: donefn,
ontransmuxerlog: ontransmuxerlog
});
};
var decrypt = function decrypt(_ref7, callback) {
var id = _ref7.id,
key = _ref7.key,
encryptedbytes = _ref7.encryptedbytes,
decryptionworker = _ref7.decryptionworker;
var decryptionhandler = function decryptionhandler(event) {
if (event.data.source === id) {
decryptionworker.removeeventlistener('message', decryptionhandler);
var decrypted = event.data.decrypted;
callback(new uint8array(decrypted.bytes, decrypted.byteoffset, decrypted.bytelength));
}
};
decryptionworker.addeventlistener('message', decryptionhandler);
var keybytes;
if (key.bytes.slice) {
keybytes = key.bytes.slice();
} else {
keybytes = new uint32array(array.prototype.slice.call(key.bytes));
} // incrementally decrypt the bytes
decryptionworker.postmessage(createtransferablemessage({
source: id,
encrypted: encryptedbytes,
key: keybytes,
iv: key.iv
}), [encryptedbytes.buffer, keybytes.buffer]);
};
/**
* decrypt the segment via the decryption web worker
*
* @param {webworker} decryptionworker - a webworker interface to aes-128 decryption
* routines
* @param {object} segment - a simplified copy of the segmentinfo object
* from segmentloader
* @param {function} trackinfofn - a callback that receives track info
* @param {function} timinginfofn - a callback that receives timing info
* @param {function} videosegmenttiminginfofn
* a callback that receives video timing info based on media times and
* any adjustments made by the transmuxer
* @param {function} audiosegmenttiminginfofn
* a callback that receives audio timing info based on media times and
* any adjustments made by the transmuxer
* @param {boolean} isendoftimeline
* true if this segment represents the last segment in a timeline
* @param {function} endedtimelinefn
* a callback made when a timeline is ended, will only be called if
* isendoftimeline is true
* @param {function} datafn - a callback that is executed when segment bytes are available
* and ready to use
* @param {function} donefn - a callback that is executed after decryption has completed
*/
var decryptsegment = function decryptsegment(_ref8) {
var decryptionworker = _ref8.decryptionworker,
segment = _ref8.segment,
trackinfofn = _ref8.trackinfofn,
timinginfofn = _ref8.timinginfofn,
videosegmenttiminginfofn = _ref8.videosegmenttiminginfofn,
audiosegmenttiminginfofn = _ref8.audiosegmenttiminginfofn,
id3fn = _ref8.id3fn,
captionsfn = _ref8.captionsfn,
isendoftimeline = _ref8.isendoftimeline,
endedtimelinefn = _ref8.endedtimelinefn,
datafn = _ref8.datafn,
donefn = _ref8.donefn,
ontransmuxerlog = _ref8.ontransmuxerlog;
decrypt({
id: segment.requestid,
key: segment.key,
encryptedbytes: segment.encryptedbytes,
decryptionworker: decryptionworker
}, function (decryptedbytes) {
segment.bytes = decryptedbytes;
handlesegmentbytes({
segment: segment,
bytes: segment.bytes,
trackinfofn: trackinfofn,
timinginfofn: timinginfofn,
videosegmenttiminginfofn: videosegmenttiminginfofn,
audiosegmenttiminginfofn: audiosegmenttiminginfofn,
id3fn: id3fn,
captionsfn: captionsfn,
isendoftimeline: isendoftimeline,
endedtimelinefn: endedtimelinefn,
datafn: datafn,
donefn: donefn,
ontransmuxerlog: ontransmuxerlog
});
});
};
/**
* this function waits for all xhrs to finish (with either success or failure)
* before continueing processing via it's callback. the function gathers errors
* from each request into a single errors array so that the error status for
* each request can be examined later.
*
* @param {object} activexhrs - an object that tracks all xhr requests
* @param {webworker} decryptionworker - a webworker interface to aes-128 decryption
* routines
* @param {function} trackinfofn - a callback that receives track info
* @param {function} timinginfofn - a callback that receives timing info
* @param {function} videosegmenttiminginfofn
* a callback that receives video timing info based on media times and
* any adjustments made by the transmuxer
* @param {function} audiosegmenttiminginfofn
* a callback that receives audio timing info based on media times and
* any adjustments made by the transmuxer
* @param {function} id3fn - a callback that receives id3 metadata
* @param {function} captionsfn - a callback that receives captions
* @param {boolean} isendoftimeline
* true if this segment represents the last segment in a timeline
* @param {function} endedtimelinefn
* a callback made when a timeline is ended, will only be called if
* isendoftimeline is true
* @param {function} datafn - a callback that is executed when segment bytes are available
* and ready to use
* @param {function} donefn - a callback that is executed after all resources have been
* downloaded and any decryption completed
*/
var waitforcompletion = function waitforcompletion(_ref9) {
var activexhrs = _ref9.activexhrs,
decryptionworker = _ref9.decryptionworker,
trackinfofn = _ref9.trackinfofn,
timinginfofn = _ref9.timinginfofn,
videosegmenttiminginfofn = _ref9.videosegmenttiminginfofn,
audiosegmenttiminginfofn = _ref9.audiosegmenttiminginfofn,
id3fn = _ref9.id3fn,
captionsfn = _ref9.captionsfn,
isendoftimeline = _ref9.isendoftimeline,
endedtimelinefn = _ref9.endedtimelinefn,
datafn = _ref9.datafn,
donefn = _ref9.donefn,
ontransmuxerlog = _ref9.ontransmuxerlog;
var count = 0;
var diderror = false;
return function (error, segment) {
if (diderror) {
return;
}
if (error) {
diderror = true; // if there are errors, we have to abort any outstanding requests
abortall(activexhrs); // even though the requests above are aborted, and in theory we could wait until we
// handle the aborted events from those requests, there are some cases where we may
// never get an aborted event. for instance, if the network connection is lost and
// there were two requests, the first may have triggered an error immediately, while
// the second request remains unsent. in that case, the aborted algorithm will not
// trigger an abort: see https://xhr.spec.whatwg.org/#the-abort()-method
//
// we also can't rely on the ready state of the xhr, since the request that
// triggered the connection error may also show as a ready state of 0 (unsent).
// therefore, we have to finish this group of requests immediately after the first
// seen error.
return donefn(error, segment);
}
count += 1;
if (count === activexhrs.length) {
var segmentfinish = function segmentfinish() {
if (segment.encryptedbytes) {
return decryptsegment({
decryptionworker: decryptionworker,
segment: segment,
trackinfofn: trackinfofn,
timinginfofn: timinginfofn,
videosegmenttiminginfofn: videosegmenttiminginfofn,
audiosegmenttiminginfofn: audiosegmenttiminginfofn,
id3fn: id3fn,
captionsfn: captionsfn,
isendoftimeline: isendoftimeline,
endedtimelinefn: endedtimelinefn,
datafn: datafn,
donefn: donefn,
ontransmuxerlog: ontransmuxerlog
});
} // otherwise, everything is ready just continue
handlesegmentbytes({
segment: segment,
bytes: segment.bytes,
trackinfofn: trackinfofn,
timinginfofn: timinginfofn,
videosegmenttiminginfofn: videosegmenttiminginfofn,
audiosegmenttiminginfofn: audiosegmenttiminginfofn,
id3fn: id3fn,
captionsfn: captionsfn,
isendoftimeline: isendoftimeline,
endedtimelinefn: endedtimelinefn,
datafn: datafn,
donefn: donefn,
ontransmuxerlog: ontransmuxerlog
});
}; // keep track of when *all* of the requests have completed
segment.endofallrequests = date.now();
if (segment.map && segment.map.encryptedbytes && !segment.map.bytes) {
return decrypt({
decryptionworker: decryptionworker,
// add -init to the "id" to differentiate between segment
// and init segment decryption, just in case they happen
// at the same time at some point in the future.
id: segment.requestid + '-init',
encryptedbytes: segment.map.encryptedbytes,
key: segment.map.key
}, function (decryptedbytes) {
segment.map.bytes = decryptedbytes;
parseinitsegment(segment, function (parseerror) {
if (parseerror) {
abortall(activexhrs);
return donefn(parseerror, segment);
}
segmentfinish();
});
});
}
segmentfinish();
}
};
};
/**
* calls the abort callback if any request within the batch was aborted. will only call
* the callback once per batch of requests, even if multiple were aborted.
*
* @param {object} loadendstate - state to check to see if the abort function was called
* @param {function} abortfn - callback to call for abort
*/
var handleloadend = function handleloadend(_ref10) {
var loadendstate = _ref10.loadendstate,
abortfn = _ref10.abortfn;
return function (event) {
var request = event.target;
if (request.aborted && abortfn && !loadendstate.calledabortfn) {
abortfn();
loadendstate.calledabortfn = true;
}
};
};
/**
* simple progress event callback handler that gathers some stats before
* executing a provided callback with the `segment` object
*
* @param {object} segment - a simplified copy of the segmentinfo object
* from segmentloader
* @param {function} progressfn - a callback that is executed each time a progress event
* is received
* @param {function} trackinfofn - a callback that receives track info
* @param {function} timinginfofn - a callback that receives timing info
* @param {function} videosegmenttiminginfofn
* a callback that receives video timing info based on media times and
* any adjustments made by the transmuxer
* @param {function} audiosegmenttiminginfofn
* a callback that receives audio timing info based on media times and
* any adjustments made by the transmuxer
* @param {boolean} isendoftimeline
* true if this segment represents the last segment in a timeline
* @param {function} endedtimelinefn
* a callback made when a timeline is ended, will only be called if
* isendoftimeline is true
* @param {function} datafn - a callback that is executed when segment bytes are available
* and ready to use
* @param {event} event - the progress event object from xmlhttprequest
*/
var handleprogress = function handleprogress(_ref11) {
var segment = _ref11.segment,
progressfn = _ref11.progressfn;
_ref11.trackinfofn;
_ref11.timinginfofn;
_ref11.videosegmenttiminginfofn;
_ref11.audiosegmenttiminginfofn;
_ref11.id3fn;
_ref11.captionsfn;
_ref11.isendoftimeline;
_ref11.endedtimelinefn;
_ref11.datafn;
return function (event) {
var request = event.target;
if (request.aborted) {
return;
}
segment.stats = videojs.mergeoptions(segment.stats, getprogressstats(event)); // record the time that we receive the first byte of data
if (!segment.stats.firstbytesreceivedat && segment.stats.bytesreceived) {
segment.stats.firstbytesreceivedat = date.now();
}
return progressfn(event, segment);
};
};
/**
* load all resources and does any processing necessary for a media-segment
*
* features:
* decrypts the media-segment if it has a key uri and an iv
* aborts *all* requests if *any* one request fails
*
* the segment object, at minimum, has the following format:
* {
* resolveduri: string,
* [transmuxer]: object,
* [byterange]: {
* offset: number,
* length: number
* },
* [key]: {
* resolveduri: string
* [byterange]: {
* offset: number,
* length: number
* },
* iv: {
* bytes: uint32array
* }
* },
* [map]: {
* resolveduri: string,
* [byterange]: {
* offset: number,
* length: number
* },
* [bytes]: uint8array
* }
* }
* ...where [name] denotes optional properties
*
* @param {function} xhr - an instance of the xhr wrapper in xhr.js
* @param {object} xhroptions - the base options to provide to all xhr requests
* @param {webworker} decryptionworker - a webworker interface to aes-128
* decryption routines
* @param {object} segment - a simplified copy of the segmentinfo object
* from segmentloader
* @param {function} abortfn - a callback called (only once) if any piece of a request was
* aborted
* @param {function} progressfn - a callback that receives progress events from the main
* segment's xhr request
* @param {function} trackinfofn - a callback that receives track info
* @param {function} timinginfofn - a callback that receives timing info
* @param {function} videosegmenttiminginfofn
* a callback that receives video timing info based on media times and
* any adjustments made by the transmuxer
* @param {function} audiosegmenttiminginfofn
* a callback that receives audio timing info based on media times and
* any adjustments made by the transmuxer
* @param {function} id3fn - a callback that receives id3 metadata
* @param {function} captionsfn - a callback that receives captions
* @param {boolean} isendoftimeline
* true if this segment represents the last segment in a timeline
* @param {function} endedtimelinefn
* a callback made when a timeline is ended, will only be called if
* isendoftimeline is true
* @param {function} datafn - a callback that receives data from the main segment's xhr
* request, transmuxed if needed
* @param {function} donefn - a callback that is executed only once all requests have
* succeeded or failed
* @return {function} a function that, when invoked, immediately aborts all
* outstanding requests
*/
var mediasegmentrequest = function mediasegmentrequest(_ref12) {
var xhr = _ref12.xhr,
xhroptions = _ref12.xhroptions,
decryptionworker = _ref12.decryptionworker,
segment = _ref12.segment,
abortfn = _ref12.abortfn,
progressfn = _ref12.progressfn,
trackinfofn = _ref12.trackinfofn,
timinginfofn = _ref12.timinginfofn,
videosegmenttiminginfofn = _ref12.videosegmenttiminginfofn,
audiosegmenttiminginfofn = _ref12.audiosegmenttiminginfofn,
id3fn = _ref12.id3fn,
captionsfn = _ref12.captionsfn,
isendoftimeline = _ref12.isendoftimeline,
endedtimelinefn = _ref12.endedtimelinefn,
datafn = _ref12.datafn,
donefn = _ref12.donefn,
ontransmuxerlog = _ref12.ontransmuxerlog;
var activexhrs = [];
var finishprocessingfn = waitforcompletion({
activexhrs: activexhrs,
decryptionworker: decryptionworker,
trackinfofn: trackinfofn,
timinginfofn: timinginfofn,
videosegmenttiminginfofn: videosegmenttiminginfofn,
audiosegmenttiminginfofn: audiosegmenttiminginfofn,
id3fn: id3fn,
captionsfn: captionsfn,
isendoftimeline: isendoftimeline,
endedtimelinefn: endedtimelinefn,
datafn: datafn,
donefn: donefn,
ontransmuxerlog: ontransmuxerlog
}); // optionally, request the decryption key
if (segment.key && !segment.key.bytes) {
var objects = [segment.key];
if (segment.map && !segment.map.bytes && segment.map.key && segment.map.key.resolveduri === segment.key.resolveduri) {
objects.push(segment.map.key);
}
var keyrequestoptions = videojs.mergeoptions(xhroptions, {
uri: segment.key.resolveduri,
responsetype: 'arraybuffer'
});
var keyrequestcallback = handlekeyresponse(segment, objects, finishprocessingfn);
var keyxhr = xhr(keyrequestoptions, keyrequestcallback);
activexhrs.push(keyxhr);
} // optionally, request the associated media init segment
if (segment.map && !segment.map.bytes) {
var differentmapkey = segment.map.key && (!segment.key || segment.key.resolveduri !== segment.map.key.resolveduri);
if (differentmapkey) {
var mapkeyrequestoptions = videojs.mergeoptions(xhroptions, {
uri: segment.map.key.resolveduri,
responsetype: 'arraybuffer'
});
var mapkeyrequestcallback = handlekeyresponse(segment, [segment.map.key], finishprocessingfn);
var mapkeyxhr = xhr(mapkeyrequestoptions, mapkeyrequestcallback);
activexhrs.push(mapkeyxhr);
}
var initsegmentoptions = videojs.mergeoptions(xhroptions, {
uri: segment.map.resolveduri,
responsetype: 'arraybuffer',
headers: segmentxhrheaders(segment.map)
});
var initsegmentrequestcallback = handleinitsegmentresponse({
segment: segment,
finishprocessingfn: finishprocessingfn
});
var initsegmentxhr = xhr(initsegmentoptions, initsegmentrequestcallback);
activexhrs.push(initsegmentxhr);
}
var segmentrequestoptions = videojs.mergeoptions(xhroptions, {
uri: segment.part && segment.part.resolveduri || segment.resolveduri,
responsetype: 'arraybuffer',
headers: segmentxhrheaders(segment)
});
var segmentrequestcallback = handlesegmentresponse({
segment: segment,
finishprocessingfn: finishprocessingfn,
responsetype: segmentrequestoptions.responsetype
});
var segmentxhr = xhr(segmentrequestoptions, segmentrequestcallback);
segmentxhr.addeventlistener('progress', handleprogress({
segment: segment,
progressfn: progressfn,
trackinfofn: trackinfofn,
timinginfofn: timinginfofn,
videosegmenttiminginfofn: videosegmenttiminginfofn,
audiosegmenttiminginfofn: audiosegmenttiminginfofn,
id3fn: id3fn,
captionsfn: captionsfn,
isendoftimeline: isendoftimeline,
endedtimelinefn: endedtimelinefn,
datafn: datafn
}));
activexhrs.push(segmentxhr); // since all parts of the request must be considered, but should not make callbacks
// multiple times, provide a shared state object
var loadendstate = {};
activexhrs.foreach(function (activexhr) {
activexhr.addeventlistener('loadend', handleloadend({
loadendstate: loadendstate,
abortfn: abortfn
}));
});
return function () {
return abortall(activexhrs);
};
};
/**
* @file - codecs.js - handles tasks regarding codec strings such as translating them to
* codec strings, or translating codec strings into objects that can be examined.
*/
var logfn$1 = logger('codecutils');
/**
* returns a set of codec strings parsed from the playlist or the default
* codec strings if no codecs were specified in the playlist
*
* @param {playlist} media the current media playlist
* @return {object} an object with the video and audio codecs
*/
var getcodecs = function getcodecs(media) {
// if the codecs were explicitly specified, use them instead of the
// defaults
var mediaattributes = media.attributes || {};
if (mediaattributes.codecs) {
return object(_videojs_vhs_utils_es_codecs_js__webpack_imported_module_13__[/* parsecodecs */ "h"])(mediaattributes.codecs);
}
};
var ismaat = function ismaat(master, media) {
var mediaattributes = media.attributes || {};
return master && master.mediagroups && master.mediagroups.audio && mediaattributes.audio && master.mediagroups.audio[mediaattributes.audio];
};
var ismuxed = function ismuxed(master, media) {
if (!ismaat(master, media)) {
return true;
}
var mediaattributes = media.attributes || {};
var audiogroup = master.mediagroups.audio[mediaattributes.audio];
for (var groupid in audiogroup) {
// if an audio group has a uri (the case for hls, as hls will use external playlists),
// or there are listed playlists (the case for dash, as the manifest will have already
// provided all of the details necessary to generate the audio playlist, as opposed to
// hls' externally requested playlists), then the content is demuxed.
if (!audiogroup[groupid].uri && !audiogroup[groupid].playlists) {
return true;
}
}
return false;
};
var unwrapcodeclist = function unwrapcodeclist(codeclist) {
var codecs = {};
codeclist.foreach(function (_ref) {
var mediatype = _ref.mediatype,
type = _ref.type,
details = _ref.details;
codecs[mediatype] = codecs[mediatype] || [];
codecs[mediatype].push(object(_videojs_vhs_utils_es_codecs_js__webpack_imported_module_13__[/* translatelegacycodec */ "i"])("" + type + details));
});
object.keys(codecs).foreach(function (mediatype) {
if (codecs[mediatype].length > 1) {
logfn$1("multiple " + mediatype + " codecs found as attributes: " + codecs[mediatype].join(', ') + ". setting playlist codecs to null so that we wait for mux.js to probe segments for real codecs.");
codecs[mediatype] = null;
return;
}
codecs[mediatype] = codecs[mediatype][0];
});
return codecs;
};
var codeccount = function codeccount(codecobj) {
var count = 0;
if (codecobj.audio) {
count++;
}
if (codecobj.video) {
count++;
}
return count;
};
/**
* calculates the codec strings for a working configuration of
* sourcebuffers to play variant streams in a master playlist. if
* there is no possible working configuration, an empty object will be
* returned.
*
* @param master {object} the m3u8 object for the master playlist
* @param media {object} the m3u8 object for the variant playlist
* @return {object} the codec strings.
*
* @private
*/
var codecsforplaylist = function codecsforplaylist(master, media) {
var mediaattributes = media.attributes || {};
var codecinfo = unwrapcodeclist(getcodecs(media) || []); // hls with multiple-audio tracks must always get an audio codec.
// put another way, there is no way to have a video-only multiple-audio hls!
if (ismaat(master, media) && !codecinfo.audio) {
if (!ismuxed(master, media)) {
// it is possible for codecs to be specified on the audio media group playlist but
// not on the rendition playlist. this is mostly the case for dash, where audio and
// video are always separate (and separately specified).
var defaultcodecs = unwrapcodeclist(object(_videojs_vhs_utils_es_codecs_js__webpack_imported_module_13__[/* codecsfromdefault */ "d"])(master, mediaattributes.audio) || []);
if (defaultcodecs.audio) {
codecinfo.audio = defaultcodecs.audio;
}
}
}
return codecinfo;
};
var logfn = logger('playlistselector');
var representationtostring = function representationtostring(representation) {
if (!representation || !representation.playlist) {
return;
}
var playlist = representation.playlist;
return json.stringify({
id: playlist.id,
bandwidth: representation.bandwidth,
width: representation.width,
height: representation.height,
codecs: playlist.attributes && playlist.attributes.codecs || ''
});
}; // utilities
/**
* returns the css value for the specified property on an element
* using `getcomputedstyle`. firefox has a long-standing issue where
* getcomputedstyle() may return null when running in an iframe with
* `display: none`.
*
* @see https://bugzilla.mozilla.org/show_bug.cgi?id=548397
* @param {htmlelement} el the htmlelement to work on
* @param {string} the proprety to get the style for
*/
var safegetcomputedstyle = function safegetcomputedstyle(el, property) {
if (!el) {
return '';
}
var result = global_window__webpack_imported_module_0___default.a.getcomputedstyle(el);
if (!result) {
return '';
}
return result[property];
};
/**
* resuable stable sort function
*
* @param {playlists} array
* @param {function} sortfn different comparators
* @function stablesort
*/
var stablesort = function stablesort(array, sortfn) {
var newarray = array.slice();
array.sort(function (left, right) {
var cmp = sortfn(left, right);
if (cmp === 0) {
return newarray.indexof(left) - newarray.indexof(right);
}
return cmp;
});
};
/**
* a comparator function to sort two playlist object by bandwidth.
*
* @param {object} left a media playlist object
* @param {object} right a media playlist object
* @return {number} greater than zero if the bandwidth attribute of
* left is greater than the corresponding attribute of right. less
* than zero if the bandwidth of right is greater than left and
* exactly zero if the two are equal.
*/
var compareplaylistbandwidth = function compareplaylistbandwidth(left, right) {
var leftbandwidth;
var rightbandwidth;
if (left.attributes.bandwidth) {
leftbandwidth = left.attributes.bandwidth;
}
leftbandwidth = leftbandwidth || global_window__webpack_imported_module_0___default.a.number.max_value;
if (right.attributes.bandwidth) {
rightbandwidth = right.attributes.bandwidth;
}
rightbandwidth = rightbandwidth || global_window__webpack_imported_module_0___default.a.number.max_value;
return leftbandwidth - rightbandwidth;
};
/**
* a comparator function to sort two playlist object by resolution (width).
*
* @param {object} left a media playlist object
* @param {object} right a media playlist object
* @return {number} greater than zero if the resolution.width attribute of
* left is greater than the corresponding attribute of right. less
* than zero if the resolution.width of right is greater than left and
* exactly zero if the two are equal.
*/
var compareplaylistresolution = function compareplaylistresolution(left, right) {
var leftwidth;
var rightwidth;
if (left.attributes.resolution && left.attributes.resolution.width) {
leftwidth = left.attributes.resolution.width;
}
leftwidth = leftwidth || global_window__webpack_imported_module_0___default.a.number.max_value;
if (right.attributes.resolution && right.attributes.resolution.width) {
rightwidth = right.attributes.resolution.width;
}
rightwidth = rightwidth || global_window__webpack_imported_module_0___default.a.number.max_value; // note - fallback to bandwidth sort as appropriate in cases where multiple renditions
// have the same media dimensions/ resolution
if (leftwidth === rightwidth && left.attributes.bandwidth && right.attributes.bandwidth) {
return left.attributes.bandwidth - right.attributes.bandwidth;
}
return leftwidth - rightwidth;
};
/**
* chooses the appropriate media playlist based on bandwidth and player size
*
* @param {object} master
* object representation of the master manifest
* @param {number} playerbandwidth
* current calculated bandwidth of the player
* @param {number} playerwidth
* current width of the player element (should account for the device pixel ratio)
* @param {number} playerheight
* current height of the player element (should account for the device pixel ratio)
* @param {boolean} limitrenditionbyplayerdimensions
* true if the player width and height should be used during the selection, false otherwise
* @param {object} masterplaylistcontroller
* the current masterplaylistcontroller object
* @return {playlist} the highest bitrate playlist less than the
* currently detected bandwidth, accounting for some amount of
* bandwidth variance
*/
var simpleselector = function simpleselector(master, playerbandwidth, playerwidth, playerheight, limitrenditionbyplayerdimensions, masterplaylistcontroller) {
// if we end up getting called before `master` is available, exit early
if (!master) {
return;
}
var options = {
bandwidth: playerbandwidth,
width: playerwidth,
height: playerheight,
limitrenditionbyplayerdimensions: limitrenditionbyplayerdimensions
};
var playlists = master.playlists; // if playlist is audio only, select between currently active audio group playlists.
if (playlist.isaudioonly(master)) {
playlists = masterplaylistcontroller.getaudiotrackplaylists_(); // add audioonly to options so that we log audioonly: true
// at the buttom of this function for debugging.
options.audioonly = true;
} // convert the playlists to an intermediary representation to make comparisons easier
var sortedplaylistreps = playlists.map(function (playlist) {
var bandwidth;
var width = playlist.attributes && playlist.attributes.resolution && playlist.attributes.resolution.width;
var height = playlist.attributes && playlist.attributes.resolution && playlist.attributes.resolution.height;
bandwidth = playlist.attributes && playlist.attributes.bandwidth;
bandwidth = bandwidth || global_window__webpack_imported_module_0___default.a.number.max_value;
return {
bandwidth: bandwidth,
width: width,
height: height,
playlist: playlist
};
});
stablesort(sortedplaylistreps, function (left, right) {
return left.bandwidth - right.bandwidth;
}); // filter out any playlists that have been excluded due to
// incompatible configurations
sortedplaylistreps = sortedplaylistreps.filter(function (rep) {
return !playlist.isincompatible(rep.playlist);
}); // filter out any playlists that have been disabled manually through the representations
// api or blacklisted temporarily due to playback errors.
var enabledplaylistreps = sortedplaylistreps.filter(function (rep) {
return playlist.isenabled(rep.playlist);
});
if (!enabledplaylistreps.length) {
// if there are no enabled playlists, then they have all been blacklisted or disabled
// by the user through the representations api. in this case, ignore blacklisting and
// fallback to what the user wants by using playlists the user has not disabled.
enabledplaylistreps = sortedplaylistreps.filter(function (rep) {
return !playlist.isdisabled(rep.playlist);
});
} // filter out any variant that has greater effective bitrate
// than the current estimated bandwidth
var bandwidthplaylistreps = enabledplaylistreps.filter(function (rep) {
return rep.bandwidth * config.bandwidth_variance < playerbandwidth;
});
var highestremainingbandwidthrep = bandwidthplaylistreps[bandwidthplaylistreps.length - 1]; // get all of the renditions with the same (highest) bandwidth
// and then taking the very first element
var bandwidthbestrep = bandwidthplaylistreps.filter(function (rep) {
return rep.bandwidth === highestremainingbandwidthrep.bandwidth;
})[0]; // if we're not going to limit renditions by player size, make an early decision.
if (limitrenditionbyplayerdimensions === false) {
var _chosenrep = bandwidthbestrep || enabledplaylistreps[0] || sortedplaylistreps[0];
if (_chosenrep && _chosenrep.playlist) {
var type = 'sortedplaylistreps';
if (bandwidthbestrep) {
type = 'bandwidthbestrep';
}
if (enabledplaylistreps[0]) {
type = 'enabledplaylistreps';
}
logfn("choosing " + representationtostring(_chosenrep) + " using " + type + " with options", options);
return _chosenrep.playlist;
}
logfn('could not choose a playlist with options', options);
return null;
} // filter out playlists without resolution information
var haveresolution = bandwidthplaylistreps.filter(function (rep) {
return rep.width && rep.height;
}); // sort variants by resolution
stablesort(haveresolution, function (left, right) {
return left.width - right.width;
}); // if we have the exact resolution as the player use it
var resolutionbestreplist = haveresolution.filter(function (rep) {
return rep.width === playerwidth && rep.height === playerheight;
});
highestremainingbandwidthrep = resolutionbestreplist[resolutionbestreplist.length - 1]; // ensure that we pick the highest bandwidth variant that have exact resolution
var resolutionbestrep = resolutionbestreplist.filter(function (rep) {
return rep.bandwidth === highestremainingbandwidthrep.bandwidth;
})[0];
var resolutionplusonelist;
var resolutionplusonesmallest;
var resolutionplusonerep; // find the smallest variant that is larger than the player
// if there is no match of exact resolution
if (!resolutionbestrep) {
resolutionplusonelist = haveresolution.filter(function (rep) {
return rep.width > playerwidth || rep.height > playerheight;
}); // find all the variants have the same smallest resolution
resolutionplusonesmallest = resolutionplusonelist.filter(function (rep) {
return rep.width === resolutionplusonelist[0].width && rep.height === resolutionplusonelist[0].height;
}); // ensure that we also pick the highest bandwidth variant that
// is just-larger-than the video player
highestremainingbandwidthrep = resolutionplusonesmallest[resolutionplusonesmallest.length - 1];
resolutionplusonerep = resolutionplusonesmallest.filter(function (rep) {
return rep.bandwidth === highestremainingbandwidthrep.bandwidth;
})[0];
}
var leastpixeldiffrep; // if this selector proves to be better than others,
// resolutionplusonerep and resolutionbestrep and all
// the code involving them should be removed.
if (masterplaylistcontroller.experimentalleastpixeldiffselector) {
// find the variant that is closest to the player's pixel size
var leastpixeldifflist = haveresolution.map(function (rep) {
rep.pixeldiff = math.abs(rep.width - playerwidth) + math.abs(rep.height - playerheight);
return rep;
}); // get the highest bandwidth, closest resolution playlist
stablesort(leastpixeldifflist, function (left, right) {
// sort by highest bandwidth if pixeldiff is the same
if (left.pixeldiff === right.pixeldiff) {
return right.bandwidth - left.bandwidth;
}
return left.pixeldiff - right.pixeldiff;
});
leastpixeldiffrep = leastpixeldifflist[0];
} // fallback chain of variants
var chosenrep = leastpixeldiffrep || resolutionplusonerep || resolutionbestrep || bandwidthbestrep || enabledplaylistreps[0] || sortedplaylistreps[0];
if (chosenrep && chosenrep.playlist) {
var _type = 'sortedplaylistreps';
if (leastpixeldiffrep) {
_type = 'leastpixeldiffrep';
} else if (resolutionplusonerep) {
_type = 'resolutionplusonerep';
} else if (resolutionbestrep) {
_type = 'resolutionbestrep';
} else if (bandwidthbestrep) {
_type = 'bandwidthbestrep';
} else if (enabledplaylistreps[0]) {
_type = 'enabledplaylistreps';
}
logfn("choosing " + representationtostring(chosenrep) + " using " + _type + " with options", options);
return chosenrep.playlist;
}
logfn('could not choose a playlist with options', options);
return null;
};
/**
* chooses the appropriate media playlist based on the most recent
* bandwidth estimate and the player size.
*
* expects to be called within the context of an instance of vhshandler
*
* @return {playlist} the highest bitrate playlist less than the
* currently detected bandwidth, accounting for some amount of
* bandwidth variance
*/
var lastbandwidthselector = function lastbandwidthselector() {
var pixelratio = this.usedevicepixelratio ? global_window__webpack_imported_module_0___default.a.devicepixelratio || 1 : 1;
return simpleselector(this.playlists.master, this.systembandwidth, parseint(safegetcomputedstyle(this.tech_.el(), 'width'), 10) * pixelratio, parseint(safegetcomputedstyle(this.tech_.el(), 'height'), 10) * pixelratio, this.limitrenditionbyplayerdimensions, this.masterplaylistcontroller_);
};
/**
* chooses the appropriate media playlist based on an
* exponential-weighted moving average of the bandwidth after
* filtering for player size.
*
* expects to be called within the context of an instance of vhshandler
*
* @param {number} decay - a number between 0 and 1. higher values of
* this parameter will cause previous bandwidth estimates to lose
* significance more quickly.
* @return {function} a function which can be invoked to create a new
* playlist selector function.
* @see https://en.wikipedia.org/wiki/moving_average#exponential_moving_average
*/
var movingaveragebandwidthselector = function movingaveragebandwidthselector(decay) {
var average = -1;
var lastsystembandwidth = -1;
if (decay < 0 || decay > 1) {
throw new error('moving average bandwidth decay must be between 0 and 1.');
}
return function () {
var pixelratio = this.usedevicepixelratio ? global_window__webpack_imported_module_0___default.a.devicepixelratio || 1 : 1;
if (average < 0) {
average = this.systembandwidth;
lastsystembandwidth = this.systembandwidth;
} // stop the average value from decaying for every 250ms
// when the systembandwidth is constant
// and
// stop average from setting to a very low value when the
// systembandwidth becomes 0 in case of chunk cancellation
if (this.systembandwidth > 0 && this.systembandwidth !== lastsystembandwidth) {
average = decay * this.systembandwidth + (1 - decay) * average;
lastsystembandwidth = this.systembandwidth;
}
return simpleselector(this.playlists.master, average, parseint(safegetcomputedstyle(this.tech_.el(), 'width'), 10) * pixelratio, parseint(safegetcomputedstyle(this.tech_.el(), 'height'), 10) * pixelratio, this.limitrenditionbyplayerdimensions, this.masterplaylistcontroller_);
};
};
/**
* chooses the appropriate media playlist based on the potential to rebuffer
*
* @param {object} settings
* object of information required to use this selector
* @param {object} settings.master
* object representation of the master manifest
* @param {number} settings.currenttime
* the current time of the player
* @param {number} settings.bandwidth
* current measured bandwidth
* @param {number} settings.duration
* duration of the media
* @param {number} settings.segmentduration
* segment duration to be used in round trip time calculations
* @param {number} settings.timeuntilrebuffer
* time left in seconds until the player has to rebuffer
* @param {number} settings.currenttimeline
* the current timeline segments are being loaded from
* @param {synccontroller} settings.synccontroller
* synccontroller for determining if we have a sync point for a given playlist
* @return {object|null}
* {object} return.playlist
* the highest bandwidth playlist with the least amount of rebuffering
* {number} return.rebufferingimpact
* the amount of time in seconds switching to this playlist will rebuffer. a
* negative value means that switching will cause zero rebuffering.
*/
var minrebuffermaxbandwidthselector = function minrebuffermaxbandwidthselector(settings) {
var master = settings.master,
currenttime = settings.currenttime,
bandwidth = settings.bandwidth,
duration = settings.duration,
segmentduration = settings.segmentduration,
timeuntilrebuffer = settings.timeuntilrebuffer,
currenttimeline = settings.currenttimeline,
synccontroller = settings.synccontroller; // filter out any playlists that have been excluded due to
// incompatible configurations
var compatibleplaylists = master.playlists.filter(function (playlist) {
return !playlist.isincompatible(playlist);
}); // filter out any playlists that have been disabled manually through the representations
// api or blacklisted temporarily due to playback errors.
var enabledplaylists = compatibleplaylists.filter(playlist.isenabled);
if (!enabledplaylists.length) {
// if there are no enabled playlists, then they have all been blacklisted or disabled
// by the user through the representations api. in this case, ignore blacklisting and
// fallback to what the user wants by using playlists the user has not disabled.
enabledplaylists = compatibleplaylists.filter(function (playlist) {
return !playlist.isdisabled(playlist);
});
}
var bandwidthplaylists = enabledplaylists.filter(playlist.hasattribute.bind(null, 'bandwidth'));
var rebufferingestimates = bandwidthplaylists.map(function (playlist) {
var syncpoint = synccontroller.getsyncpoint(playlist, duration, currenttimeline, currenttime); // if there is no sync point for this playlist, switching to it will require a
// sync request first. this will double the request time
var numrequests = syncpoint ? 1 : 2;
var requesttimeestimate = playlist.estimatesegmentrequesttime(segmentduration, bandwidth, playlist);
var rebufferingimpact = requesttimeestimate * numrequests - timeuntilrebuffer;
return {
playlist: playlist,
rebufferingimpact: rebufferingimpact
};
});
var norebufferingplaylists = rebufferingestimates.filter(function (estimate) {
return estimate.rebufferingimpact <= 0;
}); // sort by bandwidth desc
stablesort(norebufferingplaylists, function (a, b) {
return compareplaylistbandwidth(b.playlist, a.playlist);
});
if (norebufferingplaylists.length) {
return norebufferingplaylists[0];
}
stablesort(rebufferingestimates, function (a, b) {
return a.rebufferingimpact - b.rebufferingimpact;
});
return rebufferingestimates[0] || null;
};
/**
* chooses the appropriate media playlist, which in this case is the lowest bitrate
* one with video. if no renditions with video exist, return the lowest audio rendition.
*
* expects to be called within the context of an instance of vhshandler
*
* @return {object|null}
* {object} return.playlist
* the lowest bitrate playlist that contains a video codec. if no such rendition
* exists pick the lowest audio rendition.
*/
var lowestbitratecompatiblevariantselector = function lowestbitratecompatiblevariantselector() {
var _this = this; // filter out any playlists that have been excluded due to
// incompatible configurations or playback errors
var playlists = this.playlists.master.playlists.filter(playlist.isenabled); // sort ascending by bitrate
stablesort(playlists, function (a, b) {
return compareplaylistbandwidth(a, b);
}); // parse and assume that playlists with no video codec have no video
// (this is not necessarily true, although it is generally true).
//
// if an entire manifest has no valid videos everything will get filtered
// out.
var playlistswithvideo = playlists.filter(function (playlist) {
return !!codecsforplaylist(_this.playlists.master, playlist).video;
});
return playlistswithvideo[0] || null;
};
/**
* combine all segments into a single uint8array
*
* @param {object} segmentobj
* @return {uint8array} concatenated bytes
* @private
*/
var concatsegments = function concatsegments(segmentobj) {
var offset = 0;
var tempbuffer;
if (segmentobj.bytes) {
tempbuffer = new uint8array(segmentobj.bytes); // combine the individual segments into one large typed-array
segmentobj.segments.foreach(function (segment) {
tempbuffer.set(segment, offset);
offset += segment.bytelength;
});
}
return tempbuffer;
};
/**
* @file text-tracks.js
*/
/**
* create captions text tracks on video.js if they do not exist
*
* @param {object} inbandtexttracks a reference to current inbandtexttracks
* @param {object} tech the video.js tech
* @param {object} captionstream the caption stream to create
* @private
*/
var createcaptionstrackifnotexists = function createcaptionstrackifnotexists(inbandtexttracks, tech, captionstream) {
if (!inbandtexttracks[captionstream]) {
tech.trigger({
type: 'usage',
name: 'vhs-608'
});
tech.trigger({
type: 'usage',
name: 'hls-608'
});
var instreamid = captionstream; // we need to translate servicen for 708 to how mux.js currently labels them
if (/^cc708_/.test(captionstream)) {
instreamid = 'service' + captionstream.split('_')[1];
}
var track = tech.texttracks().gettrackbyid(instreamid);
if (track) {
// resuse an existing track with a cc# id because this was
// very likely created by videojs-contrib-hls from information
// in the m3u8 for us to use
inbandtexttracks[captionstream] = track;
} else {
// this section gets called when we have caption services that aren't specified in the manifest.
// manifest level caption services are handled in media-groups.js under closed-captions.
var captionservices = tech.options_.vhs && tech.options_.vhs.captionservices || {};
var label = captionstream;
var language = captionstream;
var def = false;
var captionservice = captionservices[instreamid];
if (captionservice) {
label = captionservice.label;
language = captionservice.language;
def = captionservice["default"];
} // otherwise, create a track with the default `cc#` label and
// without a language
inbandtexttracks[captionstream] = tech.addremotetexttrack({
kind: 'captions',
id: instreamid,
// todo: investigate why this doesn't seem to turn the caption on by default
"default": def,
label: label,
language: language
}, false).track;
}
}
};
/**
* add caption text track data to a source handler given an array of captions
*
* @param {object}
* @param {object} inbandtexttracks the inband text tracks
* @param {number} timestampoffset the timestamp offset of the source buffer
* @param {array} captionarray an array of caption data
* @private
*/
var addcaptiondata = function addcaptiondata(_ref) {
var inbandtexttracks = _ref.inbandtexttracks,
captionarray = _ref.captionarray,
timestampoffset = _ref.timestampoffset;
if (!captionarray) {
return;
}
var cue = global_window__webpack_imported_module_0___default.a.webkitdatacue || global_window__webpack_imported_module_0___default.a.vttcue;
captionarray.foreach(function (caption) {
var track = caption.stream;
inbandtexttracks[track].addcue(new cue(caption.starttime + timestampoffset, caption.endtime + timestampoffset, caption.text));
});
};
/**
* define properties on a cue for backwards compatability,
* but warn the user that the way that they are using it
* is depricated and will be removed at a later date.
*
* @param {cue} cue the cue to add the properties on
* @private
*/
var deprecateoldcue = function deprecateoldcue(cue) {
object.defineproperties(cue.frame, {
id: {
get: function get() {
videojs.log.warn('cue.frame.id is deprecated. use cue.value.key instead.');
return cue.value.key;
}
},
value: {
get: function get() {
videojs.log.warn('cue.frame.value is deprecated. use cue.value.data instead.');
return cue.value.data;
}
},
privatedata: {
get: function get() {
videojs.log.warn('cue.frame.privatedata is deprecated. use cue.value.data instead.');
return cue.value.data;
}
}
});
};
/**
* add metadata text track data to a source handler given an array of metadata
*
* @param {object}
* @param {object} inbandtexttracks the inband text tracks
* @param {array} metadataarray an array of meta data
* @param {number} timestampoffset the timestamp offset of the source buffer
* @param {number} videoduration the duration of the video
* @private
*/
var addmetadata = function addmetadata(_ref2) {
var inbandtexttracks = _ref2.inbandtexttracks,
metadataarray = _ref2.metadataarray,
timestampoffset = _ref2.timestampoffset,
videoduration = _ref2.videoduration;
if (!metadataarray) {
return;
}
var cue = global_window__webpack_imported_module_0___default.a.webkitdatacue || global_window__webpack_imported_module_0___default.a.vttcue;
var metadatatrack = inbandtexttracks.metadatatrack_;
if (!metadatatrack) {
return;
}
metadataarray.foreach(function (metadata) {
var time = metadata.cuetime + timestampoffset; // if time isn't a finite number between 0 and infinity, like nan,
// ignore this bit of metadata.
// this likely occurs when you have an non-timed id3 tag like tit2,
// which is the "title/songname/content description" frame
if (typeof time !== 'number' || global_window__webpack_imported_module_0___default.a.isnan(time) || time < 0 || !(time < infinity)) {
return;
}
metadata.frames.foreach(function (frame) {
var cue = new cue(time, time, frame.value || frame.url || frame.data || '');
cue.frame = frame;
cue.value = frame;
deprecateoldcue(cue);
metadatatrack.addcue(cue);
});
});
if (!metadatatrack.cues || !metadatatrack.cues.length) {
return;
} // updating the metadeta cues so that
// the endtime of each cue is the starttime of the next cue
// the endtime of last cue is the duration of the video
var cues = metadatatrack.cues;
var cuesarray = []; // create a copy of the texttrackcuelist...
// ...disregarding cues with a falsey value
for (var i = 0; i < cues.length; i++) {
if (cues[i]) {
cuesarray.push(cues[i]);
}
} // group cues by their starttime value
var cuesgroupedbystarttime = cuesarray.reduce(function (obj, cue) {
var timeslot = obj[cue.starttime] || [];
timeslot.push(cue);
obj[cue.starttime] = timeslot;
return obj;
}, {}); // sort starttimes by ascending order
var sortedstarttimes = object.keys(cuesgroupedbystarttime).sort(function (a, b) {
return number(a) - number(b);
}); // map each cue group's endtime to the next group's starttime
sortedstarttimes.foreach(function (starttime, idx) {
var cuegroup = cuesgroupedbystarttime[starttime];
var nexttime = number(sortedstarttimes[idx + 1]) || videoduration; // map each cue's endtime the next group's starttime
cuegroup.foreach(function (cue) {
cue.endtime = nexttime;
});
});
};
/**
* create metadata text track on video.js if it does not exist
*
* @param {object} inbandtexttracks a reference to current inbandtexttracks
* @param {string} dispatchtype the inband metadata track dispatch type
* @param {object} tech the video.js tech
* @private
*/
var createmetadatatrackifnotexists = function createmetadatatrackifnotexists(inbandtexttracks, dispatchtype, tech) {
if (inbandtexttracks.metadatatrack_) {
return;
}
inbandtexttracks.metadatatrack_ = tech.addremotetexttrack({
kind: 'metadata',
label: 'timed metadata'
}, false).track;
inbandtexttracks.metadatatrack_.inbandmetadatatrackdispatchtype = dispatchtype;
};
/**
* remove cues from a track on video.js.
*
* @param {double} start start of where we should remove the cue
* @param {double} end end of where the we should remove the cue
* @param {object} track the text track to remove the cues from
* @private
*/
var removecuesfromtrack = function removecuesfromtrack(start, end, track) {
var i;
var cue;
if (!track) {
return;
}
if (!track.cues) {
return;
}
i = track.cues.length;
while (i--) {
cue = track.cues[i]; // remove any cue within the provided start and end time
if (cue.starttime >= start && cue.endtime <= end) {
track.removecue(cue);
}
}
};
/**
* remove duplicate cues from a track on video.js (a cue is considered a
* duplicate if it has the same time interval and text as another)
*
* @param {object} track the text track to remove the duplicate cues from
* @private
*/
var removeduplicatecuesfromtrack = function removeduplicatecuesfromtrack(track) {
var cues = track.cues;
if (!cues) {
return;
}
for (var i = 0; i < cues.length; i++) {
var duplicates = [];
var occurrences = 0;
for (var j = 0; j < cues.length; j++) {
if (cues[i].starttime === cues[j].starttime && cues[i].endtime === cues[j].endtime && cues[i].text === cues[j].text) {
occurrences++;
if (occurrences > 1) {
duplicates.push(cues[j]);
}
}
}
if (duplicates.length) {
duplicates.foreach(function (dupe) {
return track.removecue(dupe);
});
}
}
};
/**
* returns a list of gops in the buffer that have a pts value of 3 seconds or more in
* front of current time.
*
* @param {array} buffer
* the current buffer of gop information
* @param {number} currenttime
* the current time
* @param {double} mapping
* offset to map display time to stream presentation time
* @return {array}
* list of gops considered safe to append over
*/
var gopssafetoalignwith = function gopssafetoalignwith(buffer, currenttime, mapping) {
if (typeof currenttime === 'undefined' || currenttime === null || !buffer.length) {
return [];
} // pts value for current time + 3 seconds to give a bit more wiggle room
var currenttimepts = math.ceil((currenttime - mapping + 3) * mux_js_lib_utils_clock__webpack_imported_module_20__["one_second_in_ts"]);
var i;
for (i = 0; i < buffer.length; i++) {
if (buffer[i].pts > currenttimepts) {
break;
}
}
return buffer.slice(i);
};
/**
* appends gop information (timing and bytelength) received by the transmuxer for the
* gops appended in the last call to appendbuffer
*
* @param {array} buffer
* the current buffer of gop information
* @param {array} gops
* list of new gop information
* @param {boolean} replace
* if true, replace the buffer with the new gop information. if false, append the
* new gop information to the buffer in the right location of time.
* @return {array}
* updated list of gop information
*/
var updategopbuffer = function updategopbuffer(buffer, gops, replace) {
if (!gops.length) {
return buffer;
}
if (replace) {
// if we are in safe append mode, then completely overwrite the gop buffer
// with the most recent appeneded data. this will make sure that when appending
// future segments, we only try to align with gops that are both ahead of current
// time and in the last segment appended.
return gops.slice();
}
var start = gops[0].pts;
var i = 0;
for (i; i < buffer.length; i++) {
if (buffer[i].pts >= start) {
break;
}
}
return buffer.slice(0, i).concat(gops);
};
/**
* removes gop information in buffer that overlaps with provided start and end
*
* @param {array} buffer
* the current buffer of gop information
* @param {double} start
* position to start the remove at
* @param {double} end
* position to end the remove at
* @param {double} mapping
* offset to map display time to stream presentation time
*/
var removegopbuffer = function removegopbuffer(buffer, start, end, mapping) {
var startpts = math.ceil((start - mapping) * mux_js_lib_utils_clock__webpack_imported_module_20__["one_second_in_ts"]);
var endpts = math.ceil((end - mapping) * mux_js_lib_utils_clock__webpack_imported_module_20__["one_second_in_ts"]);
var updatedbuffer = buffer.slice();
var i = buffer.length;
while (i--) {
if (buffer[i].pts <= endpts) {
break;
}
}
if (i === -1) {
// no removal because end of remove range is before start of buffer
return updatedbuffer;
}
var j = i + 1;
while (j--) {
if (buffer[j].pts <= startpts) {
break;
}
} // clamp remove range start to 0 index
j = math.max(j, 0);
updatedbuffer.splice(j, i - j + 1);
return updatedbuffer;
};
var shallowequal = function shallowequal(a, b) {
// if both are undefined
// or one or the other is undefined
// they are not equal
if (!a && !b || !a && b || a && !b) {
return false;
} // they are the same object and thus, equal
if (a === b) {
return true;
} // sort keys so we can make sure they have
// all the same keys later.
var akeys = object.keys(a).sort();
var bkeys = object.keys(b).sort(); // different number of keys, not equal
if (akeys.length !== bkeys.length) {
return false;
}
for (var i = 0; i < akeys.length; i++) {
var key = akeys[i]; // different sorted keys, not equal
if (key !== bkeys[i]) {
return false;
} // different values, not equal
if (a[key] !== b[key]) {
return false;
}
}
return true;
}; // https://www.w3.org/tr/webidl-1/#quotaexceedederror
var quota_exceeded_err = 22;
/**
* the segment loader has no recourse except to fetch a segment in the
* current playlist and use the internal timestamps in that segment to
* generate a syncpoint. this function returns a good candidate index
* for that process.
*
* @param {array} segments - the segments array from a playlist.
* @return {number} an index of a segment from the playlist to load
*/
var getsyncsegmentcandidate = function getsyncsegmentcandidate(currenttimeline, segments, targettime) {
segments = segments || [];
var timelinesegments = [];
var time = 0;
for (var i = 0; i < segments.length; i++) {
var segment = segments[i];
if (currenttimeline === segment.timeline) {
timelinesegments.push(i);
time += segment.duration;
if (time > targettime) {
return i;
}
}
}
if (timelinesegments.length === 0) {
return 0;
} // default to the last timeline segment
return timelinesegments[timelinesegments.length - 1];
}; // in the event of a quota exceeded error, keep at least one second of back buffer. this
// number was arbitrarily chosen and may be updated in the future, but seemed reasonable
// as a start to prevent any potential issues with removing content too close to the
// playhead.
var min_back_buffer = 1; // in ms
var check_buffer_delay = 500;
var finite = function finite(num) {
return typeof num === 'number' && isfinite(num);
}; // with most content hovering around 30fps, if a segment has a duration less than a half
// frame at 30fps or one frame at 60fps, the bandwidth and throughput calculations will
// not accurately reflect the rest of the content.
var min_segment_duration_to_save_stats = 1 / 60;
var illegalmediaswitch = function illegalmediaswitch(loadertype, startingmedia, trackinfo) {
// although these checks should most likely cover non 'main' types, for now it narrows
// the scope of our checks.
if (loadertype !== 'main' || !startingmedia || !trackinfo) {
return null;
}
if (!trackinfo.hasaudio && !trackinfo.hasvideo) {
return 'neither audio nor video found in segment.';
}
if (startingmedia.hasvideo && !trackinfo.hasvideo) {
return 'only audio found in segment when we expected video.' + ' we can\'t switch to audio only from a stream that had video.' + ' to get rid of this message, please add codec information to the manifest.';
}
if (!startingmedia.hasvideo && trackinfo.hasvideo) {
return 'video found in segment when we expected only audio.' + ' we can\'t switch to a stream with video from an audio only stream.' + ' to get rid of this message, please add codec information to the manifest.';
}
return null;
};
/**
* calculates a time value that is safe to remove from the back buffer without interrupting
* playback.
*
* @param {timerange} seekable
* the current seekable range
* @param {number} currenttime
* the current time of the player
* @param {number} targetduration
* the target duration of the current playlist
* @return {number}
* time that is safe to remove from the back buffer without interrupting playback
*/
var safebackbuffertrimtime = function safebackbuffertrimtime(seekable, currenttime, targetduration) {
// 30 seconds before the playhead provides a safe default for trimming.
//
// choosing a reasonable default is particularly important for high bitrate content and
// vod videos/live streams with large windows, as the buffer may end up overfilled and
// throw an append_buffer_err.
var trimtime = currenttime - config.back_buffer_length;
if (seekable.length) {
// some live playlists may have a shorter window of content than the full allowed back
// buffer. for these playlists, don't save content that's no longer within the window.
trimtime = math.max(trimtime, seekable.start(0));
} // don't remove within target duration of the current time to avoid the possibility of
// removing the gop currently being played, as removing it can cause playback stalls.
var maxtrimtime = currenttime - targetduration;
return math.min(maxtrimtime, trimtime);
};
var segmentinfostring = function segmentinfostring(segmentinfo) {
var startofsegment = segmentinfo.startofsegment,
duration = segmentinfo.duration,
segment = segmentinfo.segment,
part = segmentinfo.part,
_segmentinfo$playlist = segmentinfo.playlist,
seq = _segmentinfo$playlist.mediasequence,
id = _segmentinfo$playlist.id,
_segmentinfo$playlist2 = _segmentinfo$playlist.segments,
segments = _segmentinfo$playlist2 === void 0 ? [] : _segmentinfo$playlist2,
index = segmentinfo.mediaindex,
partindex = segmentinfo.partindex,
timeline = segmentinfo.timeline;
var segmentlen = segments.length - 1;
var selection = 'mediaindex/partindex increment';
if (segmentinfo.getmediainfofortime) {
selection = "getmediainfofortime (" + segmentinfo.getmediainfofortime + ")";
} else if (segmentinfo.issyncrequest) {
selection = 'getsyncsegmentcandidate (issyncrequest)';
}
if (segmentinfo.independent) {
selection += " with independent " + segmentinfo.independent;
}
var haspartindex = typeof partindex === 'number';
var name = segmentinfo.segment.uri ? 'segment' : 'pre-segment';
var zerobasedpartcount = haspartindex ? getknownpartcount({
preloadsegment: segment
}) - 1 : 0;
return name + " [" + (seq + index) + "/" + (seq + segmentlen) + "]" + (haspartindex ? " part [" + partindex + "/" + zerobasedpartcount + "]" : '') + (" segment start/end [" + segment.start + " => " + segment.end + "]") + (haspartindex ? " part start/end [" + part.start + " => " + part.end + "]" : '') + (" startofsegment [" + startofsegment + "]") + (" duration [" + duration + "]") + (" timeline [" + timeline + "]") + (" selected by [" + selection + "]") + (" playlist [" + id + "]");
};
var timinginfopropertyformedia = function timinginfopropertyformedia(mediatype) {
return mediatype + "timinginfo";
};
/**
* returns the timestamp offset to use for the segment.
*
* @param {number} segmenttimeline
* the timeline of the segment
* @param {number} currenttimeline
* the timeline currently being followed by the loader
* @param {number} startofsegment
* the estimated segment start
* @param {timerange[]} buffered
* the loader's buffer
* @param {boolean} overridecheck
* if true, no checks are made to see if the timestamp offset value should be set,
* but sets it directly to a value.
*
* @return {number|null}
* either a number representing a new timestamp offset, or null if the segment is
* part of the same timeline
*/
var timestampoffsetforsegment = function timestampoffsetforsegment(_ref) {
var segmenttimeline = _ref.segmenttimeline,
currenttimeline = _ref.currenttimeline,
startofsegment = _ref.startofsegment,
buffered = _ref.buffered,
overridecheck = _ref.overridecheck; // check to see if we are crossing a discontinuity to see if we need to set the
// timestamp offset on the transmuxer and source buffer.
//
// previously, we changed the timestampoffset if the start of this segment was less than
// the currently set timestampoffset, but this isn't desirable as it can produce bad
// behavior, especially around long running live streams.
if (!overridecheck && segmenttimeline === currenttimeline) {
return null;
} // when changing renditions, it's possible to request a segment on an older timeline. for
// instance, given two renditions with the following:
//
// #extinf:10
// segment1
// #ext-x-discontinuity
// #extinf:10
// segment2
// #extinf:10
// segment3
//
// and the current player state:
//
// current time: 8
// buffer: 0 => 20
//
// the next segment on the current rendition would be segment3, filling the buffer from
// 20s onwards. however, if a rendition switch happens after segment2 was requested,
// then the next segment to be requested will be segment1 from the new rendition in
// order to fill time 8 and onwards. using the buffered end would result in repeated
// content (since it would position segment1 of the new rendition starting at 20s). this
// case can be identified when the new segment's timeline is a prior value. instead of
// using the buffered end, the startofsegment can be used, which, hopefully, will be
// more accurate to the actual start time of the segment.
if (segmenttimeline < currenttimeline) {
return startofsegment;
} // segmentinfo.startofsegment used to be used as the timestamp offset, however, that
// value uses the end of the last segment if it is available. while this value
// should often be correct, it's better to rely on the buffered end, as the new
// content post discontinuity should line up with the buffered end as if it were
// time 0 for the new content.
return buffered.length ? buffered.end(buffered.length - 1) : startofsegment;
};
/**
* returns whether or not the loader should wait for a timeline change from the timeline
* change controller before processing the segment.
*
* primary timing in vhs goes by video. this is different from most media players, as
* audio is more often used as the primary timing source. for the foreseeable future, vhs
* will continue to use video as the primary timing source, due to the current logic and
* expectations built around it.
* since the timing follows video, in order to maintain sync, the video loader is
* responsible for setting both audio and video source buffer timestamp offsets.
*
* setting different values for audio and video source buffers could lead to
* desyncing. the following examples demonstrate some of the situations where this
* distinction is important. note that all of these cases involve demuxed content. when
* content is muxed, the audio and video are packaged together, therefore syncing
* separate media playlists is not an issue.
*
* case 1: audio prepares to load a new timeline before video:
*
* timeline: 0 1
* audio segments: 0 1 2 3 4 5 disco 6 7 8 9
* audio loader: ^
* video segments: 0 1 2 3 4 5 disco 6 7 8 9
* video loader ^
*
* in the above example, the audio loader is preparing to load the 6th segment, the first
* after a discontinuity, while the video loader is still loading the 5th segment, before
* the discontinuity.
*
* if the audio loader goes ahead and loads and appends the 6th segment before the video
* loader crosses the discontinuity, then when appended, the 6th audio segment will use
* the timestamp offset from timeline 0. this will likely lead to desyncing. in addition,
* the audio loader must provide the audioappendstart value to trim the content in the
* transmuxer, and that value relies on the audio timestamp offset. since the audio
* timestamp offset is set by the video (main) loader, the audio loader shouldn't load the
* segment until that value is provided.
*
* case 2: video prepares to load a new timeline before audio:
*
* timeline: 0 1
* audio segments: 0 1 2 3 4 5 disco 6 7 8 9
* audio loader: ^
* video segments: 0 1 2 3 4 5 disco 6 7 8 9
* video loader ^
*
* in the above example, the video loader is preparing to load the 6th segment, the first
* after a discontinuity, while the audio loader is still loading the 5th segment, before
* the discontinuity.
*
* if the video loader goes ahead and loads and appends the 6th segment, then once the
* segment is loaded and processed, both the video and audio timestamp offsets will be
* set, since video is used as the primary timing source. this is to ensure content lines
* up appropriately, as any modifications to the video timing are reflected by audio when
* the video loader sets the audio and video timestamp offsets to the same value. however,
* setting the timestamp offset for audio before audio has had a chance to change
* timelines will likely lead to desyncing, as the audio loader will append segment 5 with
* a timestamp intended to apply to segments from timeline 1 rather than timeline 0.
*
* case 3: when seeking, audio prepares to load a new timeline before video
*
* timeline: 0 1
* audio segments: 0 1 2 3 4 5 disco 6 7 8 9
* audio loader: ^
* video segments: 0 1 2 3 4 5 disco 6 7 8 9
* video loader ^
*
* in the above example, both audio and video loaders are loading segments from timeline
* 0, but imagine that the seek originated from timeline 1.
*
* when seeking to a new timeline, the timestamp offset will be set based on the expected
* segment start of the loaded video segment. in order to maintain sync, the audio loader
* must wait for the video loader to load its segment and update both the audio and video
* timestamp offsets before it may load and append its own segment. this is the case
* whether the seek results in a mismatched segment request (e.g., the audio loader
* chooses to load segment 3 and the video loader chooses to load segment 4) or the
* loaders choose to load the same segment index from each playlist, as the segments may
* not be aligned perfectly, even for matching segment indexes.
*
* @param {object} timelinechangecontroller
* @param {number} currenttimeline
* the timeline currently being followed by the loader
* @param {number} segmenttimeline
* the timeline of the segment being loaded
* @param {('main'|'audio')} loadertype
* the loader type
* @param {boolean} audiodisabled
* whether the audio is disabled for the loader. this should only be true when the
* loader may have muxed audio in its segment, but should not append it, e.g., for
* the main loader when an alternate audio playlist is active.
*
* @return {boolean}
* whether the loader should wait for a timeline change from the timeline change
* controller before processing the segment
*/
var shouldwaitfortimelinechange = function shouldwaitfortimelinechange(_ref2) {
var timelinechangecontroller = _ref2.timelinechangecontroller,
currenttimeline = _ref2.currenttimeline,
segmenttimeline = _ref2.segmenttimeline,
loadertype = _ref2.loadertype,
audiodisabled = _ref2.audiodisabled;
if (currenttimeline === segmenttimeline) {
return false;
}
if (loadertype === 'audio') {
var lastmaintimelinechange = timelinechangecontroller.lasttimelinechange({
type: 'main'
}); // audio loader should wait if:
//
// * main hasn't had a timeline change yet (thus has not loaded its first segment)
// * main hasn't yet changed to the timeline audio is looking to load
return !lastmaintimelinechange || lastmaintimelinechange.to !== segmenttimeline;
} // the main loader only needs to wait for timeline changes if there's demuxed audio.
// otherwise, there's nothing to wait for, since audio would be muxed into the main
// loader's segments (or the content is audio/video only and handled by the main
// loader).
if (loadertype === 'main' && audiodisabled) {
var pendingaudiotimelinechange = timelinechangecontroller.pendingtimelinechange({
type: 'audio'
}); // main loader should wait for the audio loader if audio is not pending a timeline
// change to the current timeline.
//
// since the main loader is responsible for setting the timestamp offset for both
// audio and video, the main loader must wait for audio to be about to change to its
// timeline before setting the offset, otherwise, if audio is behind in loading,
// segments from the previous timeline would be adjusted by the new timestamp offset.
//
// this requirement means that video will not cross a timeline until the audio is
// about to cross to it, so that way audio and video will always cross the timeline
// together.
//
// in addition to normal timeline changes, these rules also apply to the start of a
// stream (going from a non-existent timeline, -1, to timeline 0). it's important
// that these rules apply to the first timeline change because if they did not, it's
// possible that the main loader will cross two timelines before the audio loader has
// crossed one. logic may be implemented to handle the startup as a special case, but
// it's easier to simply treat all timeline changes the same.
if (pendingaudiotimelinechange && pendingaudiotimelinechange.to === segmenttimeline) {
return false;
}
return true;
}
return false;
};
var mediaduration = function mediaduration(timinginfos) {
var maxduration = 0;
['video', 'audio'].foreach(function (type) {
var typetiminginfo = timinginfos[type + "timinginfo"];
if (!typetiminginfo) {
return;
}
var start = typetiminginfo.start,
end = typetiminginfo.end;
var duration;
if (typeof start === 'bigint' || typeof end === 'bigint') {
duration = global_window__webpack_imported_module_0___default.a.bigint(end) - global_window__webpack_imported_module_0___default.a.bigint(start);
} else if (typeof start === 'number' && typeof end === 'number') {
duration = end - start;
}
if (typeof duration !== 'undefined' && duration > maxduration) {
maxduration = duration;
}
}); // convert back to a number if it is lower than max_safe_integer
// as we only need bigint when we are above that.
if (typeof maxduration === 'bigint' && maxduration < number.max_safe_integer) {
maxduration = number(maxduration);
}
return maxduration;
};
var segmenttoolong = function segmenttoolong(_ref3) {
var segmentduration = _ref3.segmentduration,
maxduration = _ref3.maxduration; // 0 duration segments are most likely due to metadata only segments or a lack of
// information.
if (!segmentduration) {
return false;
} // for hls:
//
// https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.3.1
// the extinf duration of each media segment in the playlist
// file, when rounded to the nearest integer, must be less than or equal
// to the target duration; longer segments can trigger playback stalls
// or other errors.
//
// for dash, the mpd-parser uses the largest reported segment duration as the target
// duration. although that reported duration is occasionally approximate (i.e., not
// exact), a strict check may report that a segment is too long more often in dash.
return math.round(segmentduration) > maxduration + time_fudge_factor;
};
var gettroublesomesegmentdurationmessage = function gettroublesomesegmentdurationmessage(segmentinfo, sourcetype) {
// right now we aren't following dash's timing model exactly, so only perform
// this check for hls content.
if (sourcetype !== 'hls') {
return null;
}
var segmentduration = mediaduration({
audiotiminginfo: segmentinfo.audiotiminginfo,
videotiminginfo: segmentinfo.videotiminginfo
}); // don't report if we lack information.
//
// if the segment has a duration of 0 it is either a lack of information or a
// metadata only segment and shouldn't be reported here.
if (!segmentduration) {
return null;
}
var targetduration = segmentinfo.playlist.targetduration;
var issegmentwaytoolong = segmenttoolong({
segmentduration: segmentduration,
maxduration: targetduration * 2
});
var issegmentslightlytoolong = segmenttoolong({
segmentduration: segmentduration,
maxduration: targetduration
});
var segmenttoolongmessage = "segment with index " + segmentinfo.mediaindex + " " + ("from playlist " + segmentinfo.playlist.id + " ") + ("has a duration of " + segmentduration + " ") + ("when the reported duration is " + segmentinfo.duration + " ") + ("and the target duration is " + targetduration + ". ") + 'for hls content, a duration in excess of the target duration may result in ' + 'playback issues. see the hls specification section on ext-x-targetduration for ' + 'more details: ' + 'https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.3.1';
if (issegmentwaytoolong || issegmentslightlytoolong) {
return {
severity: issegmentwaytoolong ? 'warn' : 'info',
message: segmenttoolongmessage
};
}
return null;
};
/**
* an object that manages segment loading and appending.
*
* @class segmentloader
* @param {object} options required and optional options
* @extends videojs.eventtarget
*/
var segmentloader = /*#__pure__*/function (_videojs$eventtarget) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(segmentloader, _videojs$eventtarget);
function segmentloader(settings, options) {
var _this;
_this = _videojs$eventtarget.call(this) || this; // check pre-conditions
if (!settings) {
throw new typeerror('initialization settings are required');
}
if (typeof settings.currenttime !== 'function') {
throw new typeerror('no currenttime getter specified');
}
if (!settings.mediasource) {
throw new typeerror('no mediasource specified');
} // public properties
_this.bandwidth = settings.bandwidth;
_this.throughput = {
rate: 0,
count: 0
};
_this.roundtrip = nan;
_this.resetstats_();
_this.mediaindex = null;
_this.partindex = null; // private settings
_this.hasplayed_ = settings.hasplayed;
_this.currenttime_ = settings.currenttime;
_this.seekable_ = settings.seekable;
_this.seeking_ = settings.seeking;
_this.duration_ = settings.duration;
_this.mediasource_ = settings.mediasource;
_this.vhs_ = settings.vhs;
_this.loadertype_ = settings.loadertype;
_this.currentmediainfo_ = void 0;
_this.startingmediainfo_ = void 0;
_this.segmentmetadatatrack_ = settings.segmentmetadatatrack;
_this.goalbufferlength_ = settings.goalbufferlength;
_this.sourcetype_ = settings.sourcetype;
_this.sourceupdater_ = settings.sourceupdater;
_this.inbandtexttracks_ = settings.inbandtexttracks;
_this.state_ = 'init';
_this.timelinechangecontroller_ = settings.timelinechangecontroller;
_this.shouldsavesegmenttiminginfo_ = true;
_this.parse708captions_ = settings.parse708captions;
_this.usedtsfortimestampoffset_ = settings.usedtsfortimestampoffset;
_this.captionservices_ = settings.captionservices;
_this.experimentalexactmanifesttimings = settings.experimentalexactmanifesttimings; // private instance variables
_this.checkbuffertimeout_ = null;
_this.error_ = void 0;
_this.currenttimeline_ = -1;
_this.pendingsegment_ = null;
_this.xhroptions_ = null;
_this.pendingsegments_ = [];
_this.audiodisabled_ = false;
_this.ispendingtimestampoffset_ = false; // todo possibly move gopbuffer and timemapping info to a separate controller
_this.gopbuffer_ = [];
_this.timemapping_ = 0;
_this.safeappend_ = videojs.browser.ie_version >= 11;
_this.appendinitsegment_ = {
audio: true,
video: true
};
_this.playlistoflastinitsegment_ = {
audio: null,
video: null
};
_this.callqueue_ = []; // if the segment loader prepares to load a segment, but does not have enough
// information yet to start the loading process (e.g., if the audio loader wants to
// load a segment from the next timeline but the main loader hasn't yet crossed that
// timeline), then the load call will be added to the queue until it is ready to be
// processed.
_this.loadqueue_ = [];
_this.metadataqueue_ = {
id3: [],
caption: []
};
_this.waitingonremove_ = false;
_this.quotaexceedederrorretrytimeout_ = null; // fragmented mp4 playback
_this.activeinitsegmentid_ = null;
_this.initsegments_ = {}; // hlse playback
_this.cacheencryptionkeys_ = settings.cacheencryptionkeys;
_this.keycache_ = {};
_this.decrypter_ = settings.decrypter; // manages the tracking and generation of sync-points, mappings
// between a time in the display time and a segment index within
// a playlist
_this.synccontroller_ = settings.synccontroller;
_this.syncpoint_ = {
segmentindex: 0,
time: 0
};
_this.transmuxer_ = _this.createtransmuxer_();
_this.triggersyncinfoupdate_ = function () {
return _this.trigger('syncinfoupdate');
};
_this.synccontroller_.on('syncinfoupdate', _this.triggersyncinfoupdate_);
_this.mediasource_.addeventlistener('sourceopen', function () {
if (!_this.isendofstream_()) {
_this.ended_ = false;
}
}); // ...for determining the fetch location
_this.fetchatbuffer_ = false;
_this.logger_ = logger("segmentloader[" + _this.loadertype_ + "]");
object.defineproperty(_babel_runtime_helpers_assertthisinitialized__webpack_imported_module_4___default()(_this), 'state', {
get: function get() {
return this.state_;
},
set: function set(newstate) {
if (newstate !== this.state_) {
this.logger_(this.state_ + " -> " + newstate);
this.state_ = newstate;
this.trigger('statechange');
}
}
});
_this.sourceupdater_.on('ready', function () {
if (_this.hasenoughinfotoappend_()) {
_this.processcallqueue_();
}
}); // only the main loader needs to listen for pending timeline changes, as the main
// loader should wait for audio to be ready to change its timeline so that both main
// and audio timelines change together. for more details, see the
// shouldwaitfortimelinechange function.
if (_this.loadertype_ === 'main') {
_this.timelinechangecontroller_.on('pendingtimelinechange', function () {
if (_this.hasenoughinfotoappend_()) {
_this.processcallqueue_();
}
});
} // the main loader only listens on pending timeline changes, but the audio loader,
// since its loads follow main, needs to listen on timeline changes. for more details,
// see the shouldwaitfortimelinechange function.
if (_this.loadertype_ === 'audio') {
_this.timelinechangecontroller_.on('timelinechange', function () {
if (_this.hasenoughinfotoload_()) {
_this.processloadqueue_();
}
if (_this.hasenoughinfotoappend_()) {
_this.processcallqueue_();
}
});
}
return _this;
}
var _proto = segmentloader.prototype;
_proto.createtransmuxer_ = function createtransmuxer_() {
return segmenttransmuxer.createtransmuxer({
remux: false,
aligngopsatend: this.safeappend_,
keeporiginaltimestamps: true,
parse708captions: this.parse708captions_,
captionservices: this.captionservices_
});
}
/**
* reset all of our media stats
*
* @private
*/
;
_proto.resetstats_ = function resetstats_() {
this.mediabytestransferred = 0;
this.mediarequests = 0;
this.mediarequestsaborted = 0;
this.mediarequeststimedout = 0;
this.mediarequestserrored = 0;
this.mediatransferduration = 0;
this.mediasecondsloaded = 0;
this.mediaappends = 0;
}
/**
* dispose of the segmentloader and reset to the default state
*/
;
_proto.dispose = function dispose() {
this.trigger('dispose');
this.state = 'disposed';
this.pause();
this.abort_();
if (this.transmuxer_) {
this.transmuxer_.terminate();
}
this.resetstats_();
if (this.checkbuffertimeout_) {
global_window__webpack_imported_module_0___default.a.cleartimeout(this.checkbuffertimeout_);
}
if (this.synccontroller_ && this.triggersyncinfoupdate_) {
this.synccontroller_.off('syncinfoupdate', this.triggersyncinfoupdate_);
}
this.off();
};
_proto.setaudio = function setaudio(enable) {
this.audiodisabled_ = !enable;
if (enable) {
this.appendinitsegment_.audio = true;
} else {
// remove current track audio if it gets disabled
this.sourceupdater_.removeaudio(0, this.duration_());
}
}
/**
* abort anything that is currently doing on with the segmentloader
* and reset to a default state
*/
;
_proto.abort = function abort() {
if (this.state !== 'waiting') {
if (this.pendingsegment_) {
this.pendingsegment_ = null;
}
return;
}
this.abort_(); // we aborted the requests we were waiting on, so reset the loader's state to ready
// since we are no longer "waiting" on any requests. xhr callback is not always run
// when the request is aborted. this will prevent the loader from being stuck in the
// waiting state indefinitely.
this.state = 'ready'; // don't wait for buffer check timeouts to begin fetching the
// next segment
if (!this.paused()) {
this.monitorbuffer_();
}
}
/**
* abort all pending xhr requests and null any pending segements
*
* @private
*/
;
_proto.abort_ = function abort_() {
if (this.pendingsegment_ && this.pendingsegment_.abortrequests) {
this.pendingsegment_.abortrequests();
} // clear out the segment being processed
this.pendingsegment_ = null;
this.callqueue_ = [];
this.loadqueue_ = [];
this.metadataqueue_.id3 = [];
this.metadataqueue_.caption = [];
this.timelinechangecontroller_.clearpendingtimelinechange(this.loadertype_);
this.waitingonremove_ = false;
global_window__webpack_imported_module_0___default.a.cleartimeout(this.quotaexceedederrorretrytimeout_);
this.quotaexceedederrorretrytimeout_ = null;
};
_proto.checkforabort_ = function checkforabort_(requestid) {
// if the state is appending, then aborts will not modify the state, meaning the first
// callback that happens should reset the state to ready so that loading can continue.
if (this.state === 'appending' && !this.pendingsegment_) {
this.state = 'ready';
return true;
}
if (!this.pendingsegment_ || this.pendingsegment_.requestid !== requestid) {
return true;
}
return false;
}
/**
* set an error on the segment loader and null out any pending segements
*
* @param {error} error the error to set on the segmentloader
* @return {error} the error that was set or that is currently set
*/
;
_proto.error = function error(_error) {
if (typeof _error !== 'undefined') {
this.logger_('error occurred:', _error);
this.error_ = _error;
}
this.pendingsegment_ = null;
return this.error_;
};
_proto.endofstream = function endofstream() {
this.ended_ = true;
if (this.transmuxer_) {
// need to clear out any cached data to prepare for the new segment
segmenttransmuxer.reset(this.transmuxer_);
}
this.gopbuffer_.length = 0;
this.pause();
this.trigger('ended');
}
/**
* indicates which time ranges are buffered
*
* @return {timerange}
* timerange object representing the current buffered ranges
*/
;
_proto.buffered_ = function buffered_() {
var trackinfo = this.getmediainfo_();
if (!this.sourceupdater_ || !trackinfo) {
return videojs.createtimeranges();
}
if (this.loadertype_ === 'main') {
var hasaudio = trackinfo.hasaudio,
hasvideo = trackinfo.hasvideo,
ismuxed = trackinfo.ismuxed;
if (hasvideo && hasaudio && !this.audiodisabled_ && !ismuxed) {
return this.sourceupdater_.buffered();
}
if (hasvideo) {
return this.sourceupdater_.videobuffered();
}
} // one case that can be ignored for now is audio only with alt audio,
// as we don't yet have proper support for that.
return this.sourceupdater_.audiobuffered();
}
/**
* gets and sets init segment for the provided map
*
* @param {object} map
* the map object representing the init segment to get or set
* @param {boolean=} set
* if true, the init segment for the provided map should be saved
* @return {object}
* map object for desired init segment
*/
;
_proto.initsegmentformap = function initsegmentformap(map, set) {
if (set === void 0) {
set = false;
}
if (!map) {
return null;
}
var id = initsegmentid(map);
var storedmap = this.initsegments_[id];
if (set && !storedmap && map.bytes) {
this.initsegments_[id] = storedmap = {
resolveduri: map.resolveduri,
byterange: map.byterange,
bytes: map.bytes,
tracks: map.tracks,
timescales: map.timescales
};
}
return storedmap || map;
}
/**
* gets and sets key for the provided key
*
* @param {object} key
* the key object representing the key to get or set
* @param {boolean=} set
* if true, the key for the provided key should be saved
* @return {object}
* key object for desired key
*/
;
_proto.segmentkey = function segmentkey(key, set) {
if (set === void 0) {
set = false;
}
if (!key) {
return null;
}
var id = segmentkeyid(key);
var storedkey = this.keycache_[id]; // todo: we should use the http expires header to invalidate our cache per
// https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-6.2.3
if (this.cacheencryptionkeys_ && set && !storedkey && key.bytes) {
this.keycache_[id] = storedkey = {
resolveduri: key.resolveduri,
bytes: key.bytes
};
}
var result = {
resolveduri: (storedkey || key).resolveduri
};
if (storedkey) {
result.bytes = storedkey.bytes;
}
return result;
}
/**
* returns true if all configuration required for loading is present, otherwise false.
*
* @return {boolean} true if the all configuration is ready for loading
* @private
*/
;
_proto.couldbeginloading_ = function couldbeginloading_() {
return this.playlist_ && !this.paused();
}
/**
* load a playlist and start to fill the buffer
*/
;
_proto.load = function load() {
// un-pause
this.monitorbuffer_(); // if we don't have a playlist yet, keep waiting for one to be
// specified
if (!this.playlist_) {
return;
} // if all the configuration is ready, initialize and begin loading
if (this.state === 'init' && this.couldbeginloading_()) {
return this.init_();
} // if we're in the middle of processing a segment already, don't
// kick off an additional segment request
if (!this.couldbeginloading_() || this.state !== 'ready' && this.state !== 'init') {
return;
}
this.state = 'ready';
}
/**
* once all the starting parameters have been specified, begin
* operation. this method should only be invoked from the init
* state.
*
* @private
*/
;
_proto.init_ = function init_() {
this.state = 'ready'; // if this is the audio segment loader, and it hasn't been inited before, then any old
// audio data from the muxed content should be removed
this.reseteverything();
return this.monitorbuffer_();
}
/**
* set a playlist on the segment loader
*
* @param {playlistloader} media the playlist to set on the segment loader
*/
;
_proto.playlist = function playlist(newplaylist, options) {
if (options === void 0) {
options = {};
}
if (!newplaylist) {
return;
}
var oldplaylist = this.playlist_;
var segmentinfo = this.pendingsegment_;
this.playlist_ = newplaylist;
this.xhroptions_ = options; // when we haven't started playing yet, the start of a live playlist
// is always our zero-time so force a sync update each time the playlist
// is refreshed from the server
//
// use the init state to determine if playback has started, as the playlist sync info
// should be fixed once requests begin (as sync points are generated based on sync
// info), but not before then.
if (this.state === 'init') {
newplaylist.syncinfo = {
mediasequence: newplaylist.mediasequence,
time: 0
}; // setting the date time mapping means mapping the program date time (if available)
// to time 0 on the player's timeline. the playlist's syncinfo serves a similar
// purpose, mapping the initial mediasequence to time zero. since the syncinfo can
// be updated as the playlist is refreshed before the loader starts loading, the
// program date time mapping needs to be updated as well.
//
// this mapping is only done for the main loader because a program date time should
// map equivalently between playlists.
if (this.loadertype_ === 'main') {
this.synccontroller_.setdatetimemappingforstart(newplaylist);
}
}
var oldid = null;
if (oldplaylist) {
if (oldplaylist.id) {
oldid = oldplaylist.id;
} else if (oldplaylist.uri) {
oldid = oldplaylist.uri;
}
}
this.logger_("playlist update [" + oldid + " => " + (newplaylist.id || newplaylist.uri) + "]"); // in vod, this is always a rendition switch (or we updated our syncinfo above)
// in live, we always want to update with new playlists (including refreshes)
this.trigger('syncinfoupdate'); // if we were unpaused but waiting for a playlist, start
// buffering now
if (this.state === 'init' && this.couldbeginloading_()) {
return this.init_();
}
if (!oldplaylist || oldplaylist.uri !== newplaylist.uri) {
if (this.mediaindex !== null) {
// we must reset/resync the segment loader when we switch renditions and
// the segment loader is already synced to the previous rendition
// on playlist changes we want it to be possible to fetch
// at the buffer for vod but not for live. so we use resetloader
// for live and resyncloader for vod. we want this because
// if a playlist uses independent and non-independent segments/parts the
// buffer may not accurately reflect the next segment that we should try
// downloading.
if (!newplaylist.endlist) {
this.resetloader();
} else {
this.resyncloader();
}
}
this.currentmediainfo_ = void 0;
this.trigger('playlistupdate'); // the rest of this function depends on `oldplaylist` being defined
return;
} // we reloaded the same playlist so we are in a live scenario
// and we will likely need to adjust the mediaindex
var mediasequencediff = newplaylist.mediasequence - oldplaylist.mediasequence;
this.logger_("live window shift [" + mediasequencediff + "]"); // update the mediaindex on the segmentloader
// this is important because we can abort a request and this value must be
// equal to the last appended mediaindex
if (this.mediaindex !== null) {
this.mediaindex -= mediasequencediff; // this can happen if we are going to load the first segment, but get a playlist
// update during that. mediaindex would go from 0 to -1 if mediasequence in the
// new playlist was incremented by 1.
if (this.mediaindex < 0) {
this.mediaindex = null;
this.partindex = null;
} else {
var segment = this.playlist_.segments[this.mediaindex]; // partindex should remain the same for the same segment
// unless parts fell off of the playlist for this segment.
// in that case we need to reset partindex and resync
if (this.partindex && (!segment.parts || !segment.parts.length || !segment.parts[this.partindex])) {
var mediaindex = this.mediaindex;
this.logger_("currently processing part (index " + this.partindex + ") no longer exists.");
this.resetloader(); // we want to throw away the partindex and the data associated with it,
// as the part was dropped from our current playlists segment.
// the mediaindex will still be valid so keep that around.
this.mediaindex = mediaindex;
}
}
} // update the mediaindex on the segmentinfo object
// this is important because we will update this.mediaindex with this value
// in `handleappendsdone_` after the segment has been successfully appended
if (segmentinfo) {
segmentinfo.mediaindex -= mediasequencediff;
if (segmentinfo.mediaindex < 0) {
segmentinfo.mediaindex = null;
segmentinfo.partindex = null;
} else {
// we need to update the referenced segment so that timing information is
// saved for the new playlist's segment, however, if the segment fell off the
// playlist, we can leave the old reference and just lose the timing info
if (segmentinfo.mediaindex >= 0) {
segmentinfo.segment = newplaylist.segments[segmentinfo.mediaindex];
}
if (segmentinfo.partindex >= 0 && segmentinfo.segment.parts) {
segmentinfo.part = segmentinfo.segment.parts[segmentinfo.partindex];
}
}
}
this.synccontroller_.saveexpiredsegmentinfo(oldplaylist, newplaylist);
}
/**
* prevent the loader from fetching additional segments. if there
* is a segment request outstanding, it will finish processing
* before the loader halts. a segment loader can be unpaused by
* calling load().
*/
;
_proto.pause = function pause() {
if (this.checkbuffertimeout_) {
global_window__webpack_imported_module_0___default.a.cleartimeout(this.checkbuffertimeout_);
this.checkbuffertimeout_ = null;
}
}
/**
* returns whether the segment loader is fetching additional
* segments when given the opportunity. this property can be
* modified through calls to pause() and load().
*/
;
_proto.paused = function paused() {
return this.checkbuffertimeout_ === null;
}
/**
* delete all the buffered data and reset the segmentloader
*
* @param {function} [done] an optional callback to be executed when the remove
* operation is complete
*/
;
_proto.reseteverything = function reseteverything(done) {
this.ended_ = false;
this.activeinitsegmentid_ = null;
this.appendinitsegment_ = {
audio: true,
video: true
};
this.resetloader(); // remove from 0, the earliest point, to infinity, to signify removal of everything.
// vtt segment loader doesn't need to do anything but in the regular segmentloader,
// we then clamp the value to duration if necessary.
this.remove(0, infinity, done); // clears fmp4 captions
if (this.transmuxer_) {
this.transmuxer_.postmessage({
action: 'clearallmp4captions'
}); // reset the cache in the transmuxer
this.transmuxer_.postmessage({
action: 'reset'
});
}
}
/**
* force the segmentloader to resync and start loading around the currenttime instead
* of starting at the end of the buffer
*
* useful for fast quality changes
*/
;
_proto.resetloader = function resetloader() {
this.fetchatbuffer_ = false;
this.resyncloader();
}
/**
* force the segmentloader to restart synchronization and make a conservative guess
* before returning to the simple walk-forward method
*/
;
_proto.resyncloader = function resyncloader() {
if (this.transmuxer_) {
// need to clear out any cached data to prepare for the new segment
segmenttransmuxer.reset(this.transmuxer_);
}
this.mediaindex = null;
this.partindex = null;
this.syncpoint_ = null;
this.ispendingtimestampoffset_ = false;
this.callqueue_ = [];
this.loadqueue_ = [];
this.metadataqueue_.id3 = [];
this.metadataqueue_.caption = [];
this.abort();
if (this.transmuxer_) {
this.transmuxer_.postmessage({
action: 'clearparsedmp4captions'
});
}
}
/**
* remove any data in the source buffer between start and end times
*
* @param {number} start - the start time of the region to remove from the buffer
* @param {number} end - the end time of the region to remove from the buffer
* @param {function} [done] - an optional callback to be executed when the remove
* @param {boolean} force - force all remove operations to happen
* operation is complete
*/
;
_proto.remove = function remove(start, end, done, force) {
if (done === void 0) {
done = function done() {};
}
if (force === void 0) {
force = false;
} // clamp end to duration if we need to remove everything.
// this is due to a browser bug that causes issues if we remove to infinity.
// videojs/videojs-contrib-hls#1225
if (end === infinity) {
end = this.duration_();
} // skip removes that would throw an error
// commonly happens during a rendition switch at the start of a video
// from start 0 to end 0
if (end <= start) {
this.logger_('skipping remove because end ${end} is <= start ${start}');
return;
}
if (!this.sourceupdater_ || !this.getmediainfo_()) {
this.logger_('skipping remove because no source updater or starting media info'); // nothing to remove if we haven't processed any media
return;
} // set it to one to complete this function's removes
var removesremaining = 1;
var removefinished = function removefinished() {
removesremaining--;
if (removesremaining === 0) {
done();
}
};
if (force || !this.audiodisabled_) {
removesremaining++;
this.sourceupdater_.removeaudio(start, end, removefinished);
} // while it would be better to only remove video if the main loader has video, this
// should be safe with audio only as removevideo will call back even if there's no
// video buffer.
//
// in theory we can check to see if there's video before calling the remove, but in
// the event that we're switching between renditions and from video to audio only
// (when we add support for that), we may need to clear the video contents despite
// what the new media will contain.
if (force || this.loadertype_ === 'main') {
this.gopbuffer_ = removegopbuffer(this.gopbuffer_, start, end, this.timemapping_);
removesremaining++;
this.sourceupdater_.removevideo(start, end, removefinished);
} // remove any captions and id3 tags
for (var track in this.inbandtexttracks_) {
removecuesfromtrack(start, end, this.inbandtexttracks_[track]);
}
removecuesfromtrack(start, end, this.segmentmetadatatrack_); // finished this function's removes
removefinished();
}
/**
* (re-)schedule monitorbuffertick_ to run as soon as possible
*
* @private
*/
;
_proto.monitorbuffer_ = function monitorbuffer_() {
if (this.checkbuffertimeout_) {
global_window__webpack_imported_module_0___default.a.cleartimeout(this.checkbuffertimeout_);
}
this.checkbuffertimeout_ = global_window__webpack_imported_module_0___default.a.settimeout(this.monitorbuffertick_.bind(this), 1);
}
/**
* as long as the segmentloader is in the ready state, periodically
* invoke fillbuffer_().
*
* @private
*/
;
_proto.monitorbuffertick_ = function monitorbuffertick_() {
if (this.state === 'ready') {
this.fillbuffer_();
}
if (this.checkbuffertimeout_) {
global_window__webpack_imported_module_0___default.a.cleartimeout(this.checkbuffertimeout_);
}
this.checkbuffertimeout_ = global_window__webpack_imported_module_0___default.a.settimeout(this.monitorbuffertick_.bind(this), check_buffer_delay);
}
/**
* fill the buffer with segements unless the sourcebuffers are
* currently updating
*
* note: this function should only ever be called by monitorbuffer_
* and never directly
*
* @private
*/
;
_proto.fillbuffer_ = function fillbuffer_() {
// todo since the source buffer maintains a queue, and we shouldn't call this function
// except when we're ready for the next segment, this check can most likely be removed
if (this.sourceupdater_.updating()) {
return;
} // see if we need to begin loading immediately
var segmentinfo = this.choosenextrequest_();
if (!segmentinfo) {
return;
}
if (typeof segmentinfo.timestampoffset === 'number') {
this.ispendingtimestampoffset_ = false;
this.timelinechangecontroller_.pendingtimelinechange({
type: this.loadertype_,
from: this.currenttimeline_,
to: segmentinfo.timeline
});
}
this.loadsegment_(segmentinfo);
}
/**
* determines if we should call endofstream on the media source based
* on the state of the buffer or if appened segment was the final
* segment in the playlist.
*
* @param {number} [mediaindex] the media index of segment we last appended
* @param {object} [playlist] a media playlist object
* @return {boolean} do we need to call endofstream on the mediasource
*/
;
_proto.isendofstream_ = function isendofstream_(mediaindex, playlist, partindex) {
if (mediaindex === void 0) {
mediaindex = this.mediaindex;
}
if (playlist === void 0) {
playlist = this.playlist_;
}
if (partindex === void 0) {
partindex = this.partindex;
}
if (!playlist || !this.mediasource_) {
return false;
}
var segment = typeof mediaindex === 'number' && playlist.segments[mediaindex]; // mediaindex is zero based but length is 1 based
var appendedlastsegment = mediaindex + 1 === playlist.segments.length; // true if there are no parts, or this is the last part.
var appendedlastpart = !segment || !segment.parts || partindex + 1 === segment.parts.length; // if we've buffered to the end of the video, we need to call endofstream
// so that mediasources can trigger the `ended` event when it runs out of
// buffered data instead of waiting for me
return playlist.endlist && this.mediasource_.readystate === 'open' && appendedlastsegment && appendedlastpart;
}
/**
* determines what request should be made given current segment loader state.
*
* @return {object} a request object that describes the segment/part to load
*/
;
_proto.choosenextrequest_ = function choosenextrequest_() {
var buffered = this.buffered_();
var bufferedend = lastbufferedend(buffered) || 0;
var bufferedtime = timeaheadof(buffered, this.currenttime_());
var preloaded = !this.hasplayed_() && bufferedtime >= 1;
var haveenoughbuffer = bufferedtime >= this.goalbufferlength_();
var segments = this.playlist_.segments; // return no segment if:
// 1. we don't have segments
// 2. the video has not yet played and we already downloaded a segment
// 3. we already have enough buffered time
if (!segments.length || preloaded || haveenoughbuffer) {
return null;
}
this.syncpoint_ = this.syncpoint_ || this.synccontroller_.getsyncpoint(this.playlist_, this.duration_(), this.currenttimeline_, this.currenttime_());
var next = {
partindex: null,
mediaindex: null,
startofsegment: null,
playlist: this.playlist_,
issyncrequest: boolean(!this.syncpoint_)
};
if (next.issyncrequest) {
next.mediaindex = getsyncsegmentcandidate(this.currenttimeline_, segments, bufferedend);
} else if (this.mediaindex !== null) {
var segment = segments[this.mediaindex];
var partindex = typeof this.partindex === 'number' ? this.partindex : -1;
next.startofsegment = segment.end ? segment.end : bufferedend;
if (segment.parts && segment.parts[partindex + 1]) {
next.mediaindex = this.mediaindex;
next.partindex = partindex + 1;
} else {
next.mediaindex = this.mediaindex + 1;
}
} else {
// find the segment containing the end of the buffer or current time.
var _playlist$getmediainf = playlist.getmediainfofortime({
experimentalexactmanifesttimings: this.experimentalexactmanifesttimings,
playlist: this.playlist_,
currenttime: this.fetchatbuffer_ ? bufferedend : this.currenttime_(),
startingpartindex: this.syncpoint_.partindex,
startingsegmentindex: this.syncpoint_.segmentindex,
starttime: this.syncpoint_.time
}),
segmentindex = _playlist$getmediainf.segmentindex,
starttime = _playlist$getmediainf.starttime,
_partindex = _playlist$getmediainf.partindex;
next.getmediainfofortime = this.fetchatbuffer_ ? "bufferedend " + bufferedend : "currenttime " + this.currenttime_();
next.mediaindex = segmentindex;
next.startofsegment = starttime;
next.partindex = _partindex;
}
var nextsegment = segments[next.mediaindex];
var nextpart = nextsegment && typeof next.partindex === 'number' && nextsegment.parts && nextsegment.parts[next.partindex]; // if the next segment index is invalid or
// the next partindex is invalid do not choose a next segment.
if (!nextsegment || typeof next.partindex === 'number' && !nextpart) {
return null;
} // if the next segment has parts, and we don't have a partindex.
// set partindex to 0
if (typeof next.partindex !== 'number' && nextsegment.parts) {
next.partindex = 0;
nextpart = nextsegment.parts[0];
} // if we have no buffered data then we need to make sure
// that the next part we append is "independent" if possible.
// so we check if the previous part is independent, and request
// it if it is.
if (!bufferedtime && nextpart && !nextpart.independent) {
if (next.partindex === 0) {
var lastsegment = segments[next.mediaindex - 1];
var lastsegmentlastpart = lastsegment.parts && lastsegment.parts.length && lastsegment.parts[lastsegment.parts.length - 1];
if (lastsegmentlastpart && lastsegmentlastpart.independent) {
next.mediaindex -= 1;
next.partindex = lastsegment.parts.length - 1;
next.independent = 'previous segment';
}
} else if (nextsegment.parts[next.partindex - 1].independent) {
next.partindex -= 1;
next.independent = 'previous part';
}
}
var ended = this.mediasource_ && this.mediasource_.readystate === 'ended'; // do not choose a next segment if all of the following:
// 1. this is the last segment in the playlist
// 2. end of stream has been called on the media source already
// 3. the player is not seeking
if (next.mediaindex >= segments.length - 1 && ended && !this.seeking_()) {
return null;
}
return this.generatesegmentinfo_(next);
};
_proto.generatesegmentinfo_ = function generatesegmentinfo_(options) {
var independent = options.independent,
playlist = options.playlist,
mediaindex = options.mediaindex,
startofsegment = options.startofsegment,
issyncrequest = options.issyncrequest,
partindex = options.partindex,
forcetimestampoffset = options.forcetimestampoffset,
getmediainfofortime = options.getmediainfofortime;
var segment = playlist.segments[mediaindex];
var part = typeof partindex === 'number' && segment.parts[partindex];
var segmentinfo = {
requestid: 'segment-loader-' + math.random(),
// resolve the segment url relative to the playlist
uri: part && part.resolveduri || segment.resolveduri,
// the segment's mediaindex at the time it was requested
mediaindex: mediaindex,
partindex: part ? partindex : null,
// whether or not to update the segmentloader's state with this
// segment's mediaindex
issyncrequest: issyncrequest,
startofsegment: startofsegment,
// the segment's playlist
playlist: playlist,
// unencrypted bytes of the segment
bytes: null,
// when a key is defined for this segment, the encrypted bytes
encryptedbytes: null,
// the target timestampoffset for this segment when we append it
// to the source buffer
timestampoffset: null,
// the timeline that the segment is in
timeline: segment.timeline,
// the expected duration of the segment in seconds
duration: part && part.duration || segment.duration,
// retain the segment in case the playlist updates while doing an async process
segment: segment,
part: part,
bytelength: 0,
transmuxer: this.transmuxer_,
// type of getmediainfofortime that was used to get this segment
getmediainfofortime: getmediainfofortime,
independent: independent
};
var overridecheck = typeof forcetimestampoffset !== 'undefined' ? forcetimestampoffset : this.ispendingtimestampoffset_;
segmentinfo.timestampoffset = this.timestampoffsetforsegment_({
segmenttimeline: segment.timeline,
currenttimeline: this.currenttimeline_,
startofsegment: startofsegment,
buffered: this.buffered_(),
overridecheck: overridecheck
});
var audiobufferedend = lastbufferedend(this.sourceupdater_.audiobuffered());
if (typeof audiobufferedend === 'number') {
// since the transmuxer is using the actual timing values, but the buffer is
// adjusted by the timestamp offset, we must adjust the value here
segmentinfo.audioappendstart = audiobufferedend - this.sourceupdater_.audiotimestampoffset();
}
if (this.sourceupdater_.videobuffered().length) {
segmentinfo.gopstoalignwith = gopssafetoalignwith(this.gopbuffer_, // since the transmuxer is using the actual timing values, but the time is
// adjusted by the timestmap offset, we must adjust the value here
this.currenttime_() - this.sourceupdater_.videotimestampoffset(), this.timemapping_);
}
return segmentinfo;
} // get the timestampoffset for a segment,
// added so that vtt segment loader can override and prevent
// adding timestamp offsets.
;
_proto.timestampoffsetforsegment_ = function timestampoffsetforsegment_(options) {
return timestampoffsetforsegment(options);
}
/**
* determines if the network has enough bandwidth to complete the current segment
* request in a timely manner. if not, the request will be aborted early and bandwidth
* updated to trigger a playlist switch.
*
* @param {object} stats
* object containing stats about the request timing and size
* @private
*/
;
_proto.earlyabortwhenneeded_ = function earlyabortwhenneeded_(stats) {
if (this.vhs_.tech_.paused() || // don't abort if the current playlist is on the lowestenabledrendition
// todo: replace using timeout with a boolean indicating whether this playlist is
// the lowestenabledrendition.
!this.xhroptions_.timeout || // don't abort if we have no bandwidth information to estimate segment sizes
!this.playlist_.attributes.bandwidth) {
return;
} // wait at least 1 second since the first byte of data has been received before
// using the calculated bandwidth from the progress event to allow the bitrate
// to stabilize
if (date.now() - (stats.firstbytesreceivedat || date.now()) < 1000) {
return;
}
var currenttime = this.currenttime_();
var measuredbandwidth = stats.bandwidth;
var segmentduration = this.pendingsegment_.duration;
var requesttimeremaining = playlist.estimatesegmentrequesttime(segmentduration, measuredbandwidth, this.playlist_, stats.bytesreceived); // subtract 1 from the timeuntilrebuffer so we still consider an early abort
// if we are only left with less than 1 second when the request completes.
// a negative timeuntilrebuffering indicates we are already rebuffering
var timeuntilrebuffer$1 = timeuntilrebuffer(this.buffered_(), currenttime, this.vhs_.tech_.playbackrate()) - 1; // only consider aborting early if the estimated time to finish the download
// is larger than the estimated time until the player runs out of forward buffer
if (requesttimeremaining <= timeuntilrebuffer$1) {
return;
}
var switchcandidate = minrebuffermaxbandwidthselector({
master: this.vhs_.playlists.master,
currenttime: currenttime,
bandwidth: measuredbandwidth,
duration: this.duration_(),
segmentduration: segmentduration,
timeuntilrebuffer: timeuntilrebuffer$1,
currenttimeline: this.currenttimeline_,
synccontroller: this.synccontroller_
});
if (!switchcandidate) {
return;
}
var rebufferingimpact = requesttimeremaining - timeuntilrebuffer$1;
var timesavedbyswitching = rebufferingimpact - switchcandidate.rebufferingimpact;
var minimumtimesaving = 0.5; // if we are already rebuffering, increase the amount of variance we add to the
// potential round trip time of the new request so that we are not too aggressive
// with switching to a playlist that might save us a fraction of a second.
if (timeuntilrebuffer$1 <= time_fudge_factor) {
minimumtimesaving = 1;
}
if (!switchcandidate.playlist || switchcandidate.playlist.uri === this.playlist_.uri || timesavedbyswitching < minimumtimesaving) {
return;
} // set the bandwidth to that of the desired playlist being sure to scale by
// bandwidth_variance and add one so the playlist selector does not exclude it
// don't trigger a bandwidthupdate as the bandwidth is artifial
this.bandwidth = switchcandidate.playlist.attributes.bandwidth * config.bandwidth_variance + 1;
this.trigger('earlyabort');
};
_proto.handleabort_ = function handleabort_(segmentinfo) {
this.logger_("aborting " + segmentinfostring(segmentinfo));
this.mediarequestsaborted += 1;
}
/**
* xhr `progress` event handler
*
* @param {event}
* the xhr `progress` event
* @param {object} simplesegment
* a simplified segment object copy
* @private
*/
;
_proto.handleprogress_ = function handleprogress_(event, simplesegment) {
this.earlyabortwhenneeded_(simplesegment.stats);
if (this.checkforabort_(simplesegment.requestid)) {
return;
}
this.trigger('progress');
};
_proto.handletrackinfo_ = function handletrackinfo_(simplesegment, trackinfo) {
this.earlyabortwhenneeded_(simplesegment.stats);
if (this.checkforabort_(simplesegment.requestid)) {
return;
}
if (this.checkforillegalmediaswitch(trackinfo)) {
return;
}
trackinfo = trackinfo || {}; // when we have track info, determine what media types this loader is dealing with.
// guard against cases where we're not getting track info at all until we are
// certain that all streams will provide it.
if (!shallowequal(this.currentmediainfo_, trackinfo)) {
this.appendinitsegment_ = {
audio: true,
video: true
};
this.startingmediainfo_ = trackinfo;
this.currentmediainfo_ = trackinfo;
this.logger_('trackinfo update', trackinfo);
this.trigger('trackinfo');
} // trackinfo may cause an abort if the trackinfo
// causes a codec change to an unsupported codec.
if (this.checkforabort_(simplesegment.requestid)) {
return;
} // set trackinfo on the pending segment so that
// it can append.
this.pendingsegment_.trackinfo = trackinfo; // check if any calls were waiting on the track info
if (this.hasenoughinfotoappend_()) {
this.processcallqueue_();
}
};
_proto.handletiminginfo_ = function handletiminginfo_(simplesegment, mediatype, timetype, time) {
this.earlyabortwhenneeded_(simplesegment.stats);
if (this.checkforabort_(simplesegment.requestid)) {
return;
}
var segmentinfo = this.pendingsegment_;
var timinginfoproperty = timinginfopropertyformedia(mediatype);
segmentinfo[timinginfoproperty] = segmentinfo[timinginfoproperty] || {};
segmentinfo[timinginfoproperty][timetype] = time;
this.logger_("timinginfo: " + mediatype + " - " + timetype + " - " + time); // check if any calls were waiting on the timing info
if (this.hasenoughinfotoappend_()) {
this.processcallqueue_();
}
};
_proto.handlecaptions_ = function handlecaptions_(simplesegment, captiondata) {
var _this2 = this;
this.earlyabortwhenneeded_(simplesegment.stats);
if (this.checkforabort_(simplesegment.requestid)) {
return;
} // this could only happen with fmp4 segments, but
// should still not happen in general
if (captiondata.length === 0) {
this.logger_('segmentloader received no captions from a caption event');
return;
}
var segmentinfo = this.pendingsegment_; // wait until we have some video data so that caption timing
// can be adjusted by the timestamp offset
if (!segmentinfo.hasappendeddata_) {
this.metadataqueue_.caption.push(this.handlecaptions_.bind(this, simplesegment, captiondata));
return;
}
var timestampoffset = this.sourceupdater_.videotimestampoffset() === null ? this.sourceupdater_.audiotimestampoffset() : this.sourceupdater_.videotimestampoffset();
var captiontracks = {}; // get total start/end and captions for each track/stream
captiondata.foreach(function (caption) {
// caption.stream is actually a track name...
// set to the existing values in tracks or default values
captiontracks[caption.stream] = captiontracks[caption.stream] || {
// infinity, as any other value will be less than this
starttime: infinity,
captions: [],
// 0 as an other value will be more than this
endtime: 0
};
var captiontrack = captiontracks[caption.stream];
captiontrack.starttime = math.min(captiontrack.starttime, caption.starttime + timestampoffset);
captiontrack.endtime = math.max(captiontrack.endtime, caption.endtime + timestampoffset);
captiontrack.captions.push(caption);
});
object.keys(captiontracks).foreach(function (trackname) {
var _captiontracks$trackn = captiontracks[trackname],
starttime = _captiontracks$trackn.starttime,
endtime = _captiontracks$trackn.endtime,
captions = _captiontracks$trackn.captions;
var inbandtexttracks = _this2.inbandtexttracks_;
_this2.logger_("adding cues from " + starttime + " -> " + endtime + " for " + trackname);
createcaptionstrackifnotexists(inbandtexttracks, _this2.vhs_.tech_, trackname); // clear out any cues that start and end at the same time period for the same track.
// we do this because a rendition change that also changes the timescale for captions
// will result in captions being re-parsed for certain segments. if we add them again
// without clearing we will have two of the same captions visible.
removecuesfromtrack(starttime, endtime, inbandtexttracks[trackname]);
addcaptiondata({
captionarray: captions,
inbandtexttracks: inbandtexttracks,
timestampoffset: timestampoffset
});
}); // reset stored captions since we added parsed
// captions to a text track at this point
if (this.transmuxer_) {
this.transmuxer_.postmessage({
action: 'clearparsedmp4captions'
});
}
};
_proto.handleid3_ = function handleid3_(simplesegment, id3frames, dispatchtype) {
this.earlyabortwhenneeded_(simplesegment.stats);
if (this.checkforabort_(simplesegment.requestid)) {
return;
}
var segmentinfo = this.pendingsegment_; // we need to have appended data in order for the timestamp offset to be set
if (!segmentinfo.hasappendeddata_) {
this.metadataqueue_.id3.push(this.handleid3_.bind(this, simplesegment, id3frames, dispatchtype));
return;
}
var timestampoffset = this.sourceupdater_.videotimestampoffset() === null ? this.sourceupdater_.audiotimestampoffset() : this.sourceupdater_.videotimestampoffset(); // there's potentially an issue where we could double add metadata if there's a muxed
// audio/video source with a metadata track, and an alt audio with a metadata track.
// however, this probably won't happen, and if it does it can be handled then.
createmetadatatrackifnotexists(this.inbandtexttracks_, dispatchtype, this.vhs_.tech_);
addmetadata({
inbandtexttracks: this.inbandtexttracks_,
metadataarray: id3frames,
timestampoffset: timestampoffset,
videoduration: this.duration_()
});
};
_proto.processmetadataqueue_ = function processmetadataqueue_() {
this.metadataqueue_.id3.foreach(function (fn) {
return fn();
});
this.metadataqueue_.caption.foreach(function (fn) {
return fn();
});
this.metadataqueue_.id3 = [];
this.metadataqueue_.caption = [];
};
_proto.processcallqueue_ = function processcallqueue_() {
var callqueue = this.callqueue_; // clear out the queue before the queued functions are run, since some of the
// functions may check the length of the load queue and default to pushing themselves
// back onto the queue.
this.callqueue_ = [];
callqueue.foreach(function (fun) {
return fun();
});
};
_proto.processloadqueue_ = function processloadqueue_() {
var loadqueue = this.loadqueue_; // clear out the queue before the queued functions are run, since some of the
// functions may check the length of the load queue and default to pushing themselves
// back onto the queue.
this.loadqueue_ = [];
loadqueue.foreach(function (fun) {
return fun();
});
}
/**
* determines whether the loader has enough info to load the next segment.
*
* @return {boolean}
* whether or not the loader has enough info to load the next segment
*/
;
_proto.hasenoughinfotoload_ = function hasenoughinfotoload_() {
// since primary timing goes by video, only the audio loader potentially needs to wait
// to load.
if (this.loadertype_ !== 'audio') {
return true;
}
var segmentinfo = this.pendingsegment_; // a fill buffer must have already run to establish a pending segment before there's
// enough info to load.
if (!segmentinfo) {
return false;
} // the first segment can and should be loaded immediately so that source buffers are
// created together (before appending). source buffer creation uses the presence of
// audio and video data to determine whether to create audio/video source buffers, and
// uses processed (transmuxed or parsed) media to determine the types required.
if (!this.getcurrentmediainfo_()) {
return true;
}
if ( // technically, instead of waiting to load a segment on timeline changes, a segment
// can be requested and downloaded and only wait before it is transmuxed or parsed.
// but in practice, there are a few reasons why it is better to wait until a loader
// is ready to append that segment before requesting and downloading:
//
// 1. because audio and main loaders cross discontinuities together, if this loader
// is waiting for the other to catch up, then instead of requesting another
// segment and using up more bandwidth, by not yet loading, more bandwidth is
// allotted to the loader currently behind.
// 2. media-segment-request doesn't have to have logic to consider whether a segment
// is ready to be processed or not, isolating the queueing behavior to the loader.
// 3. the audio loader bases some of its segment properties on timing information
// provided by the main loader, meaning that, if the logic for waiting on
// processing was in media-segment-request, then it would also need to know how
// to re-generate the segment information after the main loader caught up.
shouldwaitfortimelinechange({
timelinechangecontroller: this.timelinechangecontroller_,
currenttimeline: this.currenttimeline_,
segmenttimeline: segmentinfo.timeline,
loadertype: this.loadertype_,
audiodisabled: this.audiodisabled_
})) {
return false;
}
return true;
};
_proto.getcurrentmediainfo_ = function getcurrentmediainfo_(segmentinfo) {
if (segmentinfo === void 0) {
segmentinfo = this.pendingsegment_;
}
return segmentinfo && segmentinfo.trackinfo || this.currentmediainfo_;
};
_proto.getmediainfo_ = function getmediainfo_(segmentinfo) {
if (segmentinfo === void 0) {
segmentinfo = this.pendingsegment_;
}
return this.getcurrentmediainfo_(segmentinfo) || this.startingmediainfo_;
};
_proto.getpendingsegmentplaylist = function getpendingsegmentplaylist() {
return this.pendingsegment_ ? this.pendingsegment_.playlist : null;
};
_proto.hasenoughinfotoappend_ = function hasenoughinfotoappend_() {
if (!this.sourceupdater_.ready()) {
return false;
} // if content needs to be removed or the loader is waiting on an append reattempt,
// then no additional content should be appended until the prior append is resolved.
if (this.waitingonremove_ || this.quotaexceedederrorretrytimeout_) {
return false;
}
var segmentinfo = this.pendingsegment_;
var trackinfo = this.getcurrentmediainfo_(); // no segment to append any data for or
// we do not have information on this specific
// segment yet
if (!segmentinfo || !trackinfo) {
return false;
}
var hasaudio = trackinfo.hasaudio,
hasvideo = trackinfo.hasvideo,
ismuxed = trackinfo.ismuxed;
if (hasvideo && !segmentinfo.videotiminginfo) {
return false;
} // muxed content only relies on video timing information for now.
if (hasaudio && !this.audiodisabled_ && !ismuxed && !segmentinfo.audiotiminginfo) {
return false;
}
if (shouldwaitfortimelinechange({
timelinechangecontroller: this.timelinechangecontroller_,
currenttimeline: this.currenttimeline_,
segmenttimeline: segmentinfo.timeline,
loadertype: this.loadertype_,
audiodisabled: this.audiodisabled_
})) {
return false;
}
return true;
};
_proto.handledata_ = function handledata_(simplesegment, result) {
this.earlyabortwhenneeded_(simplesegment.stats);
if (this.checkforabort_(simplesegment.requestid)) {
return;
} // if there's anything in the call queue, then this data came later and should be
// executed after the calls currently queued.
if (this.callqueue_.length || !this.hasenoughinfotoappend_()) {
this.callqueue_.push(this.handledata_.bind(this, simplesegment, result));
return;
}
var segmentinfo = this.pendingsegment_; // update the time mapping so we can translate from display time to media time
this.settimemapping_(segmentinfo.timeline); // for tracking overall stats
this.updatemediasecondsloaded_(segmentinfo.part || segmentinfo.segment); // note that the state isn't changed from loading to appending. this is because abort
// logic may change behavior depending on the state, and changing state too early may
// inflate our estimates of bandwidth. in the future this should be re-examined to
// note more granular states.
// don't process and append data if the mediasource is closed
if (this.mediasource_.readystate === 'closed') {
return;
} // if this request included an initialization segment, save that data
// to the initsegment cache
if (simplesegment.map) {
simplesegment.map = this.initsegmentformap(simplesegment.map, true); // move over init segment properties to media request
segmentinfo.segment.map = simplesegment.map;
} // if this request included a segment key, save that data in the cache
if (simplesegment.key) {
this.segmentkey(simplesegment.key, true);
}
segmentinfo.isfmp4 = simplesegment.isfmp4;
segmentinfo.timinginfo = segmentinfo.timinginfo || {};
if (segmentinfo.isfmp4) {
this.trigger('fmp4');
segmentinfo.timinginfo.start = segmentinfo[timinginfopropertyformedia(result.type)].start;
} else {
var trackinfo = this.getcurrentmediainfo_();
var usevideotiminginfo = this.loadertype_ === 'main' && trackinfo && trackinfo.hasvideo;
var firstvideoframetimefordata;
if (usevideotiminginfo) {
firstvideoframetimefordata = segmentinfo.videotiminginfo.start;
} // segment loader knows more about segment timing than the transmuxer (in certain
// aspects), so make any changes required for a more accurate start time.
// don't set the end time yet, as the segment may not be finished processing.
segmentinfo.timinginfo.start = this.truesegmentstart_({
currentstart: segmentinfo.timinginfo.start,
playlist: segmentinfo.playlist,
mediaindex: segmentinfo.mediaindex,
currentvideotimestampoffset: this.sourceupdater_.videotimestampoffset(),
usevideotiminginfo: usevideotiminginfo,
firstvideoframetimefordata: firstvideoframetimefordata,
videotiminginfo: segmentinfo.videotiminginfo,
audiotiminginfo: segmentinfo.audiotiminginfo
});
} // init segments for audio and video only need to be appended in certain cases. now
// that data is about to be appended, we can check the final cases to determine
// whether we should append an init segment.
this.updateappendinitsegmentstatus(segmentinfo, result.type); // timestamp offset should be updated once we get new data and have its timing info,
// as we use the start of the segment to offset the best guess (playlist provided)
// timestamp offset.
this.updatesourcebuffertimestampoffset_(segmentinfo); // if this is a sync request we need to determine whether it should
// be appended or not.
if (segmentinfo.issyncrequest) {
// first save/update our timing info for this segment.
// this is what allows us to choose an accurate segment
// and the main reason we make a sync request.
this.updatetiminginfoend_(segmentinfo);
this.synccontroller_.savesegmenttiminginfo({
segmentinfo: segmentinfo,
shouldsavetimelinemapping: this.loadertype_ === 'main'
});
var next = this.choosenextrequest_(); // if the sync request isn't the segment that would be requested next
// after taking into account its timing info, do not append it.
if (next.mediaindex !== segmentinfo.mediaindex || next.partindex !== segmentinfo.partindex) {
this.logger_('sync segment was incorrect, not appending');
return;
} // otherwise append it like any other segment as our guess was correct.
this.logger_('sync segment was correct, appending');
} // save some state so that in the future anything waiting on first append (and/or
// timestamp offset(s)) can process immediately. while the extra state isn't optimal,
// we need some notion of whether the timestamp offset or other relevant information
// has had a chance to be set.
segmentinfo.hasappendeddata_ = true; // now that the timestamp offset should be set, we can append any waiting id3 tags.
this.processmetadataqueue_();
this.appenddata_(segmentinfo, result);
};
_proto.updateappendinitsegmentstatus = function updateappendinitsegmentstatus(segmentinfo, type) {
// alt audio doesn't manage timestamp offset
if (this.loadertype_ === 'main' && typeof segmentinfo.timestampoffset === 'number' && // in the case that we're handling partial data, we don't want to append an init
// segment for each chunk
!segmentinfo.changedtimestampoffset) {
// if the timestamp offset changed, the timeline may have changed, so we have to re-
// append init segments
this.appendinitsegment_ = {
audio: true,
video: true
};
}
if (this.playlistoflastinitsegment_[type] !== segmentinfo.playlist) {
// make sure we append init segment on playlist changes, in case the media config
// changed
this.appendinitsegment_[type] = true;
}
};
_proto.getinitsegmentandupdatestate_ = function getinitsegmentandupdatestate_(_ref4) {
var type = _ref4.type,
initsegment = _ref4.initsegment,
map = _ref4.map,
playlist = _ref4.playlist; // "the ext-x-map tag specifies how to obtain the media initialization section
// (section 3) required to parse the applicable media segments. it applies to every
// media segment that appears after it in the playlist until the next ext-x-map tag
// or until the end of the playlist."
// https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.2.5
if (map) {
var id = initsegmentid(map);
if (this.activeinitsegmentid_ === id) {
// don't need to re-append the init segment if the id matches
return null;
} // a map-specified init segment takes priority over any transmuxed (or otherwise
// obtained) init segment
//
// this also caches the init segment for later use
initsegment = this.initsegmentformap(map, true).bytes;
this.activeinitsegmentid_ = id;
} // we used to always prepend init segments for video, however, that shouldn't be
// necessary. instead, we should only append on changes, similar to what we've always
// done for audio. this is more important (though may not be that important) for
// frame-by-frame appending for lhls, simply because of the increased quantity of
// appends.
if (initsegment && this.appendinitsegment_[type]) {
// make sure we track the playlist that we last used for the init segment, so that
// we can re-append the init segment in the event that we get data from a new
// playlist. discontinuities and track changes are handled in other sections.
this.playlistoflastinitsegment_[type] = playlist; // disable future init segment appends for this type. until a change is necessary.
this.appendinitsegment_[type] = false; // we need to clear out the fmp4 active init segment id, since
// we are appending the muxer init segment
this.activeinitsegmentid_ = null;
return initsegment;
}
return null;
};
_proto.handlequotaexceedederror_ = function handlequotaexceedederror_(_ref5, error) {
var _this3 = this;
var segmentinfo = _ref5.segmentinfo,
type = _ref5.type,
bytes = _ref5.bytes;
var audiobuffered = this.sourceupdater_.audiobuffered();
var videobuffered = this.sourceupdater_.videobuffered(); // for now we're ignoring any notion of gaps in the buffer, but they, in theory,
// should be cleared out during the buffer removals. however, log in case it helps
// debug.
if (audiobuffered.length > 1) {
this.logger_('on quota_exceeded_err, found gaps in the audio buffer: ' + timerangestoarray(audiobuffered).join(', '));
}
if (videobuffered.length > 1) {
this.logger_('on quota_exceeded_err, found gaps in the video buffer: ' + timerangestoarray(videobuffered).join(', '));
}
var audiobufferstart = audiobuffered.length ? audiobuffered.start(0) : 0;
var audiobufferend = audiobuffered.length ? audiobuffered.end(audiobuffered.length - 1) : 0;
var videobufferstart = videobuffered.length ? videobuffered.start(0) : 0;
var videobufferend = videobuffered.length ? videobuffered.end(videobuffered.length - 1) : 0;
if (audiobufferend - audiobufferstart <= min_back_buffer && videobufferend - videobufferstart <= min_back_buffer) {
// can't remove enough buffer to make room for new segment (or the browser doesn't
// allow for appends of segments this size). in the future, it may be possible to
// split up the segment and append in pieces, but for now, error out this playlist
// in an attempt to switch to a more manageable rendition.
this.logger_('on quota_exceeded_err, single segment too large to append to ' + 'buffer, triggering an error. ' + ("appended byte length: " + bytes.bytelength + ", ") + ("audio buffer: " + timerangestoarray(audiobuffered).join(', ') + ", ") + ("video buffer: " + timerangestoarray(videobuffered).join(', ') + ", "));
this.error({
message: 'quota exceeded error with append of a single segment of content',
excludeuntil: infinity
});
this.trigger('error');
return;
} // to try to resolve the quota exceeded error, clear back buffer and retry. this means
// that the segment-loader should block on future events until this one is handled, so
// that it doesn't keep moving onto further segments. adding the call to the call
// queue will prevent further appends until waitingonremove_ and
// quotaexceedederrorretrytimeout_ are cleared.
//
// note that this will only block the current loader. in the case of demuxed content,
// the other load may keep filling as fast as possible. in practice, this should be
// ok, as it is a rare case when either audio has a high enough bitrate to fill up a
// source buffer, or video fills without enough room for audio to append (and without
// the availability of clearing out seconds of back buffer to make room for audio).
// but it might still be good to handle this case in the future as a todo.
this.waitingonremove_ = true;
this.callqueue_.push(this.appendtosourcebuffer_.bind(this, {
segmentinfo: segmentinfo,
type: type,
bytes: bytes
}));
var currenttime = this.currenttime_(); // try to remove as much audio and video as possible to make room for new content
// before retrying.
var timetoremoveuntil = currenttime - min_back_buffer;
this.logger_("on quota_exceeded_err, removing audio/video from 0 to " + timetoremoveuntil);
this.remove(0, timetoremoveuntil, function () {
_this3.logger_("on quota_exceeded_err, retrying append in " + min_back_buffer + "s");
_this3.waitingonremove_ = false; // wait the length of time alotted in the back buffer to prevent wasted
// attempts (since we can't clear less than the minimum)
_this3.quotaexceedederrorretrytimeout_ = global_window__webpack_imported_module_0___default.a.settimeout(function () {
_this3.logger_('on quota_exceeded_err, re-processing call queue');
_this3.quotaexceedederrorretrytimeout_ = null;
_this3.processcallqueue_();
}, min_back_buffer * 1000);
}, true);
};
_proto.handleappenderror_ = function handleappenderror_(_ref6, error) {
var segmentinfo = _ref6.segmentinfo,
type = _ref6.type,
bytes = _ref6.bytes; // if there's no error, nothing to do
if (!error) {
return;
}
if (error.code === quota_exceeded_err) {
this.handlequotaexceedederror_({
segmentinfo: segmentinfo,
type: type,
bytes: bytes
}); // a quota exceeded error should be recoverable with a future re-append, so no need
// to trigger an append error.
return;
}
this.logger_('received non quota_exceeded_err on append', error);
this.error(type + " append of " + bytes.length + "b failed for segment " + ("#" + segmentinfo.mediaindex + " in playlist " + segmentinfo.playlist.id)); // if an append errors, we often can't recover.
// (see https://w3c.github.io/media-source/#sourcebuffer-append-error).
//
// trigger a special error so that it can be handled separately from normal,
// recoverable errors.
this.trigger('appenderror');
};
_proto.appendtosourcebuffer_ = function appendtosourcebuffer_(_ref7) {
var segmentinfo = _ref7.segmentinfo,
type = _ref7.type,
initsegment = _ref7.initsegment,
data = _ref7.data,
bytes = _ref7.bytes; // if this is a re-append, bytes were already created and don't need to be recreated
if (!bytes) {
var segments = [data];
var bytelength = data.bytelength;
if (initsegment) {
// if the media initialization segment is changing, append it before the content
// segment
segments.unshift(initsegment);
bytelength += initsegment.bytelength;
} // technically we should be ok appending the init segment separately, however, we
// haven't yet tested that, and prepending is how we have always done things.
bytes = concatsegments({
bytes: bytelength,
segments: segments
});
}
this.sourceupdater_.appendbuffer({
segmentinfo: segmentinfo,
type: type,
bytes: bytes
}, this.handleappenderror_.bind(this, {
segmentinfo: segmentinfo,
type: type,
bytes: bytes
}));
};
_proto.handlesegmenttiminginfo_ = function handlesegmenttiminginfo_(type, requestid, segmenttiminginfo) {
if (!this.pendingsegment_ || requestid !== this.pendingsegment_.requestid) {
return;
}
var segment = this.pendingsegment_.segment;
var timinginfoproperty = type + "timinginfo";
if (!segment[timinginfoproperty]) {
segment[timinginfoproperty] = {};
}
segment[timinginfoproperty].transmuxerprependedseconds = segmenttiminginfo.prependedcontentduration || 0;
segment[timinginfoproperty].transmuxedpresentationstart = segmenttiminginfo.start.presentation;
segment[timinginfoproperty].transmuxeddecodestart = segmenttiminginfo.start.decode;
segment[timinginfoproperty].transmuxedpresentationend = segmenttiminginfo.end.presentation;
segment[timinginfoproperty].transmuxeddecodeend = segmenttiminginfo.end.decode; // mainly used as a reference for debugging
segment[timinginfoproperty].basemediadecodetime = segmenttiminginfo.basemediadecodetime;
};
_proto.appenddata_ = function appenddata_(segmentinfo, result) {
var type = result.type,
data = result.data;
if (!data || !data.bytelength) {
return;
}
if (type === 'audio' && this.audiodisabled_) {
return;
}
var initsegment = this.getinitsegmentandupdatestate_({
type: type,
initsegment: result.initsegment,
playlist: segmentinfo.playlist,
map: segmentinfo.isfmp4 ? segmentinfo.segment.map : null
});
this.appendtosourcebuffer_({
segmentinfo: segmentinfo,
type: type,
initsegment: initsegment,
data: data
});
}
/**
* load a specific segment from a request into the buffer
*
* @private
*/
;
_proto.loadsegment_ = function loadsegment_(segmentinfo) {
var _this4 = this;
this.state = 'waiting';
this.pendingsegment_ = segmentinfo;
this.trimbackbuffer_(segmentinfo);
if (typeof segmentinfo.timestampoffset === 'number') {
if (this.transmuxer_) {
this.transmuxer_.postmessage({
action: 'clearallmp4captions'
});
}
}
if (!this.hasenoughinfotoload_()) {
this.loadqueue_.push(function () {
// regenerate the audioappendstart, timestampoffset, etc as they
// may have changed since this function was added to the queue.
var options = _babel_runtime_helpers_extends__webpack_imported_module_2___default()({}, segmentinfo, {
forcetimestampoffset: true
});
_babel_runtime_helpers_extends__webpack_imported_module_2___default()(segmentinfo, _this4.generatesegmentinfo_(options));
_this4.ispendingtimestampoffset_ = false;
_this4.updatetransmuxerandrequestsegment_(segmentinfo);
});
return;
}
this.updatetransmuxerandrequestsegment_(segmentinfo);
};
_proto.updatetransmuxerandrequestsegment_ = function updatetransmuxerandrequestsegment_(segmentinfo) {
var _this5 = this; // we'll update the source buffer's timestamp offset once we have transmuxed data, but
// the transmuxer still needs to be updated before then.
//
// even though keeporiginaltimestamps is set to true for the transmuxer, timestamp
// offset must be passed to the transmuxer for stream correcting adjustments.
if (this.shouldupdatetransmuxertimestampoffset_(segmentinfo.timestampoffset)) {
this.gopbuffer_.length = 0; // gopstoalignwith was set before the gop buffer was cleared
segmentinfo.gopstoalignwith = [];
this.timemapping_ = 0; // reset values in the transmuxer since a discontinuity should start fresh
this.transmuxer_.postmessage({
action: 'reset'
});
this.transmuxer_.postmessage({
action: 'settimestampoffset',
timestampoffset: segmentinfo.timestampoffset
});
}
var simplesegment = this.createsimplifiedsegmentobj_(segmentinfo);
var isendofstream = this.isendofstream_(segmentinfo.mediaindex, segmentinfo.playlist, segmentinfo.partindex);
var iswalkingforward = this.mediaindex !== null;
var isdiscontinuity = segmentinfo.timeline !== this.currenttimeline_ && // currenttimeline starts at -1, so we shouldn't end the timeline switching to 0,
// the first timeline
segmentinfo.timeline > 0;
var isendoftimeline = isendofstream || iswalkingforward && isdiscontinuity;
this.logger_("requesting " + segmentinfostring(segmentinfo)); // if there's an init segment associated with this segment, but it is not cached (identified by a lack of bytes),
// then this init segment has never been seen before and should be appended.
//
// at this point the content type (audio/video or both) is not yet known, but it should be safe to set
// both to true and leave the decision of whether to append the init segment to append time.
if (simplesegment.map && !simplesegment.map.bytes) {
this.logger_('going to request init segment.');
this.appendinitsegment_ = {
video: true,
audio: true
};
}
segmentinfo.abortrequests = mediasegmentrequest({
xhr: this.vhs_.xhr,
xhroptions: this.xhroptions_,
decryptionworker: this.decrypter_,
segment: simplesegment,
abortfn: this.handleabort_.bind(this, segmentinfo),
progressfn: this.handleprogress_.bind(this),
trackinfofn: this.handletrackinfo_.bind(this),
timinginfofn: this.handletiminginfo_.bind(this),
videosegmenttiminginfofn: this.handlesegmenttiminginfo_.bind(this, 'video', segmentinfo.requestid),
audiosegmenttiminginfofn: this.handlesegmenttiminginfo_.bind(this, 'audio', segmentinfo.requestid),
captionsfn: this.handlecaptions_.bind(this),
isendoftimeline: isendoftimeline,
endedtimelinefn: function endedtimelinefn() {
_this5.logger_('received endedtimeline callback');
},
id3fn: this.handleid3_.bind(this),
datafn: this.handledata_.bind(this),
donefn: this.segmentrequestfinished_.bind(this),
ontransmuxerlog: function ontransmuxerlog(_ref8) {
var message = _ref8.message,
level = _ref8.level,
stream = _ref8.stream;
_this5.logger_(segmentinfostring(segmentinfo) + " logged from transmuxer stream " + stream + " as a " + level + ": " + message);
}
});
}
/**
* trim the back buffer so that we don't have too much data
* in the source buffer
*
* @private
*
* @param {object} segmentinfo - the current segment
*/
;
_proto.trimbackbuffer_ = function trimbackbuffer_(segmentinfo) {
var removetotime = safebackbuffertrimtime(this.seekable_(), this.currenttime_(), this.playlist_.targetduration || 10); // chrome has a hard limit of 150mb of
// buffer and a very conservative "garbage collector"
// we manually clear out the old buffer to ensure
// we don't trigger the quotaexceeded error
// on the source buffer during subsequent appends
if (removetotime > 0) {
this.remove(0, removetotime);
}
}
/**
* created a simplified copy of the segment object with just the
* information necessary to perform the xhr and decryption
*
* @private
*
* @param {object} segmentinfo - the current segment
* @return {object} a simplified segment object copy
*/
;
_proto.createsimplifiedsegmentobj_ = function createsimplifiedsegmentobj_(segmentinfo) {
var segment = segmentinfo.segment;
var part = segmentinfo.part;
var simplesegment = {
resolveduri: part ? part.resolveduri : segment.resolveduri,
byterange: part ? part.byterange : segment.byterange,
requestid: segmentinfo.requestid,
transmuxer: segmentinfo.transmuxer,
audioappendstart: segmentinfo.audioappendstart,
gopstoalignwith: segmentinfo.gopstoalignwith,
part: segmentinfo.part
};
var previoussegment = segmentinfo.playlist.segments[segmentinfo.mediaindex - 1];
if (previoussegment && previoussegment.timeline === segment.timeline) {
// the basestarttime of a segment is used to handle rollover when probing the ts
// segment to retrieve timing information. since the probe only looks at the media's
// times (e.g., pts and dts values of the segment), and doesn't consider the
// player's time (e.g., player.currenttime()), basestarttime should reflect the
// media time as well. transmuxeddecodeend represents the end time of a segment, in
// seconds of media time, so should be used here. the previous segment is used since
// the end of the previous segment should represent the beginning of the current
// segment, so long as they are on the same timeline.
if (previoussegment.videotiminginfo) {
simplesegment.basestarttime = previoussegment.videotiminginfo.transmuxeddecodeend;
} else if (previoussegment.audiotiminginfo) {
simplesegment.basestarttime = previoussegment.audiotiminginfo.transmuxeddecodeend;
}
}
if (segment.key) {
// if the media sequence is greater than 2^32, the iv will be incorrect
// assuming 10s segments, that would be about 1300 years
var iv = segment.key.iv || new uint32array([0, 0, 0, segmentinfo.mediaindex + segmentinfo.playlist.mediasequence]);
simplesegment.key = this.segmentkey(segment.key);
simplesegment.key.iv = iv;
}
if (segment.map) {
simplesegment.map = this.initsegmentformap(segment.map);
}
return simplesegment;
};
_proto.savetransferstats_ = function savetransferstats_(stats) {
// every request counts as a media request even if it has been aborted
// or canceled due to a timeout
this.mediarequests += 1;
if (stats) {
this.mediabytestransferred += stats.bytesreceived;
this.mediatransferduration += stats.roundtriptime;
}
};
_proto.savebandwidthrelatedstats_ = function savebandwidthrelatedstats_(duration, stats) {
// bytelength will be used for throughput, and should be based on bytes receieved,
// which we only know at the end of the request and should reflect total bytes
// downloaded rather than just bytes processed from components of the segment
this.pendingsegment_.bytelength = stats.bytesreceived;
if (duration < min_segment_duration_to_save_stats) {
this.logger_("ignoring segment's bandwidth because its duration of " + duration + (" is less than the min to record " + min_segment_duration_to_save_stats));
return;
}
this.bandwidth = stats.bandwidth;
this.roundtrip = stats.roundtriptime;
};
_proto.handletimeout_ = function handletimeout_() {
// although the vtt segment loader bandwidth isn't really used, it's good to
// maintain functinality between segment loaders
this.mediarequeststimedout += 1;
this.bandwidth = 1;
this.roundtrip = nan;
this.trigger('bandwidthupdate');
this.trigger('timeout');
}
/**
* handle the callback from the segmentrequest function and set the
* associated segmentloader state and errors if necessary
*
* @private
*/
;
_proto.segmentrequestfinished_ = function segmentrequestfinished_(error, simplesegment, result) {
// todo handle special cases, e.g., muxed audio/video but only audio in the segment
// check the call queue directly since this function doesn't need to deal with any
// data, and can continue even if the source buffers are not set up and we didn't get
// any data from the segment
if (this.callqueue_.length) {
this.callqueue_.push(this.segmentrequestfinished_.bind(this, error, simplesegment, result));
return;
}
this.savetransferstats_(simplesegment.stats); // the request was aborted and the segmentloader has already been reset
if (!this.pendingsegment_) {
return;
} // the request was aborted and the segmentloader has already started
// another request. this can happen when the timeout for an aborted
// request triggers due to a limitation in the xhr library
// do not count this as any sort of request or we risk double-counting
if (simplesegment.requestid !== this.pendingsegment_.requestid) {
return;
} // an error occurred from the active pendingsegment_ so reset everything
if (error) {
this.pendingsegment_ = null;
this.state = 'ready'; // aborts are not a true error condition and nothing corrective needs to be done
if (error.code === request_errors.aborted) {
return;
}
this.pause(); // the error is really just that at least one of the requests timed-out
// set the bandwidth to a very low value and trigger an abr switch to
// take emergency action
if (error.code === request_errors.timeout) {
this.handletimeout_();
return;
} // if control-flow has arrived here, then the error is real
// emit an error event to blacklist the current playlist
this.mediarequestserrored += 1;
this.error(error);
this.trigger('error');
return;
}
var segmentinfo = this.pendingsegment_; // the response was a success so set any bandwidth stats the request
// generated for abr purposes
this.savebandwidthrelatedstats_(segmentinfo.duration, simplesegment.stats);
segmentinfo.endofallrequests = simplesegment.endofallrequests;
if (result.gopinfo) {
this.gopbuffer_ = updategopbuffer(this.gopbuffer_, result.gopinfo, this.safeappend_);
} // although we may have already started appending on progress, we shouldn't switch the
// state away from loading until we are officially done loading the segment data.
this.state = 'appending'; // used for testing
this.trigger('appending');
this.waitforappendstocomplete_(segmentinfo);
};
_proto.settimemapping_ = function settimemapping_(timeline) {
var timelinemapping = this.synccontroller_.mappingfortimeline(timeline);
if (timelinemapping !== null) {
this.timemapping_ = timelinemapping;
}
};
_proto.updatemediasecondsloaded_ = function updatemediasecondsloaded_(segment) {
if (typeof segment.start === 'number' && typeof segment.end === 'number') {
this.mediasecondsloaded += segment.end - segment.start;
} else {
this.mediasecondsloaded += segment.duration;
}
};
_proto.shouldupdatetransmuxertimestampoffset_ = function shouldupdatetransmuxertimestampoffset_(timestampoffset) {
if (timestampoffset === null) {
return false;
} // note that we're potentially using the same timestamp offset for both video and
// audio
if (this.loadertype_ === 'main' && timestampoffset !== this.sourceupdater_.videotimestampoffset()) {
return true;
}
if (!this.audiodisabled_ && timestampoffset !== this.sourceupdater_.audiotimestampoffset()) {
return true;
}
return false;
};
_proto.truesegmentstart_ = function truesegmentstart_(_ref9) {
var currentstart = _ref9.currentstart,
playlist = _ref9.playlist,
mediaindex = _ref9.mediaindex,
firstvideoframetimefordata = _ref9.firstvideoframetimefordata,
currentvideotimestampoffset = _ref9.currentvideotimestampoffset,
usevideotiminginfo = _ref9.usevideotiminginfo,
videotiminginfo = _ref9.videotiminginfo,
audiotiminginfo = _ref9.audiotiminginfo;
if (typeof currentstart !== 'undefined') {
// if start was set once, keep using it
return currentstart;
}
if (!usevideotiminginfo) {
return audiotiminginfo.start;
}
var previoussegment = playlist.segments[mediaindex - 1]; // the start of a segment should be the start of the first full frame contained
// within that segment. since the transmuxer maintains a cache of incomplete data
// from and/or the last frame seen, the start time may reflect a frame that starts
// in the previous segment. check for that case and ensure the start time is
// accurate for the segment.
if (mediaindex === 0 || !previoussegment || typeof previoussegment.start === 'undefined' || previoussegment.end !== firstvideoframetimefordata + currentvideotimestampoffset) {
return firstvideoframetimefordata;
}
return videotiminginfo.start;
};
_proto.waitforappendstocomplete_ = function waitforappendstocomplete_(segmentinfo) {
var trackinfo = this.getcurrentmediainfo_(segmentinfo);
if (!trackinfo) {
this.error({
message: 'no starting media returned, likely due to an unsupported media format.',
blacklistduration: infinity
});
this.trigger('error');
return;
} // although transmuxing is done, appends may not yet be finished. throw a marker
// on each queue this loader is responsible for to ensure that the appends are
// complete.
var hasaudio = trackinfo.hasaudio,
hasvideo = trackinfo.hasvideo,
ismuxed = trackinfo.ismuxed;
var waitforvideo = this.loadertype_ === 'main' && hasvideo;
var waitforaudio = !this.audiodisabled_ && hasaudio && !ismuxed;
segmentinfo.waitingonappends = 0; // segments with no data
if (!segmentinfo.hasappendeddata_) {
if (!segmentinfo.timinginfo && typeof segmentinfo.timestampoffset === 'number') {
// when there's no audio or video data in the segment, there's no audio or video
// timing information.
//
// if there's no audio or video timing information, then the timestamp offset
// can't be adjusted to the appropriate value for the transmuxer and source
// buffers.
//
// therefore, the next segment should be used to set the timestamp offset.
this.ispendingtimestampoffset_ = true;
} // override settings for metadata only segments
segmentinfo.timinginfo = {
start: 0
};
segmentinfo.waitingonappends++;
if (!this.ispendingtimestampoffset_) {
// update the timestampoffset
this.updatesourcebuffertimestampoffset_(segmentinfo); // make sure the metadata queue is processed even though we have
// no video/audio data.
this.processmetadataqueue_();
} // append is "done" instantly with no data.
this.checkappendsdone_(segmentinfo);
return;
} // since source updater could call back synchronously, do the increments first.
if (waitforvideo) {
segmentinfo.waitingonappends++;
}
if (waitforaudio) {
segmentinfo.waitingonappends++;
}
if (waitforvideo) {
this.sourceupdater_.videoqueuecallback(this.checkappendsdone_.bind(this, segmentinfo));
}
if (waitforaudio) {
this.sourceupdater_.audioqueuecallback(this.checkappendsdone_.bind(this, segmentinfo));
}
};
_proto.checkappendsdone_ = function checkappendsdone_(segmentinfo) {
if (this.checkforabort_(segmentinfo.requestid)) {
return;
}
segmentinfo.waitingonappends--;
if (segmentinfo.waitingonappends === 0) {
this.handleappendsdone_();
}
};
_proto.checkforillegalmediaswitch = function checkforillegalmediaswitch(trackinfo) {
var illegalmediaswitcherror = illegalmediaswitch(this.loadertype_, this.getcurrentmediainfo_(), trackinfo);
if (illegalmediaswitcherror) {
this.error({
message: illegalmediaswitcherror,
blacklistduration: infinity
});
this.trigger('error');
return true;
}
return false;
};
_proto.updatesourcebuffertimestampoffset_ = function updatesourcebuffertimestampoffset_(segmentinfo) {
if (segmentinfo.timestampoffset === null || // we don't yet have the start for whatever media type (video or audio) has
// priority, timing-wise, so we must wait
typeof segmentinfo.timinginfo.start !== 'number' || // already updated the timestamp offset for this segment
segmentinfo.changedtimestampoffset || // the alt audio loader should not be responsible for setting the timestamp offset
this.loadertype_ !== 'main') {
return;
}
var didchange = false; // primary timing goes by video, and audio is trimmed in the transmuxer, meaning that
// the timing info here comes from video. in the event that the audio is longer than
// the video, this will trim the start of the audio.
// this also trims any offset from 0 at the beginning of the media
segmentinfo.timestampoffset -= this.getsegmentstarttimefortimestampoffsetcalculation_({
videotiminginfo: segmentinfo.segment.videotiminginfo,
audiotiminginfo: segmentinfo.segment.audiotiminginfo,
timinginfo: segmentinfo.timinginfo
}); // in the event that there are part segment downloads, each will try to update the
// timestamp offset. retaining this bit of state prevents us from updating in the
// future (within the same segment), however, there may be a better way to handle it.
segmentinfo.changedtimestampoffset = true;
if (segmentinfo.timestampoffset !== this.sourceupdater_.videotimestampoffset()) {
this.sourceupdater_.videotimestampoffset(segmentinfo.timestampoffset);
didchange = true;
}
if (segmentinfo.timestampoffset !== this.sourceupdater_.audiotimestampoffset()) {
this.sourceupdater_.audiotimestampoffset(segmentinfo.timestampoffset);
didchange = true;
}
if (didchange) {
this.trigger('timestampoffset');
}
};
_proto.getsegmentstarttimefortimestampoffsetcalculation_ = function getsegmentstarttimefortimestampoffsetcalculation_(_ref10) {
var videotiminginfo = _ref10.videotiminginfo,
audiotiminginfo = _ref10.audiotiminginfo,
timinginfo = _ref10.timinginfo;
if (!this.usedtsfortimestampoffset_) {
return timinginfo.start;
}
if (videotiminginfo && typeof videotiminginfo.transmuxeddecodestart === 'number') {
return videotiminginfo.transmuxeddecodestart;
} // handle audio only
if (audiotiminginfo && typeof audiotiminginfo.transmuxeddecodestart === 'number') {
return audiotiminginfo.transmuxeddecodestart;
} // handle content not transmuxed (e.g., mp4)
return timinginfo.start;
};
_proto.updatetiminginfoend_ = function updatetiminginfoend_(segmentinfo) {
segmentinfo.timinginfo = segmentinfo.timinginfo || {};
var trackinfo = this.getmediainfo_();
var usevideotiminginfo = this.loadertype_ === 'main' && trackinfo && trackinfo.hasvideo;
var prioritizedtiminginfo = usevideotiminginfo && segmentinfo.videotiminginfo ? segmentinfo.videotiminginfo : segmentinfo.audiotiminginfo;
if (!prioritizedtiminginfo) {
return;
}
segmentinfo.timinginfo.end = typeof prioritizedtiminginfo.end === 'number' ? // end time may not exist in a case where we aren't parsing the full segment (one
// current example is the case of fmp4), so use the rough duration to calculate an
// end time.
prioritizedtiminginfo.end : prioritizedtiminginfo.start + segmentinfo.duration;
}
/**
* callback to run when appendbuffer is finished. detects if we are
* in a good state to do things with the data we got, or if we need
* to wait for more
*
* @private
*/
;
_proto.handleappendsdone_ = function handleappendsdone_() {
// appendsdone can cause an abort
if (this.pendingsegment_) {
this.trigger('appendsdone');
}
if (!this.pendingsegment_) {
this.state = 'ready'; // todo should this move into this.checkforabort to speed up requests post abort in
// all appending cases?
if (!this.paused()) {
this.monitorbuffer_();
}
return;
}
var segmentinfo = this.pendingsegment_; // now that the end of the segment has been reached, we can set the end time. it's
// best to wait until all appends are done so we're sure that the primary media is
// finished (and we have its end time).
this.updatetiminginfoend_(segmentinfo);
if (this.shouldsavesegmenttiminginfo_) {
// timeline mappings should only be saved for the main loader. this is for multiple
// reasons:
//
// 1) only one mapping is saved per timeline, meaning that if both the audio loader
// and the main loader try to save the timeline mapping, whichever comes later
// will overwrite the first. in theory this is ok, as the mappings should be the
// same, however, it breaks for (2)
// 2) in the event of a live stream, the initial live point will make for a somewhat
// arbitrary mapping. if audio and video streams are not perfectly in-sync, then
// the mapping will be off for one of the streams, dependent on which one was
// first saved (see (1)).
// 3) primary timing goes by video in vhs, so the mapping should be video.
//
// since the audio loader will wait for the main loader to load the first segment,
// the main loader will save the first timeline mapping, and ensure that there won't
// be a case where audio loads two segments without saving a mapping (thus leading
// to missing segment timing info).
this.synccontroller_.savesegmenttiminginfo({
segmentinfo: segmentinfo,
shouldsavetimelinemapping: this.loadertype_ === 'main'
});
}
var segmentdurationmessage = gettroublesomesegmentdurationmessage(segmentinfo, this.sourcetype_);
if (segmentdurationmessage) {
if (segmentdurationmessage.severity === 'warn') {
videojs.log.warn(segmentdurationmessage.message);
} else {
this.logger_(segmentdurationmessage.message);
}
}
this.recordthroughput_(segmentinfo);
this.pendingsegment_ = null;
this.state = 'ready';
if (segmentinfo.issyncrequest) {
this.trigger('syncinfoupdate'); // if the sync request was not appended
// then it was not the correct segment.
// throw it away and use the data it gave us
// to get the correct one.
if (!segmentinfo.hasappendeddata_) {
this.logger_("throwing away un-appended sync request " + segmentinfostring(segmentinfo));
return;
}
}
this.logger_("appended " + segmentinfostring(segmentinfo));
this.addsegmentmetadatacue_(segmentinfo);
this.fetchatbuffer_ = true;
if (this.currenttimeline_ !== segmentinfo.timeline) {
this.timelinechangecontroller_.lasttimelinechange({
type: this.loadertype_,
from: this.currenttimeline_,
to: segmentinfo.timeline
}); // if audio is not disabled, the main segment loader is responsible for updating
// the audio timeline as well. if the content is video only, this won't have any
// impact.
if (this.loadertype_ === 'main' && !this.audiodisabled_) {
this.timelinechangecontroller_.lasttimelinechange({
type: 'audio',
from: this.currenttimeline_,
to: segmentinfo.timeline
});
}
}
this.currenttimeline_ = segmentinfo.timeline; // we must update the syncinfo to recalculate the seekable range before
// the following conditional otherwise it may consider this a bad "guess"
// and attempt to resync when the post-update seekable window and live
// point would mean that this was the perfect segment to fetch
this.trigger('syncinfoupdate');
var segment = segmentinfo.segment;
var part = segmentinfo.part;
var badsegmentguess = segment.end && this.currenttime_() - segment.end > segmentinfo.playlist.targetduration * 3;
var badpartguess = part && part.end && this.currenttime_() - part.end > segmentinfo.playlist.parttargetduration * 3; // if we previously appended a segment/part that ends more than 3 part/targetdurations before
// the currenttime_ that means that our conservative guess was too conservative.
// in that case, reset the loader state so that we try to use any information gained
// from the previous request to create a new, more accurate, sync-point.
if (badsegmentguess || badpartguess) {
this.logger_("bad " + (badsegmentguess ? 'segment' : 'part') + " " + segmentinfostring(segmentinfo));
this.reseteverything();
return;
}
var iswalkingforward = this.mediaindex !== null; // don't do a rendition switch unless we have enough time to get a sync segment
// and conservatively guess
if (iswalkingforward) {
this.trigger('bandwidthupdate');
}
this.trigger('progress');
this.mediaindex = segmentinfo.mediaindex;
this.partindex = segmentinfo.partindex; // any time an update finishes and the last segment is in the
// buffer, end the stream. this ensures the "ended" event will
// fire if playback reaches that point.
if (this.isendofstream_(segmentinfo.mediaindex, segmentinfo.playlist, segmentinfo.partindex)) {
this.endofstream();
} // used for testing
this.trigger('appended');
if (segmentinfo.hasappendeddata_) {
this.mediaappends++;
}
if (!this.paused()) {
this.monitorbuffer_();
}
}
/**
* records the current throughput of the decrypt, transmux, and append
* portion of the semgment pipeline. `throughput.rate` is a the cumulative
* moving average of the throughput. `throughput.count` is the number of
* data points in the average.
*
* @private
* @param {object} segmentinfo the object returned by loadsegment
*/
;
_proto.recordthroughput_ = function recordthroughput_(segmentinfo) {
if (segmentinfo.duration < min_segment_duration_to_save_stats) {
this.logger_("ignoring segment's throughput because its duration of " + segmentinfo.duration + (" is less than the min to record " + min_segment_duration_to_save_stats));
return;
}
var rate = this.throughput.rate; // add one to the time to ensure that we don't accidentally attempt to divide
// by zero in the case where the throughput is ridiculously high
var segmentprocessingtime = date.now() - segmentinfo.endofallrequests + 1; // multiply by 8000 to convert from bytes/millisecond to bits/second
var segmentprocessingthroughput = math.floor(segmentinfo.bytelength / segmentprocessingtime * 8 * 1000); // this is just a cumulative moving average calculation:
// newavg = oldavg + (sample - oldavg) / (samplecount + 1)
this.throughput.rate += (segmentprocessingthroughput - rate) / ++this.throughput.count;
}
/**
* adds a cue to the segment-metadata track with some metadata information about the
* segment
*
* @private
* @param {object} segmentinfo
* the object returned by loadsegment
* @method addsegmentmetadatacue_
*/
;
_proto.addsegmentmetadatacue_ = function addsegmentmetadatacue_(segmentinfo) {
if (!this.segmentmetadatatrack_) {
return;
}
var segment = segmentinfo.segment;
var start = segment.start;
var end = segment.end; // do not try adding the cue if the start and end times are invalid.
if (!finite(start) || !finite(end)) {
return;
}
removecuesfromtrack(start, end, this.segmentmetadatatrack_);
var cue = global_window__webpack_imported_module_0___default.a.webkitdatacue || global_window__webpack_imported_module_0___default.a.vttcue;
var value = {
custom: segment.custom,
datetimeobject: segment.datetimeobject,
datetimestring: segment.datetimestring,
bandwidth: segmentinfo.playlist.attributes.bandwidth,
resolution: segmentinfo.playlist.attributes.resolution,
codecs: segmentinfo.playlist.attributes.codecs,
bytelength: segmentinfo.bytelength,
uri: segmentinfo.uri,
timeline: segmentinfo.timeline,
playlist: segmentinfo.playlist.id,
start: start,
end: end
};
var data = json.stringify(value);
var cue = new cue(start, end, data); // attach the metadata to the value property of the cue to keep consistency between
// the differences of webkitdatacue in safari and vttcue in other browsers
cue.value = value;
this.segmentmetadatatrack_.addcue(cue);
};
return segmentloader;
}(videojs.eventtarget);
function noop() {}
var totitlecase = function totitlecase(string) {
if (typeof string !== 'string') {
return string;
}
return string.replace(/./, function (w) {
return w.touppercase();
});
};
var buffertypes = ['video', 'audio'];
var _updating = function updating(type, sourceupdater) {
var sourcebuffer = sourceupdater[type + "buffer"];
return sourcebuffer && sourcebuffer.updating || sourceupdater.queuepending[type];
};
var nextqueueindexoftype = function nextqueueindexoftype(type, queue) {
for (var i = 0; i < queue.length; i++) {
var queueentry = queue[i];
if (queueentry.type === 'mediasource') {
// if the next entry is a media source entry (uses multiple source buffers), block
// processing to allow it to go through first.
return null;
}
if (queueentry.type === type) {
return i;
}
}
return null;
};
var shiftqueue = function shiftqueue(type, sourceupdater) {
if (sourceupdater.queue.length === 0) {
return;
}
var queueindex = 0;
var queueentry = sourceupdater.queue[queueindex];
if (queueentry.type === 'mediasource') {
if (!sourceupdater.updating() && sourceupdater.mediasource.readystate !== 'closed') {
sourceupdater.queue.shift();
queueentry.action(sourceupdater);
if (queueentry.donefn) {
queueentry.donefn();
} // only specific source buffer actions must wait for async updateend events. media
// source actions process synchronously. therefore, both audio and video source
// buffers are now clear to process the next queue entries.
shiftqueue('audio', sourceupdater);
shiftqueue('video', sourceupdater);
} // media source actions require both source buffers, so if the media source action
// couldn't process yet (because one or both source buffers are busy), block other
// queue actions until both are available and the media source action can process.
return;
}
if (type === 'mediasource') {
// if the queue was shifted by a media source action (this happens when pushing a
// media source action onto the queue), then it wasn't from an updateend event from an
// audio or video source buffer, so there's no change from previous state, and no
// processing should be done.
return;
} // media source queue entries don't need to consider whether the source updater is
// started (i.e., source buffers are created) as they don't need the source buffers, but
// source buffer queue entries do.
if (!sourceupdater.ready() || sourceupdater.mediasource.readystate === 'closed' || _updating(type, sourceupdater)) {
return;
}
if (queueentry.type !== type) {
queueindex = nextqueueindexoftype(type, sourceupdater.queue);
if (queueindex === null) {
// either there's no queue entry that uses this source buffer type in the queue, or
// there's a media source queue entry before the next entry of this type, in which
// case wait for that action to process first.
return;
}
queueentry = sourceupdater.queue[queueindex];
}
sourceupdater.queue.splice(queueindex, 1); // keep a record that this source buffer type is in use.
//
// the queue pending operation must be set before the action is performed in the event
// that the action results in a synchronous event that is acted upon. for instance, if
// an exception is thrown that can be handled, it's possible that new actions will be
// appended to an empty queue and immediately executed, but would not have the correct
// pending information if this property was set after the action was performed.
sourceupdater.queuepending[type] = queueentry;
queueentry.action(type, sourceupdater);
if (!queueentry.donefn) {
// synchronous operation, process next entry
sourceupdater.queuepending[type] = null;
shiftqueue(type, sourceupdater);
return;
}
};
var cleanupbuffer = function cleanupbuffer(type, sourceupdater) {
var buffer = sourceupdater[type + "buffer"];
var titletype = totitlecase(type);
if (!buffer) {
return;
}
buffer.removeeventlistener('updateend', sourceupdater["on" + titletype + "updateend_"]);
buffer.removeeventlistener('error', sourceupdater["on" + titletype + "error_"]);
sourceupdater.codecs[type] = null;
sourceupdater[type + "buffer"] = null;
};
var insourcebuffers = function insourcebuffers(mediasource, sourcebuffer) {
return mediasource && sourcebuffer && array.prototype.indexof.call(mediasource.sourcebuffers, sourcebuffer) !== -1;
};
var actions = {
appendbuffer: function appendbuffer(bytes, segmentinfo, onerror) {
return function (type, sourceupdater) {
var sourcebuffer = sourceupdater[type + "buffer"]; // can't do anything if the media source / source buffer is null
// or the media source does not contain this source buffer.
if (!insourcebuffers(sourceupdater.mediasource, sourcebuffer)) {
return;
}
sourceupdater.logger_("appending segment " + segmentinfo.mediaindex + "'s " + bytes.length + " bytes to " + type + "buffer");
try {
sourcebuffer.appendbuffer(bytes);
} catch (e) {
sourceupdater.logger_("error with code " + e.code + " " + (e.code === quota_exceeded_err ? '(quota_exceeded_err) ' : '') + ("when appending segment " + segmentinfo.mediaindex + " to " + type + "buffer"));
sourceupdater.queuepending[type] = null;
onerror(e);
}
};
},
remove: function remove(start, end) {
return function (type, sourceupdater) {
var sourcebuffer = sourceupdater[type + "buffer"]; // can't do anything if the media source / source buffer is null
// or the media source does not contain this source buffer.
if (!insourcebuffers(sourceupdater.mediasource, sourcebuffer)) {
return;
}
sourceupdater.logger_("removing " + start + " to " + end + " from " + type + "buffer");
try {
sourcebuffer.remove(start, end);
} catch (e) {
sourceupdater.logger_("remove " + start + " to " + end + " from " + type + "buffer failed");
}
};
},
timestampoffset: function timestampoffset(offset) {
return function (type, sourceupdater) {
var sourcebuffer = sourceupdater[type + "buffer"]; // can't do anything if the media source / source buffer is null
// or the media source does not contain this source buffer.
if (!insourcebuffers(sourceupdater.mediasource, sourcebuffer)) {
return;
}
sourceupdater.logger_("setting " + type + "timestampoffset to " + offset);
sourcebuffer.timestampoffset = offset;
};
},
callback: function callback(_callback) {
return function (type, sourceupdater) {
_callback();
};
},
endofstream: function endofstream(error) {
return function (sourceupdater) {
if (sourceupdater.mediasource.readystate !== 'open') {
return;
}
sourceupdater.logger_("calling mediasource endofstream(" + (error || '') + ")");
try {
sourceupdater.mediasource.endofstream(error);
} catch (e) {
videojs.log.warn('failed to call media source endofstream', e);
}
};
},
duration: function duration(_duration) {
return function (sourceupdater) {
sourceupdater.logger_("setting mediasource duration to " + _duration);
try {
sourceupdater.mediasource.duration = _duration;
} catch (e) {
videojs.log.warn('failed to set media source duration', e);
}
};
},
abort: function abort() {
return function (type, sourceupdater) {
if (sourceupdater.mediasource.readystate !== 'open') {
return;
}
var sourcebuffer = sourceupdater[type + "buffer"]; // can't do anything if the media source / source buffer is null
// or the media source does not contain this source buffer.
if (!insourcebuffers(sourceupdater.mediasource, sourcebuffer)) {
return;
}
sourceupdater.logger_("calling abort on " + type + "buffer");
try {
sourcebuffer.abort();
} catch (e) {
videojs.log.warn("failed to abort on " + type + "buffer", e);
}
};
},
addsourcebuffer: function addsourcebuffer(type, codec) {
return function (sourceupdater) {
var titletype = totitlecase(type);
var mime = object(_videojs_vhs_utils_es_codecs_js__webpack_imported_module_13__[/* getmimeforcodec */ "e"])(codec);
sourceupdater.logger_("adding " + type + "buffer with codec " + codec + " to mediasource");
var sourcebuffer = sourceupdater.mediasource.addsourcebuffer(mime);
sourcebuffer.addeventlistener('updateend', sourceupdater["on" + titletype + "updateend_"]);
sourcebuffer.addeventlistener('error', sourceupdater["on" + titletype + "error_"]);
sourceupdater.codecs[type] = codec;
sourceupdater[type + "buffer"] = sourcebuffer;
};
},
removesourcebuffer: function removesourcebuffer(type) {
return function (sourceupdater) {
var sourcebuffer = sourceupdater[type + "buffer"];
cleanupbuffer(type, sourceupdater); // can't do anything if the media source / source buffer is null
// or the media source does not contain this source buffer.
if (!insourcebuffers(sourceupdater.mediasource, sourcebuffer)) {
return;
}
sourceupdater.logger_("removing " + type + "buffer with codec " + sourceupdater.codecs[type] + " from mediasource");
try {
sourceupdater.mediasource.removesourcebuffer(sourcebuffer);
} catch (e) {
videojs.log.warn("failed to removesourcebuffer " + type + "buffer", e);
}
};
},
changetype: function changetype(codec) {
return function (type, sourceupdater) {
var sourcebuffer = sourceupdater[type + "buffer"];
var mime = object(_videojs_vhs_utils_es_codecs_js__webpack_imported_module_13__[/* getmimeforcodec */ "e"])(codec); // can't do anything if the media source / source buffer is null
// or the media source does not contain this source buffer.
if (!insourcebuffers(sourceupdater.mediasource, sourcebuffer)) {
return;
} // do not update codec if we don't need to.
if (sourceupdater.codecs[type] === codec) {
return;
}
sourceupdater.logger_("changing " + type + "buffer codec from " + sourceupdater.codecs[type] + " to " + codec); // check if change to the provided type is supported
try {
sourcebuffer.changetype(mime);
sourceupdater.codecs[type] = codec;
} catch (e) {
videojs.log.warn("failed to changetype on " + type + "buffer", e);
}
};
}
};
var pushqueue = function pushqueue(_ref) {
var type = _ref.type,
sourceupdater = _ref.sourceupdater,
action = _ref.action,
donefn = _ref.donefn,
name = _ref.name;
sourceupdater.queue.push({
type: type,
action: action,
donefn: donefn,
name: name
});
shiftqueue(type, sourceupdater);
};
var onupdateend = function onupdateend(type, sourceupdater) {
return function (e) {
// although there should, in theory, be a pending action for any updateend receieved,
// there are some actions that may trigger updateend events without set definitions in
// the w3c spec. for instance, setting the duration on the media source may trigger
// updateend events on source buffers. this does not appear to be in the spec. as such,
// if we encounter an updateend without a corresponding pending action from our queue
// for that source buffer type, process the next action.
if (sourceupdater.queuepending[type]) {
var donefn = sourceupdater.queuepending[type].donefn;
sourceupdater.queuepending[type] = null;
if (donefn) {
// if there's an error, report it
donefn(sourceupdater[type + "error_"]);
}
}
shiftqueue(type, sourceupdater);
};
};
/**
* a queue of callbacks to be serialized and applied when a
* mediasource and its associated sourcebuffers are not in the
* updating state. it is used by the segment loader to update the
* underlying sourcebuffers when new data is loaded, for instance.
*
* @class sourceupdater
* @param {mediasource} mediasource the mediasource to create the sourcebuffer from
* @param {string} mimetype the desired mime type of the underlying sourcebuffer
*/
var sourceupdater = /*#__pure__*/function (_videojs$eventtarget) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(sourceupdater, _videojs$eventtarget);
function sourceupdater(mediasource) {
var _this;
_this = _videojs$eventtarget.call(this) || this;
_this.mediasource = mediasource;
_this.sourceopenlistener_ = function () {
return shiftqueue('mediasource', _babel_runtime_helpers_assertthisinitialized__webpack_imported_module_4___default()(_this));
};
_this.mediasource.addeventlistener('sourceopen', _this.sourceopenlistener_);
_this.logger_ = logger('sourceupdater'); // initial timestamp offset is 0
_this.audiotimestampoffset_ = 0;
_this.videotimestampoffset_ = 0;
_this.queue = [];
_this.queuepending = {
audio: null,
video: null
};
_this.delayedaudioappendqueue_ = [];
_this.videoappendqueued_ = false;
_this.codecs = {};
_this.onvideoupdateend_ = onupdateend('video', _babel_runtime_helpers_assertthisinitialized__webpack_imported_module_4___default()(_this));
_this.onaudioupdateend_ = onupdateend('audio', _babel_runtime_helpers_assertthisinitialized__webpack_imported_module_4___default()(_this));
_this.onvideoerror_ = function (e) {
// used for debugging
_this.videoerror_ = e;
};
_this.onaudioerror_ = function (e) {
// used for debugging
_this.audioerror_ = e;
};
_this.createdsourcebuffers_ = false;
_this.initializedeme_ = false;
_this.triggeredready_ = false;
return _this;
}
var _proto = sourceupdater.prototype;
_proto.initializedeme = function initializedeme() {
this.initializedeme_ = true;
this.triggerready();
};
_proto.hascreatedsourcebuffers = function hascreatedsourcebuffers() {
// if false, likely waiting on one of the segment loaders to get enough data to create
// source buffers
return this.createdsourcebuffers_;
};
_proto.hasinitializedanyeme = function hasinitializedanyeme() {
return this.initializedeme_;
};
_proto.ready = function ready() {
return this.hascreatedsourcebuffers() && this.hasinitializedanyeme();
};
_proto.createsourcebuffers = function createsourcebuffers(codecs) {
if (this.hascreatedsourcebuffers()) {
// already created them before
return;
} // the intial addorchangesourcebuffers will always be
// two add buffers.
this.addorchangesourcebuffers(codecs);
this.createdsourcebuffers_ = true;
this.trigger('createdsourcebuffers');
this.triggerready();
};
_proto.triggerready = function triggerready() {
// only allow ready to be triggered once, this prevents the case
// where:
// 1. we trigger createdsourcebuffers
// 2. ie 11 synchronously initializates eme
// 3. the synchronous initialization causes us to trigger ready
// 4. we go back to the ready check in createsourcebuffers and ready is triggered again.
if (this.ready() && !this.triggeredready_) {
this.triggeredready_ = true;
this.trigger('ready');
}
}
/**
* add a type of source buffer to the media source.
*
* @param {string} type
* the type of source buffer to add.
*
* @param {string} codec
* the codec to add the source buffer with.
*/
;
_proto.addsourcebuffer = function addsourcebuffer(type, codec) {
pushqueue({
type: 'mediasource',
sourceupdater: this,
action: actions.addsourcebuffer(type, codec),
name: 'addsourcebuffer'
});
}
/**
* call abort on a source buffer.
*
* @param {string} type
* the type of source buffer to call abort on.
*/
;
_proto.abort = function abort(type) {
pushqueue({
type: type,
sourceupdater: this,
action: actions.abort(type),
name: 'abort'
});
}
/**
* call removesourcebuffer and remove a specific type
* of source buffer on the mediasource.
*
* @param {string} type
* the type of source buffer to remove.
*/
;
_proto.removesourcebuffer = function removesourcebuffer(type) {
if (!this.canremovesourcebuffer()) {
videojs.log.error('removesourcebuffer is not supported!');
return;
}
pushqueue({
type: 'mediasource',
sourceupdater: this,
action: actions.removesourcebuffer(type),
name: 'removesourcebuffer'
});
}
/**
* whether or not the removesourcebuffer function is supported
* on the mediasource.
*
* @return {boolean}
* if removesourcebuffer can be called.
*/
;
_proto.canremovesourcebuffer = function canremovesourcebuffer() {
// ie reports that it supports removesourcebuffer, but often throws
// errors when attempting to use the function. so we report that it
// does not support removesourcebuffer. as of firefox 83 removesourcebuffer
// throws errors, so we report that it does not support this as well.
return !videojs.browser.ie_version && !videojs.browser.is_firefox && global_window__webpack_imported_module_0___default.a.mediasource && global_window__webpack_imported_module_0___default.a.mediasource.prototype && typeof global_window__webpack_imported_module_0___default.a.mediasource.prototype.removesourcebuffer === 'function';
}
/**
* whether or not the changetype function is supported
* on our sourcebuffers.
*
* @return {boolean}
* if changetype can be called.
*/
;
sourceupdater.canchangetype = function canchangetype() {
return global_window__webpack_imported_module_0___default.a.sourcebuffer && global_window__webpack_imported_module_0___default.a.sourcebuffer.prototype && typeof global_window__webpack_imported_module_0___default.a.sourcebuffer.prototype.changetype === 'function';
}
/**
* whether or not the changetype function is supported
* on our sourcebuffers.
*
* @return {boolean}
* if changetype can be called.
*/
;
_proto.canchangetype = function canchangetype() {
return this.constructor.canchangetype();
}
/**
* call the changetype function on a source buffer, given the code and type.
*
* @param {string} type
* the type of source buffer to call changetype on.
*
* @param {string} codec
* the codec string to change type with on the source buffer.
*/
;
_proto.changetype = function changetype(type, codec) {
if (!this.canchangetype()) {
videojs.log.error('changetype is not supported!');
return;
}
pushqueue({
type: type,
sourceupdater: this,
action: actions.changetype(codec),
name: 'changetype'
});
}
/**
* add source buffers with a codec or, if they are already created,
* call changetype on source buffers using changetype.
*
* @param {object} codecs
* codecs to switch to
*/
;
_proto.addorchangesourcebuffers = function addorchangesourcebuffers(codecs) {
var _this2 = this;
if (!codecs || typeof codecs !== 'object' || object.keys(codecs).length === 0) {
throw new error('cannot addorchangesourcebuffers to undefined codecs');
}
object.keys(codecs).foreach(function (type) {
var codec = codecs[type];
if (!_this2.hascreatedsourcebuffers()) {
return _this2.addsourcebuffer(type, codec);
}
if (_this2.canchangetype()) {
_this2.changetype(type, codec);
}
});
}
/**
* queue an update to append an arraybuffer.
*
* @param {mediaobject} object containing audiobytes and/or videobytes
* @param {function} done the function to call when done
* @see http://www.w3.org/tr/media-source/#widl-sourcebuffer-appendbuffer-void-arraybuffer-data
*/
;
_proto.appendbuffer = function appendbuffer(options, donefn) {
var _this3 = this;
var segmentinfo = options.segmentinfo,
type = options.type,
bytes = options.bytes;
this.processedappend_ = true;
if (type === 'audio' && this.videobuffer && !this.videoappendqueued_) {
this.delayedaudioappendqueue_.push([options, donefn]);
this.logger_("delayed audio append of " + bytes.length + " until video append");
return;
} // in the case of certain errors, for instance, quota_exceeded_err, updateend will
// not be fired. this means that the queue will be blocked until the next action
// taken by the segment-loader. provide a mechanism for segment-loader to handle
// these errors by calling the donefn with the specific error.
var onerror = donefn;
pushqueue({
type: type,
sourceupdater: this,
action: actions.appendbuffer(bytes, segmentinfo || {
mediaindex: -1
}, onerror),
donefn: donefn,
name: 'appendbuffer'
});
if (type === 'video') {
this.videoappendqueued_ = true;
if (!this.delayedaudioappendqueue_.length) {
return;
}
var queue = this.delayedaudioappendqueue_.slice();
this.logger_("queuing delayed audio " + queue.length + " appendbuffers");
this.delayedaudioappendqueue_.length = 0;
queue.foreach(function (que) {
_this3.appendbuffer.apply(_this3, que);
});
}
}
/**
* get the audio buffer's buffered timerange.
*
* @return {timerange}
* the audio buffer's buffered time range
*/
;
_proto.audiobuffered = function audiobuffered() {
// no media source/source buffer or it isn't in the media sources
// source buffer list
if (!insourcebuffers(this.mediasource, this.audiobuffer)) {
return videojs.createtimerange();
}
return this.audiobuffer.buffered ? this.audiobuffer.buffered : videojs.createtimerange();
}
/**
* get the video buffer's buffered timerange.
*
* @return {timerange}
* the video buffer's buffered time range
*/
;
_proto.videobuffered = function videobuffered() {
// no media source/source buffer or it isn't in the media sources
// source buffer list
if (!insourcebuffers(this.mediasource, this.videobuffer)) {
return videojs.createtimerange();
}
return this.videobuffer.buffered ? this.videobuffer.buffered : videojs.createtimerange();
}
/**
* get a combined video/audio buffer's buffered timerange.
*
* @return {timerange}
* the combined time range
*/
;
_proto.buffered = function buffered() {
var video = insourcebuffers(this.mediasource, this.videobuffer) ? this.videobuffer : null;
var audio = insourcebuffers(this.mediasource, this.audiobuffer) ? this.audiobuffer : null;
if (audio && !video) {
return this.audiobuffered();
}
if (video && !audio) {
return this.videobuffered();
}
return bufferintersection(this.audiobuffered(), this.videobuffered());
}
/**
* add a callback to the queue that will set duration on the mediasource.
*
* @param {number} duration
* the duration to set
*
* @param {function} [donefn]
* function to run after duration has been set.
*/
;
_proto.setduration = function setduration(duration, donefn) {
if (donefn === void 0) {
donefn = noop;
} // in order to set the duration on the media source, it's necessary to wait for all
// source buffers to no longer be updating. "if the updating attribute equals true on
// any sourcebuffer in sourcebuffers, then throw an invalidstateerror exception and
// abort these steps." (source: https://www.w3.org/tr/media-source/#attributes).
pushqueue({
type: 'mediasource',
sourceupdater: this,
action: actions.duration(duration),
name: 'duration',
donefn: donefn
});
}
/**
* add a mediasource endofstream call to the queue
*
* @param {error} [error]
* call endofstream with an error
*
* @param {function} [donefn]
* a function that should be called when the
* endofstream call has finished.
*/
;
_proto.endofstream = function endofstream(error, donefn) {
if (error === void 0) {
error = null;
}
if (donefn === void 0) {
donefn = noop;
}
if (typeof error !== 'string') {
error = undefined;
} // in order to set the duration on the media source, it's necessary to wait for all
// source buffers to no longer be updating. "if the updating attribute equals true on
// any sourcebuffer in sourcebuffers, then throw an invalidstateerror exception and
// abort these steps." (source: https://www.w3.org/tr/media-source/#attributes).
pushqueue({
type: 'mediasource',
sourceupdater: this,
action: actions.endofstream(error),
name: 'endofstream',
donefn: donefn
});
}
/**
* queue an update to remove a time range from the buffer.
*
* @param {number} start where to start the removal
* @param {number} end where to end the removal
* @param {function} [done=noop] optional callback to be executed when the remove
* operation is complete
* @see http://www.w3.org/tr/media-source/#widl-sourcebuffer-remove-void-double-start-unrestricted-double-end
*/
;
_proto.removeaudio = function removeaudio(start, end, done) {
if (done === void 0) {
done = noop;
}
if (!this.audiobuffered().length || this.audiobuffered().end(0) === 0) {
done();
return;
}
pushqueue({
type: 'audio',
sourceupdater: this,
action: actions.remove(start, end),
donefn: done,
name: 'remove'
});
}
/**
* queue an update to remove a time range from the buffer.
*
* @param {number} start where to start the removal
* @param {number} end where to end the removal
* @param {function} [done=noop] optional callback to be executed when the remove
* operation is complete
* @see http://www.w3.org/tr/media-source/#widl-sourcebuffer-remove-void-double-start-unrestricted-double-end
*/
;
_proto.removevideo = function removevideo(start, end, done) {
if (done === void 0) {
done = noop;
}
if (!this.videobuffered().length || this.videobuffered().end(0) === 0) {
done();
return;
}
pushqueue({
type: 'video',
sourceupdater: this,
action: actions.remove(start, end),
donefn: done,
name: 'remove'
});
}
/**
* whether the underlying sourcebuffer is updating or not
*
* @return {boolean} the updating status of the sourcebuffer
*/
;
_proto.updating = function updating() {
// the audio/video source buffer is updating
if (_updating('audio', this) || _updating('video', this)) {
return true;
}
return false;
}
/**
* set/get the timestampoffset on the audio sourcebuffer
*
* @return {number} the timestamp offset
*/
;
_proto.audiotimestampoffset = function audiotimestampoffset(offset) {
if (typeof offset !== 'undefined' && this.audiobuffer && // no point in updating if it's the same
this.audiotimestampoffset_ !== offset) {
pushqueue({
type: 'audio',
sourceupdater: this,
action: actions.timestampoffset(offset),
name: 'timestampoffset'
});
this.audiotimestampoffset_ = offset;
}
return this.audiotimestampoffset_;
}
/**
* set/get the timestampoffset on the video sourcebuffer
*
* @return {number} the timestamp offset
*/
;
_proto.videotimestampoffset = function videotimestampoffset(offset) {
if (typeof offset !== 'undefined' && this.videobuffer && // no point in updating if it's the same
this.videotimestampoffset !== offset) {
pushqueue({
type: 'video',
sourceupdater: this,
action: actions.timestampoffset(offset),
name: 'timestampoffset'
});
this.videotimestampoffset_ = offset;
}
return this.videotimestampoffset_;
}
/**
* add a function to the queue that will be called
* when it is its turn to run in the audio queue.
*
* @param {function} callback
* the callback to queue.
*/
;
_proto.audioqueuecallback = function audioqueuecallback(callback) {
if (!this.audiobuffer) {
return;
}
pushqueue({
type: 'audio',
sourceupdater: this,
action: actions.callback(callback),
name: 'callback'
});
}
/**
* add a function to the queue that will be called
* when it is its turn to run in the video queue.
*
* @param {function} callback
* the callback to queue.
*/
;
_proto.videoqueuecallback = function videoqueuecallback(callback) {
if (!this.videobuffer) {
return;
}
pushqueue({
type: 'video',
sourceupdater: this,
action: actions.callback(callback),
name: 'callback'
});
}
/**
* dispose of the source updater and the underlying sourcebuffer
*/
;
_proto.dispose = function dispose() {
var _this4 = this;
this.trigger('dispose');
buffertypes.foreach(function (type) {
_this4.abort(type);
if (_this4.canremovesourcebuffer()) {
_this4.removesourcebuffer(type);
} else {
_this4[type + "queuecallback"](function () {
return cleanupbuffer(type, _this4);
});
}
});
this.videoappendqueued_ = false;
this.delayedaudioappendqueue_.length = 0;
if (this.sourceopenlistener_) {
this.mediasource.removeeventlistener('sourceopen', this.sourceopenlistener_);
}
this.off();
};
return sourceupdater;
}(videojs.eventtarget);
var uint8toutf8 = function uint8toutf8(uintarray) {
return decodeuricomponent(escape(string.fromcharcode.apply(null, uintarray)));
};
var vtt_line_terminators = new uint8array('\n\n'.split('').map(function (_char3) {
return _char3.charcodeat(0);
}));
var novttjserror = /*#__pure__*/function (_error) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(novttjserror, _error);
function novttjserror() {
return _error.call(this, 'trying to parse received vtt cues, but there is no webvtt. make sure vtt.js is loaded.') || this;
}
return novttjserror;
}( /*#__pure__*/_babel_runtime_helpers_wrapnativesuper__webpack_imported_module_21___default()(error));
/**
* an object that manages segment loading and appending.
*
* @class vttsegmentloader
* @param {object} options required and optional options
* @extends videojs.eventtarget
*/
var vttsegmentloader = /*#__pure__*/function (_segmentloader) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(vttsegmentloader, _segmentloader);
function vttsegmentloader(settings, options) {
var _this;
if (options === void 0) {
options = {};
}
_this = _segmentloader.call(this, settings, options) || this; // segmentloader requires a mediasource be specified or it will throw an error;
// however, vttsegmentloader has no need of a media source, so delete the reference
_this.mediasource_ = null;
_this.subtitlestrack_ = null;
_this.loadertype_ = 'subtitle';
_this.featuresnativetexttracks_ = settings.featuresnativetexttracks;
_this.loadvttjs = settings.loadvttjs; // the vtt segment will have its own time mappings. saving vtt segment timing info in
// the sync controller leads to improper behavior.
_this.shouldsavesegmenttiminginfo_ = false;
return _this;
}
var _proto = vttsegmentloader.prototype;
_proto.createtransmuxer_ = function createtransmuxer_() {
// don't need to transmux any subtitles
return null;
}
/**
* indicates which time ranges are buffered
*
* @return {timerange}
* timerange object representing the current buffered ranges
*/
;
_proto.buffered_ = function buffered_() {
if (!this.subtitlestrack_ || !this.subtitlestrack_.cues || !this.subtitlestrack_.cues.length) {
return videojs.createtimeranges();
}
var cues = this.subtitlestrack_.cues;
var start = cues[0].starttime;
var end = cues[cues.length - 1].starttime;
return videojs.createtimeranges([[start, end]]);
}
/**
* gets and sets init segment for the provided map
*
* @param {object} map
* the map object representing the init segment to get or set
* @param {boolean=} set
* if true, the init segment for the provided map should be saved
* @return {object}
* map object for desired init segment
*/
;
_proto.initsegmentformap = function initsegmentformap(map, set) {
if (set === void 0) {
set = false;
}
if (!map) {
return null;
}
var id = initsegmentid(map);
var storedmap = this.initsegments_[id];
if (set && !storedmap && map.bytes) {
// append webvtt line terminators to the media initialization segment if it exists
// to follow the webvtt spec (https://w3c.github.io/webvtt/#file-structure) that
// requires two or more webvtt line terminators between the webvtt header and the
// rest of the file
var combinedbytelength = vtt_line_terminators.bytelength + map.bytes.bytelength;
var combinedsegment = new uint8array(combinedbytelength);
combinedsegment.set(map.bytes);
combinedsegment.set(vtt_line_terminators, map.bytes.bytelength);
this.initsegments_[id] = storedmap = {
resolveduri: map.resolveduri,
byterange: map.byterange,
bytes: combinedsegment
};
}
return storedmap || map;
}
/**
* returns true if all configuration required for loading is present, otherwise false.
*
* @return {boolean} true if the all configuration is ready for loading
* @private
*/
;
_proto.couldbeginloading_ = function couldbeginloading_() {
return this.playlist_ && this.subtitlestrack_ && !this.paused();
}
/**
* once all the starting parameters have been specified, begin
* operation. this method should only be invoked from the init
* state.
*
* @private
*/
;
_proto.init_ = function init_() {
this.state = 'ready';
this.reseteverything();
return this.monitorbuffer_();
}
/**
* set a subtitle track on the segment loader to add subtitles to
*
* @param {texttrack=} track
* the text track to add loaded subtitles to
* @return {texttrack}
* returns the subtitles track
*/
;
_proto.track = function track(_track) {
if (typeof _track === 'undefined') {
return this.subtitlestrack_;
}
this.subtitlestrack_ = _track; // if we were unpaused but waiting for a sourceupdater, start
// buffering now
if (this.state === 'init' && this.couldbeginloading_()) {
this.init_();
}
return this.subtitlestrack_;
}
/**
* remove any data in the source buffer between start and end times
*
* @param {number} start - the start time of the region to remove from the buffer
* @param {number} end - the end time of the region to remove from the buffer
*/
;
_proto.remove = function remove(start, end) {
removecuesfromtrack(start, end, this.subtitlestrack_);
}
/**
* fill the buffer with segements unless the sourcebuffers are
* currently updating
*
* note: this function should only ever be called by monitorbuffer_
* and never directly
*
* @private
*/
;
_proto.fillbuffer_ = function fillbuffer_() {
var _this2 = this; // see if we need to begin loading immediately
var segmentinfo = this.choosenextrequest_();
if (!segmentinfo) {
return;
}
if (this.synccontroller_.timestampoffsetfortimeline(segmentinfo.timeline) === null) {
// we don't have the timestamp offset that we need to sync subtitles.
// rerun on a timestamp offset or user interaction.
var checktimestampoffset = function checktimestampoffset() {
_this2.state = 'ready';
if (!_this2.paused()) {
// if not paused, queue a buffer check as soon as possible
_this2.monitorbuffer_();
}
};
this.synccontroller_.one('timestampoffset', checktimestampoffset);
this.state = 'waiting_on_timeline';
return;
}
this.loadsegment_(segmentinfo);
} // never set a timestamp offset for vtt segments.
;
_proto.timestampoffsetforsegment_ = function timestampoffsetforsegment_() {
return null;
};
_proto.choosenextrequest_ = function choosenextrequest_() {
return this.skipemptysegments_(_segmentloader.prototype.choosenextrequest_.call(this));
}
/**
* prevents the segment loader from requesting segments we know contain no subtitles
* by walking forward until we find the next segment that we don't know whether it is
* empty or not.
*
* @param {object} segmentinfo
* a segment info object that describes the current segment
* @return {object}
* a segment info object that describes the current segment
*/
;
_proto.skipemptysegments_ = function skipemptysegments_(segmentinfo) {
while (segmentinfo && segmentinfo.segment.empty) {
// stop at the last possible segmentinfo
if (segmentinfo.mediaindex + 1 >= segmentinfo.playlist.segments.length) {
segmentinfo = null;
break;
}
segmentinfo = this.generatesegmentinfo_({
playlist: segmentinfo.playlist,
mediaindex: segmentinfo.mediaindex + 1,
startofsegment: segmentinfo.startofsegment + segmentinfo.duration,
issyncrequest: segmentinfo.issyncrequest
});
}
return segmentinfo;
};
_proto.stopforerror = function stopforerror(error) {
this.error(error);
this.state = 'ready';
this.pause();
this.trigger('error');
}
/**
* append a decrypted segement to the sourcebuffer through a sourceupdater
*
* @private
*/
;
_proto.segmentrequestfinished_ = function segmentrequestfinished_(error, simplesegment, result) {
var _this3 = this;
if (!this.subtitlestrack_) {
this.state = 'ready';
return;
}
this.savetransferstats_(simplesegment.stats); // the request was aborted
if (!this.pendingsegment_) {
this.state = 'ready';
this.mediarequestsaborted += 1;
return;
}
if (error) {
if (error.code === request_errors.timeout) {
this.handletimeout_();
}
if (error.code === request_errors.aborted) {
this.mediarequestsaborted += 1;
} else {
this.mediarequestserrored += 1;
}
this.stopforerror(error);
return;
}
var segmentinfo = this.pendingsegment_; // although the vtt segment loader bandwidth isn't really used, it's good to
// maintain functionality between segment loaders
this.savebandwidthrelatedstats_(segmentinfo.duration, simplesegment.stats); // if this request included a segment key, save that data in the cache
if (simplesegment.key) {
this.segmentkey(simplesegment.key, true);
}
this.state = 'appending'; // used for tests
this.trigger('appending');
var segment = segmentinfo.segment;
if (segment.map) {
segment.map.bytes = simplesegment.map.bytes;
}
segmentinfo.bytes = simplesegment.bytes; // make sure that vttjs has loaded, otherwise, load it and wait till it finished loading
if (typeof global_window__webpack_imported_module_0___default.a.webvtt !== 'function' && typeof this.loadvttjs === 'function') {
this.state = 'waiting_on_vttjs'; // should be fine to call multiple times
// script will be loaded once but multiple listeners will be added to the queue, which is expected.
this.loadvttjs().then(function () {
return _this3.segmentrequestfinished_(error, simplesegment, result);
}, function () {
return _this3.stopforerror({
message: 'error loading vtt.js'
});
});
return;
}
segment.requested = true;
try {
this.parsevttcues_(segmentinfo);
} catch (e) {
this.stopforerror({
message: e.message
});
return;
}
this.updatetimemapping_(segmentinfo, this.synccontroller_.timelines[segmentinfo.timeline], this.playlist_);
if (segmentinfo.cues.length) {
segmentinfo.timinginfo = {
start: segmentinfo.cues[0].starttime,
end: segmentinfo.cues[segmentinfo.cues.length - 1].endtime
};
} else {
segmentinfo.timinginfo = {
start: segmentinfo.startofsegment,
end: segmentinfo.startofsegment + segmentinfo.duration
};
}
if (segmentinfo.issyncrequest) {
this.trigger('syncinfoupdate');
this.pendingsegment_ = null;
this.state = 'ready';
return;
}
segmentinfo.bytelength = segmentinfo.bytes.bytelength;
this.mediasecondsloaded += segment.duration; // create vttcue instances for each cue in the new segment and add them to
// the subtitle track
segmentinfo.cues.foreach(function (cue) {
_this3.subtitlestrack_.addcue(_this3.featuresnativetexttracks_ ? new global_window__webpack_imported_module_0___default.a.vttcue(cue.starttime, cue.endtime, cue.text) : cue);
}); // remove any duplicate cues from the subtitle track. the webvtt spec allows
// cues to have identical time-intervals, but if the text is also identical
// we can safely assume it is a duplicate that can be removed (ex. when a cue
// "overlaps" vtt segments)
removeduplicatecuesfromtrack(this.subtitlestrack_);
this.handleappendsdone_();
};
_proto.handledata_ = function handledata_() {// noop as we shouldn't be getting video/audio data captions
// that we do not support here.
};
_proto.updatetiminginfoend_ = function updatetiminginfoend_() {// noop
}
/**
* uses the webvtt parser to parse the segment response
*
* @throws novttjserror
*
* @param {object} segmentinfo
* a segment info object that describes the current segment
* @private
*/
;
_proto.parsevttcues_ = function parsevttcues_(segmentinfo) {
var decoder;
var decodebytestostring = false;
if (typeof global_window__webpack_imported_module_0___default.a.webvtt !== 'function') {
// caller is responsible for exception handling.
throw new novttjserror();
}
if (typeof global_window__webpack_imported_module_0___default.a.textdecoder === 'function') {
decoder = new global_window__webpack_imported_module_0___default.a.textdecoder('utf8');
} else {
decoder = global_window__webpack_imported_module_0___default.a.webvtt.stringdecoder();
decodebytestostring = true;
}
var parser = new global_window__webpack_imported_module_0___default.a.webvtt.parser(global_window__webpack_imported_module_0___default.a, global_window__webpack_imported_module_0___default.a.vttjs, decoder);
segmentinfo.cues = [];
segmentinfo.timestampmap = {
mpegts: 0,
local: 0
};
parser.oncue = segmentinfo.cues.push.bind(segmentinfo.cues);
parser.ontimestampmap = function (map) {
segmentinfo.timestampmap = map;
};
parser.onparsingerror = function (error) {
videojs.log.warn('error encountered when parsing cues: ' + error.message);
};
if (segmentinfo.segment.map) {
var mapdata = segmentinfo.segment.map.bytes;
if (decodebytestostring) {
mapdata = uint8toutf8(mapdata);
}
parser.parse(mapdata);
}
var segmentdata = segmentinfo.bytes;
if (decodebytestostring) {
segmentdata = uint8toutf8(segmentdata);
}
parser.parse(segmentdata);
parser.flush();
}
/**
* updates the start and end times of any cues parsed by the webvtt parser using
* the information parsed from the x-timestamp-map header and a ts to media time mapping
* from the synccontroller
*
* @param {object} segmentinfo
* a segment info object that describes the current segment
* @param {object} mappingobj
* object containing a mapping from ts to media time
* @param {object} playlist
* the playlist object containing the segment
* @private
*/
;
_proto.updatetimemapping_ = function updatetimemapping_(segmentinfo, mappingobj, playlist) {
var segment = segmentinfo.segment;
if (!mappingobj) {
// if the sync controller does not have a mapping of ts to media time for the
// timeline, then we don't have enough information to update the cue
// start/end times
return;
}
if (!segmentinfo.cues.length) {
// if there are no cues, we also do not have enough information to figure out
// segment timing. mark that the segment contains no cues so we don't re-request
// an empty segment.
segment.empty = true;
return;
}
var timestampmap = segmentinfo.timestampmap;
var diff = timestampmap.mpegts / mux_js_lib_utils_clock__webpack_imported_module_20__["one_second_in_ts"] - timestampmap.local + mappingobj.mapping;
segmentinfo.cues.foreach(function (cue) {
// first convert cue time to ts time using the timestamp-map provided within the vtt
cue.starttime += diff;
cue.endtime += diff;
});
if (!playlist.syncinfo) {
var firststart = segmentinfo.cues[0].starttime;
var laststart = segmentinfo.cues[segmentinfo.cues.length - 1].starttime;
playlist.syncinfo = {
mediasequence: playlist.mediasequence + segmentinfo.mediaindex,
time: math.min(firststart, laststart - segment.duration)
};
}
};
return vttsegmentloader;
}(segmentloader);
/**
* @file ad-cue-tags.js
*/
/**
* searches for an ad cue that overlaps with the given mediatime
*
* @param {object} track
* the track to find the cue for
*
* @param {number} mediatime
* the time to find the cue at
*
* @return {object|null}
* the found cue or null
*/
var findadcue = function findadcue(track, mediatime) {
var cues = track.cues;
for (var i = 0; i < cues.length; i++) {
var cue = cues[i];
if (mediatime >= cue.adstarttime && mediatime <= cue.adendtime) {
return cue;
}
}
return null;
};
var updateadcues = function updateadcues(media, track, offset) {
if (offset === void 0) {
offset = 0;
}
if (!media.segments) {
return;
}
var mediatime = offset;
var cue;
for (var i = 0; i < media.segments.length; i++) {
var segment = media.segments[i];
if (!cue) {
// since the cues will span for at least the segment duration, adding a fudge
// factor of half segment duration will prevent duplicate cues from being
// created when timing info is not exact (e.g. cue start time initialized
// at 10.006677, but next call mediatime is 10.003332 )
cue = findadcue(track, mediatime + segment.duration / 2);
}
if (cue) {
if ('cuein' in segment) {
// found a cue-in so end the cue
cue.endtime = mediatime;
cue.adendtime = mediatime;
mediatime += segment.duration;
cue = null;
continue;
}
if (mediatime < cue.endtime) {
// already processed this mediatime for this cue
mediatime += segment.duration;
continue;
} // otherwise extend cue until a cue-in is found
cue.endtime += segment.duration;
} else {
if ('cueout' in segment) {
cue = new global_window__webpack_imported_module_0___default.a.vttcue(mediatime, mediatime + segment.duration, segment.cueout);
cue.adstarttime = mediatime; // assumes tag format to be
// #ext-x-cue-out:30
cue.adendtime = mediatime + parsefloat(segment.cueout);
track.addcue(cue);
}
if ('cueoutcont' in segment) {
// entered into the middle of an ad cue
// assumes tag formate to be
// #ext-x-cue-out-cont:10/30
var _segment$cueoutcont$s = segment.cueoutcont.split('/').map(parsefloat),
adoffset = _segment$cueoutcont$s[0],
adtotal = _segment$cueoutcont$s[1];
cue = new global_window__webpack_imported_module_0___default.a.vttcue(mediatime, mediatime + segment.duration, '');
cue.adstarttime = mediatime - adoffset;
cue.adendtime = cue.adstarttime + adtotal;
track.addcue(cue);
}
}
mediatime += segment.duration;
}
}; // synchronize expired playlist segments.
// the max media sequence diff is 48 hours of live stream
// content with two second segments. anything larger than that
// will likely be invalid.
var max_media_sequence_diff_for_sync = 86400;
var syncpointstrategies = [// stategy "vod": handle the vod-case where the sync-point is *always*
// the equivalence display-time 0 === segment-index 0
{
name: 'vod',
run: function run(synccontroller, playlist, duration, currenttimeline, currenttime) {
if (duration !== infinity) {
var syncpoint = {
time: 0,
segmentindex: 0,
partindex: null
};
return syncpoint;
}
return null;
}
}, // stategy "programdatetime": we have a program-date-time tag in this playlist
{
name: 'programdatetime',
run: function run(synccontroller, playlist, duration, currenttimeline, currenttime) {
if (!object.keys(synccontroller.timelinetodatetimemappings).length) {
return null;
}
var syncpoint = null;
var lastdistance = null;
var partsandsegments = getpartsandsegments(playlist);
currenttime = currenttime || 0;
for (var i = 0; i < partsandsegments.length; i++) {
// start from the end and loop backwards for live
// or start from the front and loop forwards for non-live
var index = playlist.endlist || currenttime === 0 ? i : partsandsegments.length - (i + 1);
var partandsegment = partsandsegments[index];
var segment = partandsegment.segment;
var datetimemapping = synccontroller.timelinetodatetimemappings[segment.timeline];
if (!datetimemapping || !segment.datetimeobject) {
continue;
}
var segmenttime = segment.datetimeobject.gettime() / 1000;
var start = segmenttime + datetimemapping; // take part duration into account.
if (segment.parts && typeof partandsegment.partindex === 'number') {
for (var z = 0; z < partandsegment.partindex; z++) {
start += segment.parts[z].duration;
}
}
var distance = math.abs(currenttime - start); // once the distance begins to increase, or if distance is 0, we have passed
// currenttime and can stop looking for better candidates
if (lastdistance !== null && (distance === 0 || lastdistance < distance)) {
break;
}
lastdistance = distance;
syncpoint = {
time: start,
segmentindex: partandsegment.segmentindex,
partindex: partandsegment.partindex
};
}
return syncpoint;
}
}, // stategy "segment": we have a known time mapping for a timeline and a
// segment in the current timeline with timing data
{
name: 'segment',
run: function run(synccontroller, playlist, duration, currenttimeline, currenttime) {
var syncpoint = null;
var lastdistance = null;
currenttime = currenttime || 0;
var partsandsegments = getpartsandsegments(playlist);
for (var i = 0; i < partsandsegments.length; i++) {
// start from the end and loop backwards for live
// or start from the front and loop forwards for non-live
var index = playlist.endlist || currenttime === 0 ? i : partsandsegments.length - (i + 1);
var partandsegment = partsandsegments[index];
var segment = partandsegment.segment;
var start = partandsegment.part && partandsegment.part.start || segment && segment.start;
if (segment.timeline === currenttimeline && typeof start !== 'undefined') {
var distance = math.abs(currenttime - start); // once the distance begins to increase, we have passed
// currenttime and can stop looking for better candidates
if (lastdistance !== null && lastdistance < distance) {
break;
}
if (!syncpoint || lastdistance === null || lastdistance >= distance) {
lastdistance = distance;
syncpoint = {
time: start,
segmentindex: partandsegment.segmentindex,
partindex: partandsegment.partindex
};
}
}
}
return syncpoint;
}
}, // stategy "discontinuity": we have a discontinuity with a known
// display-time
{
name: 'discontinuity',
run: function run(synccontroller, playlist, duration, currenttimeline, currenttime) {
var syncpoint = null;
currenttime = currenttime || 0;
if (playlist.discontinuitystarts && playlist.discontinuitystarts.length) {
var lastdistance = null;
for (var i = 0; i < playlist.discontinuitystarts.length; i++) {
var segmentindex = playlist.discontinuitystarts[i];
var discontinuity = playlist.discontinuitysequence + i + 1;
var discontinuitysync = synccontroller.discontinuities[discontinuity];
if (discontinuitysync) {
var distance = math.abs(currenttime - discontinuitysync.time); // once the distance begins to increase, we have passed
// currenttime and can stop looking for better candidates
if (lastdistance !== null && lastdistance < distance) {
break;
}
if (!syncpoint || lastdistance === null || lastdistance >= distance) {
lastdistance = distance;
syncpoint = {
time: discontinuitysync.time,
segmentindex: segmentindex,
partindex: null
};
}
}
}
}
return syncpoint;
}
}, // stategy "playlist": we have a playlist with a known mapping of
// segment index to display time
{
name: 'playlist',
run: function run(synccontroller, playlist, duration, currenttimeline, currenttime) {
if (playlist.syncinfo) {
var syncpoint = {
time: playlist.syncinfo.time,
segmentindex: playlist.syncinfo.mediasequence - playlist.mediasequence,
partindex: null
};
return syncpoint;
}
return null;
}
}];
var synccontroller = /*#__pure__*/function (_videojs$eventtarget) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(synccontroller, _videojs$eventtarget);
function synccontroller(options) {
var _this;
_this = _videojs$eventtarget.call(this) || this; // ...for synching across variants
_this.timelines = [];
_this.discontinuities = [];
_this.timelinetodatetimemappings = {};
_this.logger_ = logger('synccontroller');
return _this;
}
/**
* find a sync-point for the playlist specified
*
* a sync-point is defined as a known mapping from display-time to
* a segment-index in the current playlist.
*
* @param {playlist} playlist
* the playlist that needs a sync-point
* @param {number} duration
* duration of the mediasource (infinite if playing a live source)
* @param {number} currenttimeline
* the last timeline from which a segment was loaded
* @return {object}
* a sync-point object
*/
var _proto = synccontroller.prototype;
_proto.getsyncpoint = function getsyncpoint(playlist, duration, currenttimeline, currenttime) {
var syncpoints = this.runstrategies_(playlist, duration, currenttimeline, currenttime);
if (!syncpoints.length) {
// signal that we need to attempt to get a sync-point manually
// by fetching a segment in the playlist and constructing
// a sync-point from that information
return null;
} // now find the sync-point that is closest to the currenttime because
// that should result in the most accurate guess about which segment
// to fetch
return this.selectsyncpoint_(syncpoints, {
key: 'time',
value: currenttime
});
}
/**
* calculate the amount of time that has expired off the playlist during playback
*
* @param {playlist} playlist
* playlist object to calculate expired from
* @param {number} duration
* duration of the mediasource (infinity if playling a live source)
* @return {number|null}
* the amount of time that has expired off the playlist during playback. null
* if no sync-points for the playlist can be found.
*/
;
_proto.getexpiredtime = function getexpiredtime(playlist, duration) {
if (!playlist || !playlist.segments) {
return null;
}
var syncpoints = this.runstrategies_(playlist, duration, playlist.discontinuitysequence, 0); // without sync-points, there is not enough information to determine the expired time
if (!syncpoints.length) {
return null;
}
var syncpoint = this.selectsyncpoint_(syncpoints, {
key: 'segmentindex',
value: 0
}); // if the sync-point is beyond the start of the playlist, we want to subtract the
// duration from index 0 to syncpoint.segmentindex instead of adding.
if (syncpoint.segmentindex > 0) {
syncpoint.time *= -1;
}
return math.abs(syncpoint.time + sumdurations({
defaultduration: playlist.targetduration,
durationlist: playlist.segments,
startindex: syncpoint.segmentindex,
endindex: 0
}));
}
/**
* runs each sync-point strategy and returns a list of sync-points returned by the
* strategies
*
* @private
* @param {playlist} playlist
* the playlist that needs a sync-point
* @param {number} duration
* duration of the mediasource (infinity if playing a live source)
* @param {number} currenttimeline
* the last timeline from which a segment was loaded
* @return {array}
* a list of sync-point objects
*/
;
_proto.runstrategies_ = function runstrategies_(playlist, duration, currenttimeline, currenttime) {
var syncpoints = []; // try to find a sync-point in by utilizing various strategies...
for (var i = 0; i < syncpointstrategies.length; i++) {
var strategy = syncpointstrategies[i];
var syncpoint = strategy.run(this, playlist, duration, currenttimeline, currenttime);
if (syncpoint) {
syncpoint.strategy = strategy.name;
syncpoints.push({
strategy: strategy.name,
syncpoint: syncpoint
});
}
}
return syncpoints;
}
/**
* selects the sync-point nearest the specified target
*
* @private
* @param {array} syncpoints
* list of sync-points to select from
* @param {object} target
* object specifying the property and value we are targeting
* @param {string} target.key
* specifies the property to target. must be either 'time' or 'segmentindex'
* @param {number} target.value
* the value to target for the specified key.
* @return {object}
* the sync-point nearest the target
*/
;
_proto.selectsyncpoint_ = function selectsyncpoint_(syncpoints, target) {
var bestsyncpoint = syncpoints[0].syncpoint;
var bestdistance = math.abs(syncpoints[0].syncpoint[target.key] - target.value);
var beststrategy = syncpoints[0].strategy;
for (var i = 1; i < syncpoints.length; i++) {
var newdistance = math.abs(syncpoints[i].syncpoint[target.key] - target.value);
if (newdistance < bestdistance) {
bestdistance = newdistance;
bestsyncpoint = syncpoints[i].syncpoint;
beststrategy = syncpoints[i].strategy;
}
}
this.logger_("syncpoint for [" + target.key + ": " + target.value + "] chosen with strategy" + (" [" + beststrategy + "]: [time:" + bestsyncpoint.time + ",") + (" segmentindex:" + bestsyncpoint.segmentindex) + (typeof bestsyncpoint.partindex === 'number' ? ",partindex:" + bestsyncpoint.partindex : '') + ']');
return bestsyncpoint;
}
/**
* save any meta-data present on the segments when segments leave
* the live window to the playlist to allow for synchronization at the
* playlist level later.
*
* @param {playlist} oldplaylist - the previous active playlist
* @param {playlist} newplaylist - the updated and most current playlist
*/
;
_proto.saveexpiredsegmentinfo = function saveexpiredsegmentinfo(oldplaylist, newplaylist) {
var mediasequencediff = newplaylist.mediasequence - oldplaylist.mediasequence; // ignore large media sequence gaps
if (mediasequencediff > max_media_sequence_diff_for_sync) {
videojs.log.warn("not saving expired segment info. media sequence gap " + mediasequencediff + " is too large.");
return;
} // when a segment expires from the playlist and it has a start time
// save that information as a possible sync-point reference in future
for (var i = mediasequencediff - 1; i >= 0; i--) {
var lastremovedsegment = oldplaylist.segments[i];
if (lastremovedsegment && typeof lastremovedsegment.start !== 'undefined') {
newplaylist.syncinfo = {
mediasequence: oldplaylist.mediasequence + i,
time: lastremovedsegment.start
};
this.logger_("playlist refresh sync: [time:" + newplaylist.syncinfo.time + "," + (" mediasequence: " + newplaylist.syncinfo.mediasequence + "]"));
this.trigger('syncinfoupdate');
break;
}
}
}
/**
* save the mapping from playlist's programdatetime to display. this should only happen
* before segments start to load.
*
* @param {playlist} playlist - the currently active playlist
*/
;
_proto.setdatetimemappingforstart = function setdatetimemappingforstart(playlist) {
// it's possible for the playlist to be updated before playback starts, meaning time
// zero is not yet set. if, during these playlist refreshes, a discontinuity is
// crossed, then the old time zero mapping (for the prior timeline) would be retained
// unless the mappings are cleared.
this.timelinetodatetimemappings = {};
if (playlist.segments && playlist.segments.length && playlist.segments[0].datetimeobject) {
var firstsegment = playlist.segments[0];
var playlisttimestamp = firstsegment.datetimeobject.gettime() / 1000;
this.timelinetodatetimemappings[firstsegment.timeline] = -playlisttimestamp;
}
}
/**
* calculates and saves timeline mappings, playlist sync info, and segment timing values
* based on the latest timing information.
*
* @param {object} options
* options object
* @param {segmentinfo} options.segmentinfo
* the current active request information
* @param {boolean} options.shouldsavetimelinemapping
* if there's a timeline change, determines if the timeline mapping should be
* saved for timeline mapping and program date time mappings.
*/
;
_proto.savesegmenttiminginfo = function savesegmenttiminginfo(_ref) {
var segmentinfo = _ref.segmentinfo,
shouldsavetimelinemapping = _ref.shouldsavetimelinemapping;
var didcalculatesegmenttimemapping = this.calculatesegmenttimemapping_(segmentinfo, segmentinfo.timinginfo, shouldsavetimelinemapping);
var segment = segmentinfo.segment;
if (didcalculatesegmenttimemapping) {
this.savediscontinuitysyncinfo_(segmentinfo); // if the playlist does not have sync information yet, record that information
// now with segment timing information
if (!segmentinfo.playlist.syncinfo) {
segmentinfo.playlist.syncinfo = {
mediasequence: segmentinfo.playlist.mediasequence + segmentinfo.mediaindex,
time: segment.start
};
}
}
var datetime = segment.datetimeobject;
if (segment.discontinuity && shouldsavetimelinemapping && datetime) {
this.timelinetodatetimemappings[segment.timeline] = -(datetime.gettime() / 1000);
}
};
_proto.timestampoffsetfortimeline = function timestampoffsetfortimeline(timeline) {
if (typeof this.timelines[timeline] === 'undefined') {
return null;
}
return this.timelines[timeline].time;
};
_proto.mappingfortimeline = function mappingfortimeline(timeline) {
if (typeof this.timelines[timeline] === 'undefined') {
return null;
}
return this.timelines[timeline].mapping;
}
/**
* use the "media time" for a segment to generate a mapping to "display time" and
* save that display time to the segment.
*
* @private
* @param {segmentinfo} segmentinfo
* the current active request information
* @param {object} timinginfo
* the start and end time of the current segment in "media time"
* @param {boolean} shouldsavetimelinemapping
* if there's a timeline change, determines if the timeline mapping should be
* saved in timelines.
* @return {boolean}
* returns false if segment time mapping could not be calculated
*/
;
_proto.calculatesegmenttimemapping_ = function calculatesegmenttimemapping_(segmentinfo, timinginfo, shouldsavetimelinemapping) {
// todo: remove side effects
var segment = segmentinfo.segment;
var part = segmentinfo.part;
var mappingobj = this.timelines[segmentinfo.timeline];
var start;
var end;
if (typeof segmentinfo.timestampoffset === 'number') {
mappingobj = {
time: segmentinfo.startofsegment,
mapping: segmentinfo.startofsegment - timinginfo.start
};
if (shouldsavetimelinemapping) {
this.timelines[segmentinfo.timeline] = mappingobj;
this.trigger('timestampoffset');
this.logger_("time mapping for timeline " + segmentinfo.timeline + ": " + ("[time: " + mappingobj.time + "] [mapping: " + mappingobj.mapping + "]"));
}
start = segmentinfo.startofsegment;
end = timinginfo.end + mappingobj.mapping;
} else if (mappingobj) {
start = timinginfo.start + mappingobj.mapping;
end = timinginfo.end + mappingobj.mapping;
} else {
return false;
}
if (part) {
part.start = start;
part.end = end;
} // if we don't have a segment start yet or the start value we got
// is less than our current segment.start value, save a new start value.
// we have to do this because parts will have segment timing info saved
// multiple times and we want segment start to be the earliest part start
// value for that segment.
if (!segment.start || start < segment.start) {
segment.start = start;
}
segment.end = end;
return true;
}
/**
* each time we have discontinuity in the playlist, attempt to calculate the location
* in display of the start of the discontinuity and save that. we also save an accuracy
* value so that we save values with the most accuracy (closest to 0.)
*
* @private
* @param {segmentinfo} segmentinfo - the current active request information
*/
;
_proto.savediscontinuitysyncinfo_ = function savediscontinuitysyncinfo_(segmentinfo) {
var playlist = segmentinfo.playlist;
var segment = segmentinfo.segment; // if the current segment is a discontinuity then we know exactly where
// the start of the range and it's accuracy is 0 (greater accuracy values
// mean more approximation)
if (segment.discontinuity) {
this.discontinuities[segment.timeline] = {
time: segment.start,
accuracy: 0
};
} else if (playlist.discontinuitystarts && playlist.discontinuitystarts.length) {
// search for future discontinuities that we can provide better timing
// information for and save that information for sync purposes
for (var i = 0; i < playlist.discontinuitystarts.length; i++) {
var segmentindex = playlist.discontinuitystarts[i];
var discontinuity = playlist.discontinuitysequence + i + 1;
var mediaindexdiff = segmentindex - segmentinfo.mediaindex;
var accuracy = math.abs(mediaindexdiff);
if (!this.discontinuities[discontinuity] || this.discontinuities[discontinuity].accuracy > accuracy) {
var time = void 0;
if (mediaindexdiff < 0) {
time = segment.start - sumdurations({
defaultduration: playlist.targetduration,
durationlist: playlist.segments,
startindex: segmentinfo.mediaindex,
endindex: segmentindex
});
} else {
time = segment.end + sumdurations({
defaultduration: playlist.targetduration,
durationlist: playlist.segments,
startindex: segmentinfo.mediaindex + 1,
endindex: segmentindex
});
}
this.discontinuities[discontinuity] = {
time: time,
accuracy: accuracy
};
}
}
}
};
_proto.dispose = function dispose() {
this.trigger('dispose');
this.off();
};
return synccontroller;
}(videojs.eventtarget);
/**
* the timelinechangecontroller acts as a source for segment loaders to listen for and
* keep track of latest and pending timeline changes. this is useful to ensure proper
* sync, as each loader may need to make a consideration for what timeline the other
* loader is on before making changes which could impact the other loader's media.
*
* @class timelinechangecontroller
* @extends videojs.eventtarget
*/
var timelinechangecontroller = /*#__pure__*/function (_videojs$eventtarget) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(timelinechangecontroller, _videojs$eventtarget);
function timelinechangecontroller() {
var _this;
_this = _videojs$eventtarget.call(this) || this;
_this.pendingtimelinechanges_ = {};
_this.lasttimelinechanges_ = {};
return _this;
}
var _proto = timelinechangecontroller.prototype;
_proto.clearpendingtimelinechange = function clearpendingtimelinechange(type) {
this.pendingtimelinechanges_[type] = null;
this.trigger('pendingtimelinechange');
};
_proto.pendingtimelinechange = function pendingtimelinechange(_ref) {
var type = _ref.type,
from = _ref.from,
to = _ref.to;
if (typeof from === 'number' && typeof to === 'number') {
this.pendingtimelinechanges_[type] = {
type: type,
from: from,
to: to
};
this.trigger('pendingtimelinechange');
}
return this.pendingtimelinechanges_[type];
};
_proto.lasttimelinechange = function lasttimelinechange(_ref2) {
var type = _ref2.type,
from = _ref2.from,
to = _ref2.to;
if (typeof from === 'number' && typeof to === 'number') {
this.lasttimelinechanges_[type] = {
type: type,
from: from,
to: to
};
delete this.pendingtimelinechanges_[type];
this.trigger('timelinechange');
}
return this.lasttimelinechanges_[type];
};
_proto.dispose = function dispose() {
this.trigger('dispose');
this.pendingtimelinechanges_ = {};
this.lasttimelinechanges_ = {};
this.off();
};
return timelinechangecontroller;
}(videojs.eventtarget);
/* rollup-plugin-worker-factory start for worker!/home/runner/work/http-streaming/http-streaming/src/decrypter-worker.js */
var workercode = transform(getworkerstring(function () {
var commonjsglobal = typeof globalthis !== 'undefined' ? globalthis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
function createcommonjsmodule(fn, basedir, module) {
return module = {
path: basedir,
exports: {},
require: function require(path, base) {
return commonjsrequire(path, base === undefined || base === null ? module.path : base);
}
}, fn(module, module.exports), module.exports;
}
function commonjsrequire() {
throw new error('dynamic requires are not currently supported by @rollup/plugin-commonjs');
}
var createclass = createcommonjsmodule(function (module) {
function _defineproperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
object.defineproperty(target, descriptor.key, descriptor);
}
}
function _createclass(constructor, protoprops, staticprops) {
if (protoprops) _defineproperties(constructor.prototype, protoprops);
if (staticprops) _defineproperties(constructor, staticprops);
return constructor;
}
module.exports = _createclass;
module.exports["default"] = module.exports, module.exports.__esmodule = true;
});
var setprototypeof = createcommonjsmodule(function (module) {
function _setprototypeof(o, p) {
module.exports = _setprototypeof = object.setprototypeof || function _setprototypeof(o, p) {
o.__proto__ = p;
return o;
};
module.exports["default"] = module.exports, module.exports.__esmodule = true;
return _setprototypeof(o, p);
}
module.exports = _setprototypeof;
module.exports["default"] = module.exports, module.exports.__esmodule = true;
});
var inheritsloose = createcommonjsmodule(function (module) {
function _inheritsloose(subclass, superclass) {
subclass.prototype = object.create(superclass.prototype);
subclass.prototype.constructor = subclass;
setprototypeof(subclass, superclass);
}
module.exports = _inheritsloose;
module.exports["default"] = module.exports, module.exports.__esmodule = true;
});
/**
* @file stream.js
*/
/**
* a lightweight readable stream implemention that handles event dispatching.
*
* @class stream
*/
var stream = /*#__pure__*/function () {
function stream() {
this.listeners = {};
}
/**
* add a listener for a specified event type.
*
* @param {string} type the event name
* @param {function} listener the callback to be invoked when an event of
* the specified type occurs
*/
var _proto = stream.prototype;
_proto.on = function on(type, listener) {
if (!this.listeners[type]) {
this.listeners[type] = [];
}
this.listeners[type].push(listener);
}
/**
* remove a listener for a specified event type.
*
* @param {string} type the event name
* @param {function} listener a function previously registered for this
* type of event through `on`
* @return {boolean} if we could turn it off or not
*/
;
_proto.off = function off(type, listener) {
if (!this.listeners[type]) {
return false;
}
var index = this.listeners[type].indexof(listener); // todo: which is better?
// in video.js we slice listener functions
// on trigger so that it does not mess up the order
// while we loop through.
//
// here we slice on off so that the loop in trigger
// can continue using it's old reference to loop without
// messing up the order.
this.listeners[type] = this.listeners[type].slice(0);
this.listeners[type].splice(index, 1);
return index > -1;
}
/**
* trigger an event of the specified type on this stream. any additional
* arguments to this function are passed as parameters to event listeners.
*
* @param {string} type the event name
*/
;
_proto.trigger = function trigger(type) {
var callbacks = this.listeners[type];
if (!callbacks) {
return;
} // slicing the arguments on every invocation of this method
// can add a significant amount of overhead. avoid the
// intermediate object creation for the common case of a
// single callback argument
if (arguments.length === 2) {
var length = callbacks.length;
for (var i = 0; i < length; ++i) {
callbacks[i].call(this, arguments[1]);
}
} else {
var args = array.prototype.slice.call(arguments, 1);
var _length = callbacks.length;
for (var _i = 0; _i < _length; ++_i) {
callbacks[_i].apply(this, args);
}
}
}
/**
* destroys the stream and cleans up.
*/
;
_proto.dispose = function dispose() {
this.listeners = {};
}
/**
* forwards all `data` events on this stream to the destination stream. the
* destination stream should provide a method `push` to receive the data
* events as they arrive.
*
* @param {stream} destination the stream that will receive all `data` events
* @see http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
*/
;
_proto.pipe = function pipe(destination) {
this.on('data', function (data) {
destination.push(data);
});
};
return stream;
}();
/*! @name pkcs7 @version 1.0.4 @license apache-2.0 */
/**
* returns the subarray of a uint8array without pkcs#7 padding.
*
* @param padded {uint8array} unencrypted bytes that have been padded
* @return {uint8array} the unpadded bytes
* @see http://tools.ietf.org/html/rfc5652
*/
function unpad(padded) {
return padded.subarray(0, padded.bytelength - padded[padded.bytelength - 1]);
}
/*! @name aes-decrypter @version 3.1.3 @license apache-2.0 */
/**
* @file aes.js
*
* this file contains an adaptation of the aes decryption algorithm
* from the standford javascript cryptography library. that work is
* covered by the following copyright and permissions notice:
*
* copyright 2009-2010 emily stark, mike hamburg, dan boneh.
* all rights reserved.
*
* redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. 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.
*
* this software is provided by the authors ``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 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.
*
* the views and conclusions contained in the software and documentation
* are those of the authors and should not be interpreted as representing
* official policies, either expressed or implied, of the authors.
*/
/**
* expand the s-box tables.
*
* @private
*/
var precompute = function precompute() {
var tables = [[[], [], [], [], []], [[], [], [], [], []]];
var enctable = tables[0];
var dectable = tables[1];
var sbox = enctable[4];
var sboxinv = dectable[4];
var i;
var x;
var xinv;
var d = [];
var th = [];
var x2;
var x4;
var x8;
var s;
var tenc;
var tdec; // compute double and third tables
for (i = 0; i < 256; i++) {
th[(d[i] = i << 1 ^ (i >> 7) * 283) ^ i] = i;
}
for (x = xinv = 0; !sbox[x]; x ^= x2 || 1, xinv = th[xinv] || 1) {
// compute sbox
s = xinv ^ xinv << 1 ^ xinv << 2 ^ xinv << 3 ^ xinv << 4;
s = s >> 8 ^ s & 255 ^ 99;
sbox[x] = s;
sboxinv[s] = x; // compute mixcolumns
x8 = d[x4 = d[x2 = d[x]]];
tdec = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100;
tenc = d[s] * 0x101 ^ s * 0x1010100;
for (i = 0; i < 4; i++) {
enctable[i][x] = tenc = tenc << 24 ^ tenc >>> 8;
dectable[i][s] = tdec = tdec << 24 ^ tdec >>> 8;
}
} // compactify. considerable speedup on firefox.
for (i = 0; i < 5; i++) {
enctable[i] = enctable[i].slice(0);
dectable[i] = dectable[i].slice(0);
}
return tables;
};
var aestables = null;
/**
* schedule out an aes key for both encryption and decryption. this
* is a low-level class. use a cipher mode to do bulk encryption.
*
* @class aes
* @param key {array} the key as an array of 4, 6 or 8 words.
*/
var aes = /*#__pure__*/function () {
function aes(key) {
/**
* the expanded s-box and inverse s-box tables. these will be computed
* on the client so that we don't have to send them down the wire.
*
* there are two tables, _tables[0] is for encryption and
* _tables[1] is for decryption.
*
* the first 4 sub-tables are the expanded s-box with mixcolumns. the
* last (_tables[01][4]) is the s-box itself.
*
* @private
*/
// if we have yet to precompute the s-box tables
// do so now
if (!aestables) {
aestables = precompute();
} // then make a copy of that object for use
this._tables = [[aestables[0][0].slice(), aestables[0][1].slice(), aestables[0][2].slice(), aestables[0][3].slice(), aestables[0][4].slice()], [aestables[1][0].slice(), aestables[1][1].slice(), aestables[1][2].slice(), aestables[1][3].slice(), aestables[1][4].slice()]];
var i;
var j;
var tmp;
var sbox = this._tables[0][4];
var dectable = this._tables[1];
var keylen = key.length;
var rcon = 1;
if (keylen !== 4 && keylen !== 6 && keylen !== 8) {
throw new error('invalid aes key size');
}
var enckey = key.slice(0);
var deckey = [];
this._key = [enckey, deckey]; // schedule encryption keys
for (i = keylen; i < 4 * keylen + 28; i++) {
tmp = enckey[i - 1]; // apply sbox
if (i % keylen === 0 || keylen === 8 && i % keylen === 4) {
tmp = sbox[tmp >>> 24] << 24 ^ sbox[tmp >> 16 & 255] << 16 ^ sbox[tmp >> 8 & 255] << 8 ^ sbox[tmp & 255]; // shift rows and add rcon
if (i % keylen === 0) {
tmp = tmp << 8 ^ tmp >>> 24 ^ rcon << 24;
rcon = rcon << 1 ^ (rcon >> 7) * 283;
}
}
enckey[i] = enckey[i - keylen] ^ tmp;
} // schedule decryption keys
for (j = 0; i; j++, i--) {
tmp = enckey[j & 3 ? i : i - 4];
if (i <= 4 || j < 4) {
deckey[j] = tmp;
} else {
deckey[j] = dectable[0][sbox[tmp >>> 24]] ^ dectable[1][sbox[tmp >> 16 & 255]] ^ dectable[2][sbox[tmp >> 8 & 255]] ^ dectable[3][sbox[tmp & 255]];
}
}
}
/**
* decrypt 16 bytes, specified as four 32-bit words.
*
* @param {number} encrypted0 the first word to decrypt
* @param {number} encrypted1 the second word to decrypt
* @param {number} encrypted2 the third word to decrypt
* @param {number} encrypted3 the fourth word to decrypt
* @param {int32array} out the array to write the decrypted words
* into
* @param {number} offset the offset into the output array to start
* writing results
* @return {array} the plaintext.
*/
var _proto = aes.prototype;
_proto.decrypt = function decrypt(encrypted0, encrypted1, encrypted2, encrypted3, out, offset) {
var key = this._key[1]; // state variables a,b,c,d are loaded with pre-whitened data
var a = encrypted0 ^ key[0];
var b = encrypted3 ^ key[1];
var c = encrypted2 ^ key[2];
var d = encrypted1 ^ key[3];
var a2;
var b2;
var c2; // key.length === 2 ?
var ninnerrounds = key.length / 4 - 2;
var i;
var kindex = 4;
var table = this._tables[1]; // load up the tables
var table0 = table[0];
var table1 = table[1];
var table2 = table[2];
var table3 = table[3];
var sbox = table[4]; // inner rounds. cribbed from openssl.
for (i = 0; i < ninnerrounds; i++) {
a2 = table0[a >>> 24] ^ table1[b >> 16 & 255] ^ table2[c >> 8 & 255] ^ table3[d & 255] ^ key[kindex];
b2 = table0[b >>> 24] ^ table1[c >> 16 & 255] ^ table2[d >> 8 & 255] ^ table3[a & 255] ^ key[kindex + 1];
c2 = table0[c >>> 24] ^ table1[d >> 16 & 255] ^ table2[a >> 8 & 255] ^ table3[b & 255] ^ key[kindex + 2];
d = table0[d >>> 24] ^ table1[a >> 16 & 255] ^ table2[b >> 8 & 255] ^ table3[c & 255] ^ key[kindex + 3];
kindex += 4;
a = a2;
b = b2;
c = c2;
} // last round.
for (i = 0; i < 4; i++) {
out[(3 & -i) + offset] = sbox[a >>> 24] << 24 ^ sbox[b >> 16 & 255] << 16 ^ sbox[c >> 8 & 255] << 8 ^ sbox[d & 255] ^ key[kindex++];
a2 = a;
a = b;
b = c;
c = d;
d = a2;
}
};
return aes;
}();
/**
* a wrapper around the stream class to use settimeout
* and run stream "jobs" asynchronously
*
* @class asyncstream
* @extends stream
*/
var asyncstream = /*#__pure__*/function (_stream) {
inheritsloose(asyncstream, _stream);
function asyncstream() {
var _this;
_this = _stream.call(this, stream) || this;
_this.jobs = [];
_this.delay = 1;
_this.timeout_ = null;
return _this;
}
/**
* process an async job
*
* @private
*/
var _proto = asyncstream.prototype;
_proto.processjob_ = function processjob_() {
this.jobs.shift()();
if (this.jobs.length) {
this.timeout_ = settimeout(this.processjob_.bind(this), this.delay);
} else {
this.timeout_ = null;
}
}
/**
* push a job into the stream
*
* @param {function} job the job to push into the stream
*/
;
_proto.push = function push(job) {
this.jobs.push(job);
if (!this.timeout_) {
this.timeout_ = settimeout(this.processjob_.bind(this), this.delay);
}
};
return asyncstream;
}(stream);
/**
* convert network-order (big-endian) bytes into their little-endian
* representation.
*/
var ntoh = function ntoh(word) {
return word << 24 | (word & 0xff00) << 8 | (word & 0xff0000) >> 8 | word >>> 24;
};
/**
* decrypt bytes using aes-128 with cbc and pkcs#7 padding.
*
* @param {uint8array} encrypted the encrypted bytes
* @param {uint32array} key the bytes of the decryption key
* @param {uint32array} initvector the initialization vector (iv) to
* use for the first round of cbc.
* @return {uint8array} the decrypted bytes
*
* @see http://en.wikipedia.org/wiki/advanced_encryption_standard
* @see http://en.wikipedia.org/wiki/block_cipher_mode_of_operation#cipher_block_chaining_.28cbc.29
* @see https://tools.ietf.org/html/rfc2315
*/
var decrypt = function decrypt(encrypted, key, initvector) {
// word-level access to the encrypted bytes
var encrypted32 = new int32array(encrypted.buffer, encrypted.byteoffset, encrypted.bytelength >> 2);
var decipher = new aes(array.prototype.slice.call(key)); // byte and word-level access for the decrypted output
var decrypted = new uint8array(encrypted.bytelength);
var decrypted32 = new int32array(decrypted.buffer); // temporary variables for working with the iv, encrypted, and
// decrypted data
var init0;
var init1;
var init2;
var init3;
var encrypted0;
var encrypted1;
var encrypted2;
var encrypted3; // iteration variable
var wordix; // pull out the words of the iv to ensure we don't modify the
// passed-in reference and easier access
init0 = initvector[0];
init1 = initvector[1];
init2 = initvector[2];
init3 = initvector[3]; // decrypt four word sequences, applying cipher-block chaining (cbc)
// to each decrypted block
for (wordix = 0; wordix < encrypted32.length; wordix += 4) {
// convert big-endian (network order) words into little-endian
// (javascript order)
encrypted0 = ntoh(encrypted32[wordix]);
encrypted1 = ntoh(encrypted32[wordix + 1]);
encrypted2 = ntoh(encrypted32[wordix + 2]);
encrypted3 = ntoh(encrypted32[wordix + 3]); // decrypt the block
decipher.decrypt(encrypted0, encrypted1, encrypted2, encrypted3, decrypted32, wordix); // xor with the iv, and restore network byte-order to obtain the
// plaintext
decrypted32[wordix] = ntoh(decrypted32[wordix] ^ init0);
decrypted32[wordix + 1] = ntoh(decrypted32[wordix + 1] ^ init1);
decrypted32[wordix + 2] = ntoh(decrypted32[wordix + 2] ^ init2);
decrypted32[wordix + 3] = ntoh(decrypted32[wordix + 3] ^ init3); // setup the iv for the next round
init0 = encrypted0;
init1 = encrypted1;
init2 = encrypted2;
init3 = encrypted3;
}
return decrypted;
};
/**
* the `decrypter` class that manages decryption of aes
* data through `asyncstream` objects and the `decrypt`
* function
*
* @param {uint8array} encrypted the encrypted bytes
* @param {uint32array} key the bytes of the decryption key
* @param {uint32array} initvector the initialization vector (iv) to
* @param {function} done the function to run when done
* @class decrypter
*/
var decrypter = /*#__pure__*/function () {
function decrypter(encrypted, key, initvector, done) {
var step = decrypter.step;
var encrypted32 = new int32array(encrypted.buffer);
var decrypted = new uint8array(encrypted.bytelength);
var i = 0;
this.asyncstream_ = new asyncstream(); // split up the encryption job and do the individual chunks asynchronously
this.asyncstream_.push(this.decryptchunk_(encrypted32.subarray(i, i + step), key, initvector, decrypted));
for (i = step; i < encrypted32.length; i += step) {
initvector = new uint32array([ntoh(encrypted32[i - 4]), ntoh(encrypted32[i - 3]), ntoh(encrypted32[i - 2]), ntoh(encrypted32[i - 1])]);
this.asyncstream_.push(this.decryptchunk_(encrypted32.subarray(i, i + step), key, initvector, decrypted));
} // invoke the done() callback when everything is finished
this.asyncstream_.push(function () {
// remove pkcs#7 padding from the decrypted bytes
done(null, unpad(decrypted));
});
}
/**
* a getter for step the maximum number of bytes to process at one time
*
* @return {number} the value of step 32000
*/
var _proto = decrypter.prototype;
/**
* @private
*/
_proto.decryptchunk_ = function decryptchunk_(encrypted, key, initvector, decrypted) {
return function () {
var bytes = decrypt(encrypted, key, initvector);
decrypted.set(bytes, encrypted.byteoffset);
};
};
createclass(decrypter, null, [{
key: "step",
get: function get() {
// 4 * 8000;
return 32000;
}
}]);
return decrypter;
}();
var win;
if (typeof window !== "undefined") {
win = window;
} else if (typeof commonjsglobal !== "undefined") {
win = commonjsglobal;
} else if (typeof self !== "undefined") {
win = self;
} else {
win = {};
}
var window_1 = win;
var isarraybufferview = function isarraybufferview(obj) {
if (arraybuffer.isview === 'function') {
return arraybuffer.isview(obj);
}
return obj && obj.buffer instanceof arraybuffer;
};
var bigint = window_1.bigint || number;
[bigint('0x1'), bigint('0x100'), bigint('0x10000'), bigint('0x1000000'), bigint('0x100000000'), bigint('0x10000000000'), bigint('0x1000000000000'), bigint('0x100000000000000'), bigint('0x10000000000000000')];
/**
* creates an object for sending to a web worker modifying properties that are typedarrays
* into a new object with seperated properties for the buffer, byteoffset, and bytelength.
*
* @param {object} message
* object of properties and values to send to the web worker
* @return {object}
* modified message with typedarray values expanded
* @function createtransferablemessage
*/
var createtransferablemessage = function createtransferablemessage(message) {
var transferable = {};
object.keys(message).foreach(function (key) {
var value = message[key];
if (isarraybufferview(value)) {
transferable[key] = {
bytes: value.buffer,
byteoffset: value.byteoffset,
bytelength: value.bytelength
};
} else {
transferable[key] = value;
}
});
return transferable;
};
/* global self */
/**
* our web worker interface so that things can talk to aes-decrypter
* that will be running in a web worker. the scope is passed to this by
* webworkify.
*/
self.onmessage = function (event) {
var data = event.data;
var encrypted = new uint8array(data.encrypted.bytes, data.encrypted.byteoffset, data.encrypted.bytelength);
var key = new uint32array(data.key.bytes, data.key.byteoffset, data.key.bytelength / 4);
var iv = new uint32array(data.iv.bytes, data.iv.byteoffset, data.iv.bytelength / 4);
/* eslint-disable no-new, handle-callback-err */
new decrypter(encrypted, key, iv, function (err, bytes) {
self.postmessage(createtransferablemessage({
source: data.source,
decrypted: bytes
}), [bytes.buffer]);
});
/* eslint-enable */
};
}));
var decrypter = factory(workercode);
/* rollup-plugin-worker-factory end for worker!/home/runner/work/http-streaming/http-streaming/src/decrypter-worker.js */
/**
* convert the properties of an hls track into an audiotrackkind.
*
* @private
*/
var audiotrackkind_ = function audiotrackkind_(properties) {
var kind = properties["default"] ? 'main' : 'alternative';
if (properties.characteristics && properties.characteristics.indexof('public.accessibility.describes-video') >= 0) {
kind = 'main-desc';
}
return kind;
};
/**
* pause provided segment loader and playlist loader if active
*
* @param {segmentloader} segmentloader
* segmentloader to pause
* @param {object} mediatype
* active media type
* @function stoploaders
*/
var stoploaders = function stoploaders(segmentloader, mediatype) {
segmentloader.abort();
segmentloader.pause();
if (mediatype && mediatype.activeplaylistloader) {
mediatype.activeplaylistloader.pause();
mediatype.activeplaylistloader = null;
}
};
/**
* start loading provided segment loader and playlist loader
*
* @param {playlistloader} playlistloader
* playlistloader to start loading
* @param {object} mediatype
* active media type
* @function startloaders
*/
var startloaders = function startloaders(playlistloader, mediatype) {
// segment loader will be started after `loadedmetadata` or `loadedplaylist` from the
// playlist loader
mediatype.activeplaylistloader = playlistloader;
playlistloader.load();
};
/**
* returns a function to be called when the media group changes. it performs a
* non-destructive (preserve the buffer) resync of the segmentloader. this is because a
* change of group is merely a rendition switch of the same content at another encoding,
* rather than a change of content, such as switching audio from english to spanish.
*
* @param {string} type
* mediagroup type
* @param {object} settings
* object containing required information for media groups
* @return {function}
* handler for a non-destructive resync of segmentloader when the active media
* group changes.
* @function ongroupchanged
*/
var ongroupchanged = function ongroupchanged(type, settings) {
return function () {
var _settings$segmentload = settings.segmentloaders,
segmentloader = _settings$segmentload[type],
mainsegmentloader = _settings$segmentload.main,
mediatype = settings.mediatypes[type];
var activetrack = mediatype.activetrack();
var activegroup = mediatype.getactivegroup();
var previousactiveloader = mediatype.activeplaylistloader;
var lastgroup = mediatype.lastgroup_; // the group did not change do nothing
if (activegroup && lastgroup && activegroup.id === lastgroup.id) {
return;
}
mediatype.lastgroup_ = activegroup;
mediatype.lasttrack_ = activetrack;
stoploaders(segmentloader, mediatype);
if (!activegroup || activegroup.ismasterplaylist) {
// there is no group active or active group is a main playlist and won't change
return;
}
if (!activegroup.playlistloader) {
if (previousactiveloader) {
// the previous group had a playlist loader but the new active group does not
// this means we are switching from demuxed to muxed audio. in this case we want to
// do a destructive reset of the main segment loader and not restart the audio
// loaders.
mainsegmentloader.reseteverything();
}
return;
} // non-destructive resync
segmentloader.resyncloader();
startloaders(activegroup.playlistloader, mediatype);
};
};
var ongroupchanging = function ongroupchanging(type, settings) {
return function () {
var segmentloader = settings.segmentloaders[type],
mediatype = settings.mediatypes[type];
mediatype.lastgroup_ = null;
segmentloader.abort();
segmentloader.pause();
};
};
/**
* returns a function to be called when the media track changes. it performs a
* destructive reset of the segmentloader to ensure we start loading as close to
* currenttime as possible.
*
* @param {string} type
* mediagroup type
* @param {object} settings
* object containing required information for media groups
* @return {function}
* handler for a destructive reset of segmentloader when the active media
* track changes.
* @function ontrackchanged
*/
var ontrackchanged = function ontrackchanged(type, settings) {
return function () {
var masterplaylistloader = settings.masterplaylistloader,
_settings$segmentload2 = settings.segmentloaders,
segmentloader = _settings$segmentload2[type],
mainsegmentloader = _settings$segmentload2.main,
mediatype = settings.mediatypes[type];
var activetrack = mediatype.activetrack();
var activegroup = mediatype.getactivegroup();
var previousactiveloader = mediatype.activeplaylistloader;
var lasttrack = mediatype.lasttrack_; // track did not change, do nothing
if (lasttrack && activetrack && lasttrack.id === activetrack.id) {
return;
}
mediatype.lastgroup_ = activegroup;
mediatype.lasttrack_ = activetrack;
stoploaders(segmentloader, mediatype);
if (!activegroup) {
// there is no group active so we do not want to restart loaders
return;
}
if (activegroup.ismasterplaylist) {
// track did not change, do nothing
if (!activetrack || !lasttrack || activetrack.id === lasttrack.id) {
return;
}
var mpc = settings.vhs.masterplaylistcontroller_;
var newplaylist = mpc.selectplaylist(); // media will not change do nothing
if (mpc.media() === newplaylist) {
return;
}
mediatype.logger_("track change. switching master audio from " + lasttrack.id + " to " + activetrack.id);
masterplaylistloader.pause();
mainsegmentloader.reseteverything();
mpc.fastqualitychange_(newplaylist);
return;
}
if (type === 'audio') {
if (!activegroup.playlistloader) {
// when switching from demuxed audio/video to muxed audio/video (noted by no
// playlist loader for the audio group), we want to do a destructive reset of the
// main segment loader and not restart the audio loaders
mainsegmentloader.setaudio(true); // don't have to worry about disabling the audio of the audio segment loader since
// it should be stopped
mainsegmentloader.reseteverything();
return;
} // although the segment loader is an audio segment loader, call the setaudio
// function to ensure it is prepared to re-append the init segment (or handle other
// config changes)
segmentloader.setaudio(true);
mainsegmentloader.setaudio(false);
}
if (previousactiveloader === activegroup.playlistloader) {
// nothing has actually changed. this can happen because track change events can fire
// multiple times for a "single" change. one for enabling the new active track, and
// one for disabling the track that was active
startloaders(activegroup.playlistloader, mediatype);
return;
}
if (segmentloader.track) {
// for webvtt, set the new text track in the segmentloader
segmentloader.track(activetrack);
} // destructive reset
segmentloader.reseteverything();
startloaders(activegroup.playlistloader, mediatype);
};
};
var onerror = {
/**
* returns a function to be called when a segmentloader or playlistloader encounters
* an error.
*
* @param {string} type
* mediagroup type
* @param {object} settings
* object containing required information for media groups
* @return {function}
* error handler. logs warning (or error if the playlist is blacklisted) to
* console and switches back to default audio track.
* @function onerror.audio
*/
audio: function audio(type, settings) {
return function () {
var segmentloader = settings.segmentloaders[type],
mediatype = settings.mediatypes[type],
blacklistcurrentplaylist = settings.blacklistcurrentplaylist;
stoploaders(segmentloader, mediatype); // switch back to default audio track
var activetrack = mediatype.activetrack();
var activegroup = mediatype.activegroup();
var id = (activegroup.filter(function (group) {
return group["default"];
})[0] || activegroup[0]).id;
var defaulttrack = mediatype.tracks[id];
if (activetrack === defaulttrack) {
// default track encountered an error. all we can do now is blacklist the current
// rendition and hope another will switch audio groups
blacklistcurrentplaylist({
message: 'problem encountered loading the default audio track.'
});
return;
}
videojs.log.warn('problem encountered loading the alternate audio track.' + 'switching back to default.');
for (var trackid in mediatype.tracks) {
mediatype.tracks[trackid].enabled = mediatype.tracks[trackid] === defaulttrack;
}
mediatype.ontrackchanged();
};
},
/**
* returns a function to be called when a segmentloader or playlistloader encounters
* an error.
*
* @param {string} type
* mediagroup type
* @param {object} settings
* object containing required information for media groups
* @return {function}
* error handler. logs warning to console and disables the active subtitle track
* @function onerror.subtitles
*/
subtitles: function subtitles(type, settings) {
return function () {
var segmentloader = settings.segmentloaders[type],
mediatype = settings.mediatypes[type];
videojs.log.warn('problem encountered loading the subtitle track.' + 'disabling subtitle track.');
stoploaders(segmentloader, mediatype);
var track = mediatype.activetrack();
if (track) {
track.mode = 'disabled';
}
mediatype.ontrackchanged();
};
}
};
var setuplisteners = {
/**
* setup event listeners for audio playlist loader
*
* @param {string} type
* mediagroup type
* @param {playlistloader|null} playlistloader
* playlistloader to register listeners on
* @param {object} settings
* object containing required information for media groups
* @function setuplisteners.audio
*/
audio: function audio(type, playlistloader, settings) {
if (!playlistloader) {
// no playlist loader means audio will be muxed with the video
return;
}
var tech = settings.tech,
requestoptions = settings.requestoptions,
segmentloader = settings.segmentloaders[type];
playlistloader.on('loadedmetadata', function () {
var media = playlistloader.media();
segmentloader.playlist(media, requestoptions); // if the video is already playing, or if this isn't a live video and preload
// permits, start downloading segments
if (!tech.paused() || media.endlist && tech.preload() !== 'none') {
segmentloader.load();
}
});
playlistloader.on('loadedplaylist', function () {
segmentloader.playlist(playlistloader.media(), requestoptions); // if the player isn't paused, ensure that the segment loader is running
if (!tech.paused()) {
segmentloader.load();
}
});
playlistloader.on('error', onerror[type](type, settings));
},
/**
* setup event listeners for subtitle playlist loader
*
* @param {string} type
* mediagroup type
* @param {playlistloader|null} playlistloader
* playlistloader to register listeners on
* @param {object} settings
* object containing required information for media groups
* @function setuplisteners.subtitles
*/
subtitles: function subtitles(type, playlistloader, settings) {
var tech = settings.tech,
requestoptions = settings.requestoptions,
segmentloader = settings.segmentloaders[type],
mediatype = settings.mediatypes[type];
playlistloader.on('loadedmetadata', function () {
var media = playlistloader.media();
segmentloader.playlist(media, requestoptions);
segmentloader.track(mediatype.activetrack()); // if the video is already playing, or if this isn't a live video and preload
// permits, start downloading segments
if (!tech.paused() || media.endlist && tech.preload() !== 'none') {
segmentloader.load();
}
});
playlistloader.on('loadedplaylist', function () {
segmentloader.playlist(playlistloader.media(), requestoptions); // if the player isn't paused, ensure that the segment loader is running
if (!tech.paused()) {
segmentloader.load();
}
});
playlistloader.on('error', onerror[type](type, settings));
}
};
var initialize = {
/**
* setup playlistloaders and audiotracks for the audio groups
*
* @param {string} type
* mediagroup type
* @param {object} settings
* object containing required information for media groups
* @function initialize.audio
*/
'audio': function audio(type, settings) {
var vhs = settings.vhs,
sourcetype = settings.sourcetype,
segmentloader = settings.segmentloaders[type],
requestoptions = settings.requestoptions,
mediagroups = settings.master.mediagroups,
_settings$mediatypes$ = settings.mediatypes[type],
groups = _settings$mediatypes$.groups,
tracks = _settings$mediatypes$.tracks,
logger_ = _settings$mediatypes$.logger_,
masterplaylistloader = settings.masterplaylistloader;
var audioonlymaster = isaudioonly(masterplaylistloader.master); // force a default if we have none
if (!mediagroups[type] || object.keys(mediagroups[type]).length === 0) {
mediagroups[type] = {
main: {
"default": {
"default": true
}
}
};
if (audioonlymaster) {
mediagroups[type].main["default"].playlists = masterplaylistloader.master.playlists;
}
}
for (var groupid in mediagroups[type]) {
if (!groups[groupid]) {
groups[groupid] = [];
}
for (var variantlabel in mediagroups[type][groupid]) {
var properties = mediagroups[type][groupid][variantlabel];
var playlistloader = void 0;
if (audioonlymaster) {
logger_("audio group '" + groupid + "' label '" + variantlabel + "' is a master playlist");
properties.ismasterplaylist = true;
playlistloader = null; // if vhs-json was provided as the source, and the media playlist was resolved,
// use the resolved media playlist object
} else if (sourcetype === 'vhs-json' && properties.playlists) {
playlistloader = new playlistloader(properties.playlists[0], vhs, requestoptions);
} else if (properties.resolveduri) {
playlistloader = new playlistloader(properties.resolveduri, vhs, requestoptions); // todo: dash isn't the only type with properties.playlists
// should we even have properties.playlists in this check.
} else if (properties.playlists && sourcetype === 'dash') {
playlistloader = new dashplaylistloader(properties.playlists[0], vhs, requestoptions, masterplaylistloader);
} else {
// no resolveduri means the audio is muxed with the video when using this
// audio track
playlistloader = null;
}
properties = videojs.mergeoptions({
id: variantlabel,
playlistloader: playlistloader
}, properties);
setuplisteners[type](type, properties.playlistloader, settings);
groups[groupid].push(properties);
if (typeof tracks[variantlabel] === 'undefined') {
var track = new videojs.audiotrack({
id: variantlabel,
kind: audiotrackkind_(properties),
enabled: false,
language: properties.language,
"default": properties["default"],
label: variantlabel
});
tracks[variantlabel] = track;
}
}
} // setup single error event handler for the segment loader
segmentloader.on('error', onerror[type](type, settings));
},
/**
* setup playlistloaders and texttracks for the subtitle groups
*
* @param {string} type
* mediagroup type
* @param {object} settings
* object containing required information for media groups
* @function initialize.subtitles
*/
'subtitles': function subtitles(type, settings) {
var tech = settings.tech,
vhs = settings.vhs,
sourcetype = settings.sourcetype,
segmentloader = settings.segmentloaders[type],
requestoptions = settings.requestoptions,
mediagroups = settings.master.mediagroups,
_settings$mediatypes$2 = settings.mediatypes[type],
groups = _settings$mediatypes$2.groups,
tracks = _settings$mediatypes$2.tracks,
masterplaylistloader = settings.masterplaylistloader;
for (var groupid in mediagroups[type]) {
if (!groups[groupid]) {
groups[groupid] = [];
}
for (var variantlabel in mediagroups[type][groupid]) {
if (mediagroups[type][groupid][variantlabel].forced) {
// subtitle playlists with the forced attribute are not selectable in safari.
// according to apple's hls authoring specification:
// if content has forced subtitles and regular subtitles in a given language,
// the regular subtitles track in that language must contain both the forced
// subtitles and the regular subtitles for that language.
// because of this requirement and that safari does not add forced subtitles,
// forced subtitles are skipped here to maintain consistent experience across
// all platforms
continue;
}
var properties = mediagroups[type][groupid][variantlabel];
var playlistloader = void 0;
if (sourcetype === 'hls') {
playlistloader = new playlistloader(properties.resolveduri, vhs, requestoptions);
} else if (sourcetype === 'dash') {
var playlists = properties.playlists.filter(function (p) {
return p.excludeuntil !== infinity;
});
if (!playlists.length) {
return;
}
playlistloader = new dashplaylistloader(properties.playlists[0], vhs, requestoptions, masterplaylistloader);
} else if (sourcetype === 'vhs-json') {
playlistloader = new playlistloader( // if the vhs-json object included the media playlist, use the media playlist
// as provided, otherwise use the resolved uri to load the playlist
properties.playlists ? properties.playlists[0] : properties.resolveduri, vhs, requestoptions);
}
properties = videojs.mergeoptions({
id: variantlabel,
playlistloader: playlistloader
}, properties);
setuplisteners[type](type, properties.playlistloader, settings);
groups[groupid].push(properties);
if (typeof tracks[variantlabel] === 'undefined') {
var track = tech.addremotetexttrack({
id: variantlabel,
kind: 'subtitles',
"default": properties["default"] && properties.autoselect,
language: properties.language,
label: variantlabel
}, false).track;
tracks[variantlabel] = track;
}
}
} // setup single error event handler for the segment loader
segmentloader.on('error', onerror[type](type, settings));
},
/**
* setup texttracks for the closed-caption groups
*
* @param {string} type
* mediagroup type
* @param {object} settings
* object containing required information for media groups
* @function initialize['closed-captions']
*/
'closed-captions': function closedcaptions(type, settings) {
var tech = settings.tech,
mediagroups = settings.master.mediagroups,
_settings$mediatypes$3 = settings.mediatypes[type],
groups = _settings$mediatypes$3.groups,
tracks = _settings$mediatypes$3.tracks;
for (var groupid in mediagroups[type]) {
if (!groups[groupid]) {
groups[groupid] = [];
}
for (var variantlabel in mediagroups[type][groupid]) {
var properties = mediagroups[type][groupid][variantlabel]; // look for either 608 (ccn) or 708 (servicen) caption services
if (!/^(?:cc|service)/.test(properties.instreamid)) {
continue;
}
var captionservices = tech.options_.vhs && tech.options_.vhs.captionservices || {};
var newprops = {
label: variantlabel,
language: properties.language,
instreamid: properties.instreamid,
"default": properties["default"] && properties.autoselect
};
if (captionservices[newprops.instreamid]) {
newprops = videojs.mergeoptions(newprops, captionservices[newprops.instreamid]);
}
if (newprops["default"] === undefined) {
delete newprops["default"];
} // no playlistloader is required for closed-captions because the captions are
// embedded within the video stream
groups[groupid].push(videojs.mergeoptions({
id: variantlabel
}, properties));
if (typeof tracks[variantlabel] === 'undefined') {
var track = tech.addremotetexttrack({
id: newprops.instreamid,
kind: 'captions',
"default": newprops["default"],
language: newprops.language,
label: newprops.label
}, false).track;
tracks[variantlabel] = track;
}
}
}
}
};
var groupmatch = function groupmatch(list, media) {
for (var i = 0; i < list.length; i++) {
if (playlistmatch(media, list[i])) {
return true;
}
if (list[i].playlists && groupmatch(list[i].playlists, media)) {
return true;
}
}
return false;
};
/**
* returns a function used to get the active group of the provided type
*
* @param {string} type
* mediagroup type
* @param {object} settings
* object containing required information for media groups
* @return {function}
* function that returns the active media group for the provided type. takes an
* optional parameter {texttrack} track. if no track is provided, a list of all
* variants in the group, otherwise the variant corresponding to the provided
* track is returned.
* @function activegroup
*/
var activegroup = function activegroup(type, settings) {
return function (track) {
var masterplaylistloader = settings.masterplaylistloader,
groups = settings.mediatypes[type].groups;
var media = masterplaylistloader.media();
if (!media) {
return null;
}
var variants = null; // set to variants to main media active group
if (media.attributes[type]) {
variants = groups[media.attributes[type]];
}
var groupkeys = object.keys(groups);
if (!variants) {
// find the masterplaylistloader media
// that is in a media group if we are dealing
// with audio only
if (type === 'audio' && groupkeys.length > 1 && isaudioonly(settings.master)) {
for (var i = 0; i < groupkeys.length; i++) {
var grouppropertylist = groups[groupkeys[i]];
if (groupmatch(grouppropertylist, media)) {
variants = grouppropertylist;
break;
}
} // use the main group if it exists
} else if (groups.main) {
variants = groups.main; // only one group, use that one
} else if (groupkeys.length === 1) {
variants = groups[groupkeys[0]];
}
}
if (typeof track === 'undefined') {
return variants;
}
if (track === null || !variants) {
// an active track was specified so a corresponding group is expected. track === null
// means no track is currently active so there is no corresponding group
return null;
}
return variants.filter(function (props) {
return props.id === track.id;
})[0] || null;
};
};
var activetrack = {
/**
* returns a function used to get the active track of type provided
*
* @param {string} type
* mediagroup type
* @param {object} settings
* object containing required information for media groups
* @return {function}
* function that returns the active media track for the provided type. returns
* null if no track is active
* @function activetrack.audio
*/
audio: function audio(type, settings) {
return function () {
var tracks = settings.mediatypes[type].tracks;
for (var id in tracks) {
if (tracks[id].enabled) {
return tracks[id];
}
}
return null;
};
},
/**
* returns a function used to get the active track of type provided
*
* @param {string} type
* mediagroup type
* @param {object} settings
* object containing required information for media groups
* @return {function}
* function that returns the active media track for the provided type. returns
* null if no track is active
* @function activetrack.subtitles
*/
subtitles: function subtitles(type, settings) {
return function () {
var tracks = settings.mediatypes[type].tracks;
for (var id in tracks) {
if (tracks[id].mode === 'showing' || tracks[id].mode === 'hidden') {
return tracks[id];
}
}
return null;
};
}
};
var getactivegroup = function getactivegroup(type, _ref) {
var mediatypes = _ref.mediatypes;
return function () {
var activetrack_ = mediatypes[type].activetrack();
if (!activetrack_) {
return null;
}
return mediatypes[type].activegroup(activetrack_);
};
};
/**
* setup playlistloaders and tracks for media groups (audio, subtitles,
* closed-captions) specified in the master manifest.
*
* @param {object} settings
* object containing required information for setting up the media groups
* @param {tech} settings.tech
* the tech of the player
* @param {object} settings.requestoptions
* xhr request options used by the segment loaders
* @param {playlistloader} settings.masterplaylistloader
* playlistloader for the master source
* @param {vhshandler} settings.vhs
* vhs sourcehandler
* @param {object} settings.master
* the parsed master manifest
* @param {object} settings.mediatypes
* object to store the loaders, tracks, and utility methods for each media type
* @param {function} settings.blacklistcurrentplaylist
* blacklists the current rendition and forces a rendition switch.
* @function setupmediagroups
*/
var setupmediagroups = function setupmediagroups(settings) {
['audio', 'subtitles', 'closed-captions'].foreach(function (type) {
initialize[type](type, settings);
});
var mediatypes = settings.mediatypes,
masterplaylistloader = settings.masterplaylistloader,
tech = settings.tech,
vhs = settings.vhs,
_settings$segmentload3 = settings.segmentloaders,
audiosegmentloader = _settings$segmentload3['audio'],
mainsegmentloader = _settings$segmentload3.main; // setup active group and track getters and change event handlers
['audio', 'subtitles'].foreach(function (type) {
mediatypes[type].activegroup = activegroup(type, settings);
mediatypes[type].activetrack = activetrack[type](type, settings);
mediatypes[type].ongroupchanged = ongroupchanged(type, settings);
mediatypes[type].ongroupchanging = ongroupchanging(type, settings);
mediatypes[type].ontrackchanged = ontrackchanged(type, settings);
mediatypes[type].getactivegroup = getactivegroup(type, settings);
}); // do not enable the default subtitle or caption track.
// do enable the default audio track
var audiogroup = mediatypes.audio.activegroup();
if (audiogroup) {
var groupid = (audiogroup.filter(function (group) {
return group["default"];
})[0] || audiogroup[0]).id;
mediatypes.audio.tracks[groupid].enabled = true;
mediatypes.audio.ongroupchanged();
mediatypes.audio.ontrackchanged();
var activeaudiogroup = mediatypes.audio.getactivegroup(); // a similar check for handling setaudio on each loader is run again each time the
// track is changed, but needs to be handled here since the track may not be considered
// changed on the first call to ontrackchanged
if (!activeaudiogroup.playlistloader) {
// either audio is muxed with video or the stream is audio only
mainsegmentloader.setaudio(true);
} else {
// audio is demuxed
mainsegmentloader.setaudio(false);
audiosegmentloader.setaudio(true);
}
}
masterplaylistloader.on('mediachange', function () {
['audio', 'subtitles'].foreach(function (type) {
return mediatypes[type].ongroupchanged();
});
});
masterplaylistloader.on('mediachanging', function () {
['audio', 'subtitles'].foreach(function (type) {
return mediatypes[type].ongroupchanging();
});
}); // custom audio track change event handler for usage event
var onaudiotrackchanged = function onaudiotrackchanged() {
mediatypes.audio.ontrackchanged();
tech.trigger({
type: 'usage',
name: 'vhs-audio-change'
});
tech.trigger({
type: 'usage',
name: 'hls-audio-change'
});
};
tech.audiotracks().addeventlistener('change', onaudiotrackchanged);
tech.remotetexttracks().addeventlistener('change', mediatypes.subtitles.ontrackchanged);
vhs.on('dispose', function () {
tech.audiotracks().removeeventlistener('change', onaudiotrackchanged);
tech.remotetexttracks().removeeventlistener('change', mediatypes.subtitles.ontrackchanged);
}); // clear existing audio tracks and add the ones we just created
tech.cleartracks('audio');
for (var id in mediatypes.audio.tracks) {
tech.audiotracks().addtrack(mediatypes.audio.tracks[id]);
}
};
/**
* creates skeleton object used to store the loaders, tracks, and utility methods for each
* media type
*
* @return {object}
* object to store the loaders, tracks, and utility methods for each media type
* @function createmediatypes
*/
var createmediatypes = function createmediatypes() {
var mediatypes = {};
['audio', 'subtitles', 'closed-captions'].foreach(function (type) {
mediatypes[type] = {
groups: {},
tracks: {},
activeplaylistloader: null,
activegroup: noop,
activetrack: noop,
getactivegroup: noop,
ongroupchanged: noop,
ontrackchanged: noop,
lasttrack_: null,
logger_: logger("mediagroups[" + type + "]")
};
});
return mediatypes;
};
var abort_early_blacklist_seconds = 60 * 2;
var vhs$1; // segmentloader stats that need to have each loader's
// values summed to calculate the final value
var loaderstats = ['mediarequests', 'mediarequestsaborted', 'mediarequeststimedout', 'mediarequestserrored', 'mediatransferduration', 'mediabytestransferred', 'mediaappends'];
var sumloaderstat = function sumloaderstat(stat) {
return this.audiosegmentloader_[stat] + this.mainsegmentloader_[stat];
};
var shouldswitchtomedia = function shouldswitchtomedia(_ref) {
var currentplaylist = _ref.currentplaylist,
buffered = _ref.buffered,
currenttime = _ref.currenttime,
nextplaylist = _ref.nextplaylist,
bufferlowwaterline = _ref.bufferlowwaterline,
bufferhighwaterline = _ref.bufferhighwaterline,
duration = _ref.duration,
experimentalbufferbasedabr = _ref.experimentalbufferbasedabr,
log = _ref.log; // we have no other playlist to switch to
if (!nextplaylist) {
videojs.log.warn('we received no playlist to switch to. please check your stream.');
return false;
}
var sharedlogline = "allowing switch " + (currentplaylist && currentplaylist.id || 'null') + " -> " + nextplaylist.id;
if (!currentplaylist) {
log(sharedlogline + " as current playlist is not set");
return true;
} // no need to switch if playlist is the same
if (nextplaylist.id === currentplaylist.id) {
return false;
} // determine if current time is in a buffered range.
var isbuffered = boolean(findrange(buffered, currenttime).length); // if the playlist is live, then we want to not take low water line into account.
// this is because in live, the player plays 3 segments from the end of the
// playlist, and if `buffer_low_water_line` is greater than the duration availble
// in those segments, a viewer will never experience a rendition upswitch.
if (!currentplaylist.endlist) {
// for llhls live streams, don't switch renditions before playback has started, as it almost
// doubles the time to first playback.
if (!isbuffered && typeof currentplaylist.parttargetduration === 'number') {
log("not " + sharedlogline + " as current playlist is live llhls, but currenttime isn't in buffered.");
return false;
}
log(sharedlogline + " as current playlist is live");
return true;
}
var forwardbuffer = timeaheadof(buffered, currenttime);
var maxbufferlowwaterline = experimentalbufferbasedabr ? config.experimental_max_buffer_low_water_line : config.max_buffer_low_water_line; // for the same reason as live, we ignore the low water line when the vod
// duration is below the max potential low water line
if (duration < maxbufferlowwaterline) {
log(sharedlogline + " as duration < max low water line (" + duration + " < " + maxbufferlowwaterline + ")");
return true;
}
var nextbandwidth = nextplaylist.attributes.bandwidth;
var currbandwidth = currentplaylist.attributes.bandwidth; // when switching down, if our buffer is lower than the high water line,
// we can switch down
if (nextbandwidth < currbandwidth && (!experimentalbufferbasedabr || forwardbuffer < bufferhighwaterline)) {
var logline = sharedlogline + " as next bandwidth < current bandwidth (" + nextbandwidth + " < " + currbandwidth + ")";
if (experimentalbufferbasedabr) {
logline += " and forwardbuffer < bufferhighwaterline (" + forwardbuffer + " < " + bufferhighwaterline + ")";
}
log(logline);
return true;
} // and if our buffer is higher than the low water line,
// we can switch up
if ((!experimentalbufferbasedabr || nextbandwidth > currbandwidth) && forwardbuffer >= bufferlowwaterline) {
var _logline = sharedlogline + " as forwardbuffer >= bufferlowwaterline (" + forwardbuffer + " >= " + bufferlowwaterline + ")";
if (experimentalbufferbasedabr) {
_logline += " and next bandwidth > current bandwidth (" + nextbandwidth + " > " + currbandwidth + ")";
}
log(_logline);
return true;
}
log("not " + sharedlogline + " as no switching criteria met");
return false;
};
/**
* the master playlist controller controller all interactons
* between playlists and segmentloaders. at this time this mainly
* involves a master playlist and a series of audio playlists
* if they are available
*
* @class masterplaylistcontroller
* @extends videojs.eventtarget
*/
var masterplaylistcontroller = /*#__pure__*/function (_videojs$eventtarget) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(masterplaylistcontroller, _videojs$eventtarget);
function masterplaylistcontroller(options) {
var _this;
_this = _videojs$eventtarget.call(this) || this;
var src = options.src,
handlemanifestredirects = options.handlemanifestredirects,
withcredentials = options.withcredentials,
tech = options.tech,
bandwidth = options.bandwidth,
externvhs = options.externvhs,
usecuetags = options.usecuetags,
blacklistduration = options.blacklistduration,
enablelowinitialplaylist = options.enablelowinitialplaylist,
sourcetype = options.sourcetype,
cacheencryptionkeys = options.cacheencryptionkeys,
experimentalbufferbasedabr = options.experimentalbufferbasedabr,
experimentalleastpixeldiffselector = options.experimentalleastpixeldiffselector,
captionservices = options.captionservices;
if (!src) {
throw new error('a non-empty playlist url or json manifest string is required');
}
var maxplaylistretries = options.maxplaylistretries;
if (maxplaylistretries === null || typeof maxplaylistretries === 'undefined') {
maxplaylistretries = infinity;
}
vhs$1 = externvhs;
_this.experimentalbufferbasedabr = boolean(experimentalbufferbasedabr);
_this.experimentalleastpixeldiffselector = boolean(experimentalleastpixeldiffselector);
_this.withcredentials = withcredentials;
_this.tech_ = tech;
_this.vhs_ = tech.vhs;
_this.sourcetype_ = sourcetype;
_this.usecuetags_ = usecuetags;
_this.blacklistduration = blacklistduration;
_this.maxplaylistretries = maxplaylistretries;
_this.enablelowinitialplaylist = enablelowinitialplaylist;
if (_this.usecuetags_) {
_this.cuetagstrack_ = _this.tech_.addtexttrack('metadata', 'ad-cues');
_this.cuetagstrack_.inbandmetadatatrackdispatchtype = '';
}
_this.requestoptions_ = {
withcredentials: withcredentials,
handlemanifestredirects: handlemanifestredirects,
maxplaylistretries: maxplaylistretries,
timeout: null
};
_this.on('error', _this.pauseloading);
_this.mediatypes_ = createmediatypes();
_this.mediasource = new global_window__webpack_imported_module_0___default.a.mediasource();
_this.handledurationchange_ = _this.handledurationchange_.bind(_babel_runtime_helpers_assertthisinitialized__webpack_imported_module_4___default()(_this));
_this.handlesourceopen_ = _this.handlesourceopen_.bind(_babel_runtime_helpers_assertthisinitialized__webpack_imported_module_4___default()(_this));
_this.handlesourceended_ = _this.handlesourceended_.bind(_babel_runtime_helpers_assertthisinitialized__webpack_imported_module_4___default()(_this));
_this.mediasource.addeventlistener('durationchange', _this.handledurationchange_); // load the media source into the player
_this.mediasource.addeventlistener('sourceopen', _this.handlesourceopen_);
_this.mediasource.addeventlistener('sourceended', _this.handlesourceended_); // we don't have to handle sourceclose since dispose will handle termination of
// everything, and the mediasource should not be detached without a proper disposal
_this.seekable_ = videojs.createtimeranges();
_this.hasplayed_ = false;
_this.synccontroller_ = new synccontroller(options);
_this.segmentmetadatatrack_ = tech.addremotetexttrack({
kind: 'metadata',
label: 'segment-metadata'
}, false).track;
_this.decrypter_ = new decrypter();
_this.sourceupdater_ = new sourceupdater(_this.mediasource);
_this.inbandtexttracks_ = {};
_this.timelinechangecontroller_ = new timelinechangecontroller();
var segmentloadersettings = {
vhs: _this.vhs_,
parse708captions: options.parse708captions,
usedtsfortimestampoffset: options.usedtsfortimestampoffset,
captionservices: captionservices,
mediasource: _this.mediasource,
currenttime: _this.tech_.currenttime.bind(_this.tech_),
seekable: function seekable() {
return _this.seekable();
},
seeking: function seeking() {
return _this.tech_.seeking();
},
duration: function duration() {
return _this.duration();
},
hasplayed: function hasplayed() {
return _this.hasplayed_;
},
goalbufferlength: function goalbufferlength() {
return _this.goalbufferlength();
},
bandwidth: bandwidth,
synccontroller: _this.synccontroller_,
decrypter: _this.decrypter_,
sourcetype: _this.sourcetype_,
inbandtexttracks: _this.inbandtexttracks_,
cacheencryptionkeys: cacheencryptionkeys,
sourceupdater: _this.sourceupdater_,
timelinechangecontroller: _this.timelinechangecontroller_,
experimentalexactmanifesttimings: options.experimentalexactmanifesttimings
}; // the source type check not only determines whether a special dash playlist loader
// should be used, but also covers the case where the provided src is a vhs-json
// manifest object (instead of a url). in the case of vhs-json, the default
// playlistloader should be used.
_this.masterplaylistloader_ = _this.sourcetype_ === 'dash' ? new dashplaylistloader(src, _this.vhs_, _this.requestoptions_) : new playlistloader(src, _this.vhs_, _this.requestoptions_);
_this.setupmasterplaylistloaderlisteners_(); // setup segment loaders
// combined audio/video or just video when alternate audio track is selected
_this.mainsegmentloader_ = new segmentloader(videojs.mergeoptions(segmentloadersettings, {
segmentmetadatatrack: _this.segmentmetadatatrack_,
loadertype: 'main'
}), options); // alternate audio track
_this.audiosegmentloader_ = new segmentloader(videojs.mergeoptions(segmentloadersettings, {
loadertype: 'audio'
}), options);
_this.subtitlesegmentloader_ = new vttsegmentloader(videojs.mergeoptions(segmentloadersettings, {
loadertype: 'vtt',
featuresnativetexttracks: _this.tech_.featuresnativetexttracks,
loadvttjs: function loadvttjs() {
return new promise(function (resolve, reject) {
function onload() {
tech.off('vttjserror', onerror);
resolve();
}
function onerror() {
tech.off('vttjsloaded', onload);
reject();
}
tech.one('vttjsloaded', onload);
tech.one('vttjserror', onerror); // safe to call multiple times, script will be loaded only once:
tech.addwebvttscript_();
});
}
}), options);
_this.setupsegmentloaderlisteners_();
if (_this.experimentalbufferbasedabr) {
_this.masterplaylistloader_.one('loadedplaylist', function () {
return _this.startabrtimer_();
});
_this.tech_.on('pause', function () {
return _this.stopabrtimer_();
});
_this.tech_.on('play', function () {
return _this.startabrtimer_();
});
} // create segmentloader stat-getters
// mediarequests_
// mediarequestsaborted_
// mediarequeststimedout_
// mediarequestserrored_
// mediatransferduration_
// mediabytestransferred_
// mediaappends_
loaderstats.foreach(function (stat) {
_this[stat + '_'] = sumloaderstat.bind(_babel_runtime_helpers_assertthisinitialized__webpack_imported_module_4___default()(_this), stat);
});
_this.logger_ = logger('mpc');
_this.triggeredfmp4usage = false;
if (_this.tech_.preload() === 'none') {
_this.loadonplay_ = function () {
_this.loadonplay_ = null;
_this.masterplaylistloader_.load();
};
_this.tech_.one('play', _this.loadonplay_);
} else {
_this.masterplaylistloader_.load();
}
_this.timetoloadeddata__ = -1;
_this.mainappendstoloadeddata__ = -1;
_this.audioappendstoloadeddata__ = -1;
var event = _this.tech_.preload() === 'none' ? 'play' : 'loadstart'; // start the first frame timer on loadstart or play (for preload none)
_this.tech_.one(event, function () {
var timetoloadeddatastart = date.now();
_this.tech_.one('loadeddata', function () {
_this.timetoloadeddata__ = date.now() - timetoloadeddatastart;
_this.mainappendstoloadeddata__ = _this.mainsegmentloader_.mediaappends;
_this.audioappendstoloadeddata__ = _this.audiosegmentloader_.mediaappends;
});
});
return _this;
}
var _proto = masterplaylistcontroller.prototype;
_proto.mainappendstoloadeddata_ = function mainappendstoloadeddata_() {
return this.mainappendstoloadeddata__;
};
_proto.audioappendstoloadeddata_ = function audioappendstoloadeddata_() {
return this.audioappendstoloadeddata__;
};
_proto.appendstoloadeddata_ = function appendstoloadeddata_() {
var main = this.mainappendstoloadeddata_();
var audio = this.audioappendstoloadeddata_();
if (main === -1 || audio === -1) {
return -1;
}
return main + audio;
};
_proto.timetoloadeddata_ = function timetoloadeddata_() {
return this.timetoloadeddata__;
}
/**
* run selectplaylist and switch to the new playlist if we should
*
* @param {string} [reason=abr] a reason for why the abr check is made
* @private
*/
;
_proto.checkabr_ = function checkabr_(reason) {
if (reason === void 0) {
reason = 'abr';
}
var nextplaylist = this.selectplaylist();
if (nextplaylist && this.shouldswitchtomedia_(nextplaylist)) {
this.switchmedia_(nextplaylist, reason);
}
};
_proto.switchmedia_ = function switchmedia_(playlist, cause, delay) {
var oldmedia = this.media();
var oldid = oldmedia && (oldmedia.id || oldmedia.uri);
var newid = playlist.id || playlist.uri;
if (oldid && oldid !== newid) {
this.logger_("switch media " + oldid + " -> " + newid + " from " + cause);
this.tech_.trigger({
type: 'usage',
name: "vhs-rendition-change-" + cause
});
}
this.masterplaylistloader_.media(playlist, delay);
}
/**
* start a timer that periodically calls checkabr_
*
* @private
*/
;
_proto.startabrtimer_ = function startabrtimer_() {
var _this2 = this;
this.stopabrtimer_();
this.abrtimer_ = global_window__webpack_imported_module_0___default.a.setinterval(function () {
return _this2.checkabr_();
}, 250);
}
/**
* stop the timer that periodically calls checkabr_
*
* @private
*/
;
_proto.stopabrtimer_ = function stopabrtimer_() {
// if we're scrubbing, we don't need to pause.
// this getter will be added to video.js in version 7.11.
if (this.tech_.scrubbing && this.tech_.scrubbing()) {
return;
}
global_window__webpack_imported_module_0___default.a.clearinterval(this.abrtimer_);
this.abrtimer_ = null;
}
/**
* get a list of playlists for the currently selected audio playlist
*
* @return {array} the array of audio playlists
*/
;
_proto.getaudiotrackplaylists_ = function getaudiotrackplaylists_() {
var master = this.master();
var defaultplaylists = master && master.playlists || []; // if we don't have any audio groups then we can only
// assume that the audio tracks are contained in masters
// playlist array, use that or an empty array.
if (!master || !master.mediagroups || !master.mediagroups.audio) {
return defaultplaylists;
}
var audio = master.mediagroups.audio;
var groupkeys = object.keys(audio);
var track; // get the current active track
if (object.keys(this.mediatypes_.audio.groups).length) {
track = this.mediatypes_.audio.activetrack(); // or get the default track from master if mediatypes_ isn't setup yet
} else {
// default group is `main` or just the first group.
var defaultgroup = audio.main || groupkeys.length && audio[groupkeys[0]];
for (var label in defaultgroup) {
if (defaultgroup[label]["default"]) {
track = {
label: label
};
break;
}
}
} // no active track no playlists.
if (!track) {
return defaultplaylists;
}
var playlists = []; // get all of the playlists that are possible for the
// active track.
for (var group in audio) {
if (audio[group][track.label]) {
var properties = audio[group][track.label];
if (properties.playlists && properties.playlists.length) {
playlists.push.apply(playlists, properties.playlists);
} else if (properties.uri) {
playlists.push(properties);
} else if (master.playlists.length) {
// if an audio group does not have a uri
// see if we have main playlists that use it as a group.
// if we do then add those to the playlists list.
for (var i = 0; i < master.playlists.length; i++) {
var playlist = master.playlists[i];
if (playlist.attributes && playlist.attributes.audio && playlist.attributes.audio === group) {
playlists.push(playlist);
}
}
}
}
}
if (!playlists.length) {
return defaultplaylists;
}
return playlists;
}
/**
* register event handlers on the master playlist loader. a helper
* function for construction time.
*
* @private
*/
;
_proto.setupmasterplaylistloaderlisteners_ = function setupmasterplaylistloaderlisteners_() {
var _this3 = this;
this.masterplaylistloader_.on('loadedmetadata', function () {
var media = _this3.masterplaylistloader_.media();
var requesttimeout = media.targetduration * 1.5 * 1000; // if we don't have any more available playlists, we don't want to
// timeout the request.
if (islowestenabledrendition(_this3.masterplaylistloader_.master, _this3.masterplaylistloader_.media())) {
_this3.requestoptions_.timeout = 0;
} else {
_this3.requestoptions_.timeout = requesttimeout;
} // if this isn't a live video and preload permits, start
// downloading segments
if (media.endlist && _this3.tech_.preload() !== 'none') {
_this3.mainsegmentloader_.playlist(media, _this3.requestoptions_);
_this3.mainsegmentloader_.load();
}
setupmediagroups({
sourcetype: _this3.sourcetype_,
segmentloaders: {
audio: _this3.audiosegmentloader_,
subtitles: _this3.subtitlesegmentloader_,
main: _this3.mainsegmentloader_
},
tech: _this3.tech_,
requestoptions: _this3.requestoptions_,
masterplaylistloader: _this3.masterplaylistloader_,
vhs: _this3.vhs_,
master: _this3.master(),
mediatypes: _this3.mediatypes_,
blacklistcurrentplaylist: _this3.blacklistcurrentplaylist.bind(_this3)
});
_this3.triggerpresenceusage_(_this3.master(), media);
_this3.setupfirstplay();
if (!_this3.mediatypes_.audio.activeplaylistloader || _this3.mediatypes_.audio.activeplaylistloader.media()) {
_this3.trigger('selectedinitialmedia');
} else {
// we must wait for the active audio playlist loader to
// finish setting up before triggering this event so the
// representations api and eme setup is correct
_this3.mediatypes_.audio.activeplaylistloader.one('loadedmetadata', function () {
_this3.trigger('selectedinitialmedia');
});
}
});
this.masterplaylistloader_.on('loadedplaylist', function () {
if (_this3.loadonplay_) {
_this3.tech_.off('play', _this3.loadonplay_);
}
var updatedplaylist = _this3.masterplaylistloader_.media();
if (!updatedplaylist) {
// exclude any variants that are not supported by the browser before selecting
// an initial media as the playlist selectors do not consider browser support
_this3.excludeunsupportedvariants_();
var selectedmedia;
if (_this3.enablelowinitialplaylist) {
selectedmedia = _this3.selectinitialplaylist();
}
if (!selectedmedia) {
selectedmedia = _this3.selectplaylist();
}
if (!selectedmedia || !_this3.shouldswitchtomedia_(selectedmedia)) {
return;
}
_this3.initialmedia_ = selectedmedia;
_this3.switchmedia_(_this3.initialmedia_, 'initial'); // under the standard case where a source url is provided, loadedplaylist will
// fire again since the playlist will be requested. in the case of vhs-json
// (where the manifest object is provided as the source), when the media
// playlist's `segments` list is already available, a media playlist won't be
// requested, and loadedplaylist won't fire again, so the playlist handler must be
// called on its own here.
var havejsonsource = _this3.sourcetype_ === 'vhs-json' && _this3.initialmedia_.segments;
if (!havejsonsource) {
return;
}
updatedplaylist = _this3.initialmedia_;
}
_this3.handleupdatedmediaplaylist(updatedplaylist);
});
this.masterplaylistloader_.on('error', function () {
_this3.blacklistcurrentplaylist(_this3.masterplaylistloader_.error);
});
this.masterplaylistloader_.on('mediachanging', function () {
_this3.mainsegmentloader_.abort();
_this3.mainsegmentloader_.pause();
});
this.masterplaylistloader_.on('mediachange', function () {
var media = _this3.masterplaylistloader_.media();
var requesttimeout = media.targetduration * 1.5 * 1000; // if we don't have any more available playlists, we don't want to
// timeout the request.
if (islowestenabledrendition(_this3.masterplaylistloader_.master, _this3.masterplaylistloader_.media())) {
_this3.requestoptions_.timeout = 0;
} else {
_this3.requestoptions_.timeout = requesttimeout;
}
_this3.masterplaylistloader_.load(); // todo: create a new event on the playlistloader that signals
// that the segments have changed in some way and use that to
// update the segmentloader instead of doing it twice here and
// on `loadedplaylist`
_this3.mainsegmentloader_.playlist(media, _this3.requestoptions_);
_this3.mainsegmentloader_.load();
_this3.tech_.trigger({
type: 'mediachange',
bubbles: true
});
});
this.masterplaylistloader_.on('playlistunchanged', function () {
var updatedplaylist = _this3.masterplaylistloader_.media(); // ignore unchanged playlists that have already been
// excluded for not-changing. we likely just have a really slowly updating
// playlist.
if (updatedplaylist.lastexcludereason_ === 'playlist-unchanged') {
return;
}
var playlistoutdated = _this3.stuckatplaylistend_(updatedplaylist);
if (playlistoutdated) {
// playlist has stopped updating and we're stuck at its end. try to
// blacklist it and switch to another playlist in the hope that that
// one is updating (and give the player a chance to re-adjust to the
// safe live point).
_this3.blacklistcurrentplaylist({
message: 'playlist no longer updating.',
reason: 'playlist-unchanged'
}); // useful for monitoring qos
_this3.tech_.trigger('playliststuck');
}
});
this.masterplaylistloader_.on('renditiondisabled', function () {
_this3.tech_.trigger({
type: 'usage',
name: 'vhs-rendition-disabled'
});
_this3.tech_.trigger({
type: 'usage',
name: 'hls-rendition-disabled'
});
});
this.masterplaylistloader_.on('renditionenabled', function () {
_this3.tech_.trigger({
type: 'usage',
name: 'vhs-rendition-enabled'
});
_this3.tech_.trigger({
type: 'usage',
name: 'hls-rendition-enabled'
});
});
}
/**
* given an updated media playlist (whether it was loaded for the first time, or
* refreshed for live playlists), update any relevant properties and state to reflect
* changes in the media that should be accounted for (e.g., cues and duration).
*
* @param {object} updatedplaylist the updated media playlist object
*
* @private
*/
;
_proto.handleupdatedmediaplaylist = function handleupdatedmediaplaylist(updatedplaylist) {
if (this.usecuetags_) {
this.updateadcues_(updatedplaylist);
} // todo: create a new event on the playlistloader that signals
// that the segments have changed in some way and use that to
// update the segmentloader instead of doing it twice here and
// on `mediachange`
this.mainsegmentloader_.playlist(updatedplaylist, this.requestoptions_);
this.updateduration(!updatedplaylist.endlist); // if the player isn't paused, ensure that the segment loader is running,
// as it is possible that it was temporarily stopped while waiting for
// a playlist (e.g., in case the playlist errored and we re-requested it).
if (!this.tech_.paused()) {
this.mainsegmentloader_.load();
if (this.audiosegmentloader_) {
this.audiosegmentloader_.load();
}
}
}
/**
* a helper function for triggerring presence usage events once per source
*
* @private
*/
;
_proto.triggerpresenceusage_ = function triggerpresenceusage_(master, media) {
var mediagroups = master.mediagroups || {};
var defaultdemuxed = true;
var audiogroupkeys = object.keys(mediagroups.audio);
for (var mediagroup in mediagroups.audio) {
for (var label in mediagroups.audio[mediagroup]) {
var properties = mediagroups.audio[mediagroup][label];
if (!properties.uri) {
defaultdemuxed = false;
}
}
}
if (defaultdemuxed) {
this.tech_.trigger({
type: 'usage',
name: 'vhs-demuxed'
});
this.tech_.trigger({
type: 'usage',
name: 'hls-demuxed'
});
}
if (object.keys(mediagroups.subtitles).length) {
this.tech_.trigger({
type: 'usage',
name: 'vhs-webvtt'
});
this.tech_.trigger({
type: 'usage',
name: 'hls-webvtt'
});
}
if (vhs$1.playlist.isaes(media)) {
this.tech_.trigger({
type: 'usage',
name: 'vhs-aes'
});
this.tech_.trigger({
type: 'usage',
name: 'hls-aes'
});
}
if (audiogroupkeys.length && object.keys(mediagroups.audio[audiogroupkeys[0]]).length > 1) {
this.tech_.trigger({
type: 'usage',
name: 'vhs-alternate-audio'
});
this.tech_.trigger({
type: 'usage',
name: 'hls-alternate-audio'
});
}
if (this.usecuetags_) {
this.tech_.trigger({
type: 'usage',
name: 'vhs-playlist-cue-tags'
});
this.tech_.trigger({
type: 'usage',
name: 'hls-playlist-cue-tags'
});
}
};
_proto.shouldswitchtomedia_ = function shouldswitchtomedia_(nextplaylist) {
var currentplaylist = this.masterplaylistloader_.media() || this.masterplaylistloader_.pendingmedia_;
var currenttime = this.tech_.currenttime();
var bufferlowwaterline = this.bufferlowwaterline();
var bufferhighwaterline = this.bufferhighwaterline();
var buffered = this.tech_.buffered();
return shouldswitchtomedia({
buffered: buffered,
currenttime: currenttime,
currentplaylist: currentplaylist,
nextplaylist: nextplaylist,
bufferlowwaterline: bufferlowwaterline,
bufferhighwaterline: bufferhighwaterline,
duration: this.duration(),
experimentalbufferbasedabr: this.experimentalbufferbasedabr,
log: this.logger_
});
}
/**
* register event handlers on the segment loaders. a helper function
* for construction time.
*
* @private
*/
;
_proto.setupsegmentloaderlisteners_ = function setupsegmentloaderlisteners_() {
var _this4 = this;
this.mainsegmentloader_.on('bandwidthupdate', function () {
// whether or not buffer based abr or another abr is used, on a bandwidth change it's
// useful to check to see if a rendition switch should be made.
_this4.checkabr_('bandwidthupdate');
_this4.tech_.trigger('bandwidthupdate');
});
this.mainsegmentloader_.on('timeout', function () {
if (_this4.experimentalbufferbasedabr) {
// if a rendition change is needed, then it would've be done on `bandwidthupdate`.
// here the only consideration is that for buffer based abr there's no guarantee
// of an immediate switch (since the bandwidth is averaged with a timeout
// bandwidth value of 1), so force a load on the segment loader to keep it going.
_this4.mainsegmentloader_.load();
}
}); // `progress` events are not reliable enough of a bandwidth measure to trigger buffer
// based abr.
if (!this.experimentalbufferbasedabr) {
this.mainsegmentloader_.on('progress', function () {
_this4.trigger('progress');
});
}
this.mainsegmentloader_.on('error', function () {
_this4.blacklistcurrentplaylist(_this4.mainsegmentloader_.error());
});
this.mainsegmentloader_.on('appenderror', function () {
_this4.error = _this4.mainsegmentloader_.error_;
_this4.trigger('error');
});
this.mainsegmentloader_.on('syncinfoupdate', function () {
_this4.onsyncinfoupdate_();
});
this.mainsegmentloader_.on('timestampoffset', function () {
_this4.tech_.trigger({
type: 'usage',
name: 'vhs-timestamp-offset'
});
_this4.tech_.trigger({
type: 'usage',
name: 'hls-timestamp-offset'
});
});
this.audiosegmentloader_.on('syncinfoupdate', function () {
_this4.onsyncinfoupdate_();
});
this.audiosegmentloader_.on('appenderror', function () {
_this4.error = _this4.audiosegmentloader_.error_;
_this4.trigger('error');
});
this.mainsegmentloader_.on('ended', function () {
_this4.logger_('main segment loader ended');
_this4.onendofstream();
});
this.mainsegmentloader_.on('earlyabort', function (event) {
// never try to early abort with the new abr algorithm
if (_this4.experimentalbufferbasedabr) {
return;
}
_this4.delegateloaders_('all', ['abort']);
_this4.blacklistcurrentplaylist({
message: 'aborted early because there isn\'t enough bandwidth to complete the ' + 'request without rebuffering.'
}, abort_early_blacklist_seconds);
});
var updatecodecs = function updatecodecs() {
if (!_this4.sourceupdater_.hascreatedsourcebuffers()) {
return _this4.trytocreatesourcebuffers_();
}
var codecs = _this4.getcodecsorexclude_(); // no codecs means that the playlist was excluded
if (!codecs) {
return;
}
_this4.sourceupdater_.addorchangesourcebuffers(codecs);
};
this.mainsegmentloader_.on('trackinfo', updatecodecs);
this.audiosegmentloader_.on('trackinfo', updatecodecs);
this.mainsegmentloader_.on('fmp4', function () {
if (!_this4.triggeredfmp4usage) {
_this4.tech_.trigger({
type: 'usage',
name: 'vhs-fmp4'
});
_this4.tech_.trigger({
type: 'usage',
name: 'hls-fmp4'
});
_this4.triggeredfmp4usage = true;
}
});
this.audiosegmentloader_.on('fmp4', function () {
if (!_this4.triggeredfmp4usage) {
_this4.tech_.trigger({
type: 'usage',
name: 'vhs-fmp4'
});
_this4.tech_.trigger({
type: 'usage',
name: 'hls-fmp4'
});
_this4.triggeredfmp4usage = true;
}
});
this.audiosegmentloader_.on('ended', function () {
_this4.logger_('audiosegmentloader ended');
_this4.onendofstream();
});
};
_proto.mediasecondsloaded_ = function mediasecondsloaded_() {
return math.max(this.audiosegmentloader_.mediasecondsloaded + this.mainsegmentloader_.mediasecondsloaded);
}
/**
* call load on our segmentloaders
*/
;
_proto.load = function load() {
this.mainsegmentloader_.load();
if (this.mediatypes_.audio.activeplaylistloader) {
this.audiosegmentloader_.load();
}
if (this.mediatypes_.subtitles.activeplaylistloader) {
this.subtitlesegmentloader_.load();
}
}
/**
* re-tune playback quality level for the current player
* conditions without performing destructive actions, like
* removing already buffered content
*
* @private
* @deprecated
*/
;
_proto.smoothqualitychange_ = function smoothqualitychange_(media) {
if (media === void 0) {
media = this.selectplaylist();
}
this.fastqualitychange_(media);
}
/**
* re-tune playback quality level for the current player
* conditions. this method will perform destructive actions like removing
* already buffered content in order to readjust the currently active
* playlist quickly. this is good for manual quality changes
*
* @private
*/
;
_proto.fastqualitychange_ = function fastqualitychange_(media) {
var _this5 = this;
if (media === void 0) {
media = this.selectplaylist();
}
if (media === this.masterplaylistloader_.media()) {
this.logger_('skipping fastqualitychange because new media is same as old');
return;
}
this.switchmedia_(media, 'fast-quality'); // delete all buffered data to allow an immediate quality switch, then seek to give
// the browser a kick to remove any cached frames from the previous rendtion (.04 seconds
// ahead is roughly the minimum that will accomplish this across a variety of content
// in ie and edge, but seeking in place is sufficient on all other browsers)
// edge/ie bug: https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/14600375/
// chrome bug: https://bugs.chromium.org/p/chromium/issues/detail?id=651904
this.mainsegmentloader_.reseteverything(function () {
// since this is not a typical seek, we avoid the seekto method which can cause segments
// from the previously enabled rendition to load before the new playlist has finished loading
if (videojs.browser.ie_version || videojs.browser.is_edge) {
_this5.tech_.setcurrenttime(_this5.tech_.currenttime() + 0.04);
} else {
_this5.tech_.setcurrenttime(_this5.tech_.currenttime());
}
}); // don't need to reset audio as it is reset when media changes
}
/**
* begin playback.
*/
;
_proto.play = function play() {
if (this.setupfirstplay()) {
return;
}
if (this.tech_.ended()) {
this.tech_.setcurrenttime(0);
}
if (this.hasplayed_) {
this.load();
}
var seekable = this.tech_.seekable(); // if the viewer has paused and we fell out of the live window,
// seek forward to the live point
if (this.tech_.duration() === infinity) {
if (this.tech_.currenttime() < seekable.start(0)) {
return this.tech_.setcurrenttime(seekable.end(seekable.length - 1));
}
}
}
/**
* seek to the latest media position if this is a live video and the
* player and video are loaded and initialized.
*/
;
_proto.setupfirstplay = function setupfirstplay() {
var _this6 = this;
var media = this.masterplaylistloader_.media(); // check that everything is ready to begin buffering for the first call to play
// if 1) there is no active media
// 2) the player is paused
// 3) the first play has already been setup
// then exit early
if (!media || this.tech_.paused() || this.hasplayed_) {
return false;
} // when the video is a live stream
if (!media.endlist) {
var seekable = this.seekable();
if (!seekable.length) {
// without a seekable range, the player cannot seek to begin buffering at the live
// point
return false;
}
if (videojs.browser.ie_version && this.tech_.readystate() === 0) {
// ie11 throws an invalidstateerror if you try to set currenttime while the
// readystate is 0, so it must be delayed until the tech fires loadedmetadata.
this.tech_.one('loadedmetadata', function () {
_this6.trigger('firstplay');
_this6.tech_.setcurrenttime(seekable.end(0));
_this6.hasplayed_ = true;
});
return false;
} // trigger firstplay to inform the source handler to ignore the next seek event
this.trigger('firstplay'); // seek to the live point
this.tech_.setcurrenttime(seekable.end(0));
}
this.hasplayed_ = true; // we can begin loading now that everything is ready
this.load();
return true;
}
/**
* handle the sourceopen event on the mediasource
*
* @private
*/
;
_proto.handlesourceopen_ = function handlesourceopen_() {
// only attempt to create the source buffer if none already exist.
// handlesourceopen is also called when we are "re-opening" a source buffer
// after `endofstream` has been called (in response to a seek for instance)
this.trytocreatesourcebuffers_(); // if autoplay is enabled, begin playback. this is duplicative of
// code in video.js but is required because play() must be invoked
// *after* the media source has opened.
if (this.tech_.autoplay()) {
var playpromise = this.tech_.play(); // catch/silence error when a pause interrupts a play request
// on browsers which return a promise
if (typeof playpromise !== 'undefined' && typeof playpromise.then === 'function') {
playpromise.then(null, function (e) {});
}
}
this.trigger('sourceopen');
}
/**
* handle the sourceended event on the mediasource
*
* @private
*/
;
_proto.handlesourceended_ = function handlesourceended_() {
if (!this.inbandtexttracks_.metadatatrack_) {
return;
}
var cues = this.inbandtexttracks_.metadatatrack_.cues;
if (!cues || !cues.length) {
return;
}
var duration = this.duration();
cues[cues.length - 1].endtime = isnan(duration) || math.abs(duration) === infinity ? number.max_value : duration;
}
/**
* handle the durationchange event on the mediasource
*
* @private
*/
;
_proto.handledurationchange_ = function handledurationchange_() {
this.tech_.trigger('durationchange');
}
/**
* calls endofstream on the media source when all active stream types have called
* endofstream
*
* @param {string} streamtype
* stream type of the segment loader that called endofstream
* @private
*/
;
_proto.onendofstream = function onendofstream() {
var isendofstream = this.mainsegmentloader_.ended_;
if (this.mediatypes_.audio.activeplaylistloader) {
var mainmediainfo = this.mainsegmentloader_.getcurrentmediainfo_(); // if the audio playlist loader exists, then alternate audio is active
if (!mainmediainfo || mainmediainfo.hasvideo) {
// if we do not know if the main segment loader contains video yet or if we
// definitively know the main segment loader contains video, then we need to wait
// for both main and audio segment loaders to call endofstream
isendofstream = isendofstream && this.audiosegmentloader_.ended_;
} else {
// otherwise just rely on the audio loader
isendofstream = this.audiosegmentloader_.ended_;
}
}
if (!isendofstream) {
return;
}
this.stopabrtimer_();
this.sourceupdater_.endofstream();
}
/**
* check if a playlist has stopped being updated
*
* @param {object} playlist the media playlist object
* @return {boolean} whether the playlist has stopped being updated or not
*/
;
_proto.stuckatplaylistend_ = function stuckatplaylistend_(playlist) {
var seekable = this.seekable();
if (!seekable.length) {
// playlist doesn't have enough information to determine whether we are stuck
return false;
}
var expired = this.synccontroller_.getexpiredtime(playlist, this.duration());
if (expired === null) {
return false;
} // does not use the safe live end to calculate playlist end, since we
// don't want to say we are stuck while there is still content
var absoluteplaylistend = vhs$1.playlist.playlistend(playlist, expired);
var currenttime = this.tech_.currenttime();
var buffered = this.tech_.buffered();
if (!buffered.length) {
// return true if the playhead reached the absolute end of the playlist
return absoluteplaylistend - currenttime <= safe_time_delta;
}
var bufferedend = buffered.end(buffered.length - 1); // return true if there is too little buffer left and buffer has reached absolute
// end of playlist
return bufferedend - currenttime <= safe_time_delta && absoluteplaylistend - bufferedend <= safe_time_delta;
}
/**
* blacklists a playlist when an error occurs for a set amount of time
* making it unavailable for selection by the rendition selection algorithm
* and then forces a new playlist (rendition) selection.
*
* @param {object=} error an optional error that may include the playlist
* to blacklist
* @param {number=} blacklistduration an optional number of seconds to blacklist the
* playlist
*/
;
_proto.blacklistcurrentplaylist = function blacklistcurrentplaylist(error, blacklistduration) {
if (error === void 0) {
error = {};
} // if the `error` was generated by the playlist loader, it will contain
// the playlist we were trying to load (but failed) and that should be
// blacklisted instead of the currently selected playlist which is likely
// out-of-date in this scenario
var currentplaylist = error.playlist || this.masterplaylistloader_.media();
blacklistduration = blacklistduration || error.blacklistduration || this.blacklistduration; // if there is no current playlist, then an error occurred while we were
// trying to load the master or while we were disposing of the tech
if (!currentplaylist) {
this.error = error;
if (this.mediasource.readystate !== 'open') {
this.trigger('error');
} else {
this.sourceupdater_.endofstream('network');
}
return;
}
currentplaylist.playlisterrors_++;
var playlists = this.masterplaylistloader_.master.playlists;
var enabledplaylists = playlists.filter(isenabled);
var isfinalrendition = enabledplaylists.length === 1 && enabledplaylists[0] === currentplaylist; // don't blacklist the only playlist unless it was blacklisted
// forever
if (playlists.length === 1 && blacklistduration !== infinity) {
videojs.log.warn("problem encountered with playlist " + currentplaylist.id + ". " + 'trying again since it is the only playlist.');
this.tech_.trigger('retryplaylist'); // if this is a final rendition, we should delay
return this.masterplaylistloader_.load(isfinalrendition);
}
if (isfinalrendition) {
// since we're on the final non-blacklisted playlist, and we're about to blacklist
// it, instead of erring the player or retrying this playlist, clear out the current
// blacklist. this allows other playlists to be attempted in case any have been
// fixed.
var reincluded = false;
playlists.foreach(function (playlist) {
// skip current playlist which is about to be blacklisted
if (playlist === currentplaylist) {
return;
}
var excludeuntil = playlist.excludeuntil; // a playlist cannot be reincluded if it wasn't excluded to begin with.
if (typeof excludeuntil !== 'undefined' && excludeuntil !== infinity) {
reincluded = true;
delete playlist.excludeuntil;
}
});
if (reincluded) {
videojs.log.warn('removing other playlists from the exclusion list because the last ' + 'rendition is about to be excluded.'); // technically we are retrying a playlist, in that we are simply retrying a previous
// playlist. this is needed for users relying on the retryplaylist event to catch a
// case where the player might be stuck and looping through "dead" playlists.
this.tech_.trigger('retryplaylist');
}
} // blacklist this playlist
var excludeuntil;
if (currentplaylist.playlisterrors_ > this.maxplaylistretries) {
excludeuntil = infinity;
} else {
excludeuntil = date.now() + blacklistduration * 1000;
}
currentplaylist.excludeuntil = excludeuntil;
if (error.reason) {
currentplaylist.lastexcludereason_ = error.reason;
}
this.tech_.trigger('blacklistplaylist');
this.tech_.trigger({
type: 'usage',
name: 'vhs-rendition-blacklisted'
});
this.tech_.trigger({
type: 'usage',
name: 'hls-rendition-blacklisted'
}); // todo: should we select a new playlist if this blacklist wasn't for the currentplaylist?
// would be something like media().id !=== currentplaylist.id and we would need something
// like `pendingmedia` in playlist loaders to check against that too. this will prevent us
// from loading a new playlist on any blacklist.
// select a new playlist
var nextplaylist = this.selectplaylist();
if (!nextplaylist) {
this.error = 'playback cannot continue. no available working or supported playlists.';
this.trigger('error');
return;
}
var logfn = error.internal ? this.logger_ : videojs.log.warn;
var errormessage = error.message ? ' ' + error.message : '';
logfn((error.internal ? 'internal problem' : 'problem') + " encountered with playlist " + currentplaylist.id + "." + (errormessage + " switching to playlist " + nextplaylist.id + ".")); // if audio group changed reset audio loaders
if (nextplaylist.attributes.audio !== currentplaylist.attributes.audio) {
this.delegateloaders_('audio', ['abort', 'pause']);
} // if subtitle group changed reset subtitle loaders
if (nextplaylist.attributes.subtitles !== currentplaylist.attributes.subtitles) {
this.delegateloaders_('subtitle', ['abort', 'pause']);
}
this.delegateloaders_('main', ['abort', 'pause']);
var delayduration = nextplaylist.targetduration / 2 * 1000 || 5 * 1000;
var shoulddelay = typeof nextplaylist.lastrequest === 'number' && date.now() - nextplaylist.lastrequest <= delayduration; // delay if it's a final rendition or if the last refresh is sooner than half targetduration
return this.switchmedia_(nextplaylist, 'exclude', isfinalrendition || shoulddelay);
}
/**
* pause all segment/playlist loaders
*/
;
_proto.pauseloading = function pauseloading() {
this.delegateloaders_('all', ['abort', 'pause']);
this.stopabrtimer_();
}
/**
* call a set of functions in order on playlist loaders, segment loaders,
* or both types of loaders.
*
* @param {string} filter
* filter loaders that should call fnnames using a string. can be:
* * all - run on all loaders
* * audio - run on all audio loaders
* * subtitle - run on all subtitle loaders
* * main - run on the main/master loaders
*
* @param {array|string} fnnames
* a string or array of function names to call.
*/
;
_proto.delegateloaders_ = function delegateloaders_(filter, fnnames) {
var _this7 = this;
var loaders = [];
var dontfilterplaylist = filter === 'all';
if (dontfilterplaylist || filter === 'main') {
loaders.push(this.masterplaylistloader_);
}
var mediatypes = [];
if (dontfilterplaylist || filter === 'audio') {
mediatypes.push('audio');
}
if (dontfilterplaylist || filter === 'subtitle') {
mediatypes.push('closed-captions');
mediatypes.push('subtitles');
}
mediatypes.foreach(function (mediatype) {
var loader = _this7.mediatypes_[mediatype] && _this7.mediatypes_[mediatype].activeplaylistloader;
if (loader) {
loaders.push(loader);
}
});
['main', 'audio', 'subtitle'].foreach(function (name) {
var loader = _this7[name + "segmentloader_"];
if (loader && (filter === name || filter === 'all')) {
loaders.push(loader);
}
});
loaders.foreach(function (loader) {
return fnnames.foreach(function (fnname) {
if (typeof loader[fnname] === 'function') {
loader[fnname]();
}
});
});
}
/**
* set the current time on all segment loaders
*
* @param {timerange} currenttime the current time to set
* @return {timerange} the current time
*/
;
_proto.setcurrenttime = function setcurrenttime(currenttime) {
var buffered = findrange(this.tech_.buffered(), currenttime);
if (!(this.masterplaylistloader_ && this.masterplaylistloader_.media())) {
// return immediately if the metadata is not ready yet
return 0;
} // it's clearly an edge-case but don't thrown an error if asked to
// seek within an empty playlist
if (!this.masterplaylistloader_.media().segments) {
return 0;
} // if the seek location is already buffered, continue buffering as usual
if (buffered && buffered.length) {
return currenttime;
} // cancel outstanding requests so we begin buffering at the new
// location
this.mainsegmentloader_.reseteverything();
this.mainsegmentloader_.abort();
if (this.mediatypes_.audio.activeplaylistloader) {
this.audiosegmentloader_.reseteverything();
this.audiosegmentloader_.abort();
}
if (this.mediatypes_.subtitles.activeplaylistloader) {
this.subtitlesegmentloader_.reseteverything();
this.subtitlesegmentloader_.abort();
} // start segment loader loading in case they are paused
this.load();
}
/**
* get the current duration
*
* @return {timerange} the duration
*/
;
_proto.duration = function duration() {
if (!this.masterplaylistloader_) {
return 0;
}
var media = this.masterplaylistloader_.media();
if (!media) {
// no playlists loaded yet, so can't determine a duration
return 0;
} // don't rely on the media source for duration in the case of a live playlist since
// setting the native mediasource's duration to infinity ends up with consequences to
// seekable behavior. see https://github.com/w3c/media-source/issues/5 for details.
//
// this is resolved in the spec by https://github.com/w3c/media-source/pull/92,
// however, few browsers have support for setliveseekablerange()
// https://developer.mozilla.org/en-us/docs/web/api/mediasource/setliveseekablerange
//
// until a time when the duration of the media source can be set to infinity, and a
// seekable range specified across browsers, just return infinity.
if (!media.endlist) {
return infinity;
} // since this is a vod video, it is safe to rely on the media source's duration (if
// available). if it's not available, fall back to a playlist-calculated estimate.
if (this.mediasource) {
return this.mediasource.duration;
}
return vhs$1.playlist.duration(media);
}
/**
* check the seekable range
*
* @return {timerange} the seekable range
*/
;
_proto.seekable = function seekable() {
return this.seekable_;
};
_proto.onsyncinfoupdate_ = function onsyncinfoupdate_() {
var audioseekable; // todo check for creation of both source buffers before updating seekable
//
// a fix was made to this function where a check for
// this.sourceupdater_.hascreatedsourcebuffers
// was added to ensure that both source buffers were created before seekable was
// updated. however, it originally had a bug where it was checking for a true and
// returning early instead of checking for false. setting it to check for false to
// return early though created other issues. a call to play() would check for seekable
// end without verifying that a seekable range was present. in addition, even checking
// for that didn't solve some issues, as handlefirstplay is sometimes worked around
// due to a media update calling load on the segment loaders, skipping a seek to live,
// thereby starting live streams at the beginning of the stream rather than at the end.
//
// this conditional should be fixed to wait for the creation of two source buffers at
// the same time as the other sections of code are fixed to properly seek to live and
// not throw an error due to checking for a seekable end when no seekable range exists.
//
// for now, fall back to the older behavior, with the understanding that the seekable
// range may not be completely correct, leading to a suboptimal initial live point.
if (!this.masterplaylistloader_) {
return;
}
var media = this.masterplaylistloader_.media();
if (!media) {
return;
}
var expired = this.synccontroller_.getexpiredtime(media, this.duration());
if (expired === null) {
// not enough information to update seekable
return;
}
var master = this.masterplaylistloader_.master;
var mainseekable = vhs$1.playlist.seekable(media, expired, vhs$1.playlist.liveedgedelay(master, media));
if (mainseekable.length === 0) {
return;
}
if (this.mediatypes_.audio.activeplaylistloader) {
media = this.mediatypes_.audio.activeplaylistloader.media();
expired = this.synccontroller_.getexpiredtime(media, this.duration());
if (expired === null) {
return;
}
audioseekable = vhs$1.playlist.seekable(media, expired, vhs$1.playlist.liveedgedelay(master, media));
if (audioseekable.length === 0) {
return;
}
}
var oldend;
var oldstart;
if (this.seekable_ && this.seekable_.length) {
oldend = this.seekable_.end(0);
oldstart = this.seekable_.start(0);
}
if (!audioseekable) {
// seekable has been calculated based on buffering video data so it
// can be returned directly
this.seekable_ = mainseekable;
} else if (audioseekable.start(0) > mainseekable.end(0) || mainseekable.start(0) > audioseekable.end(0)) {
// seekables are pretty far off, rely on main
this.seekable_ = mainseekable;
} else {
this.seekable_ = videojs.createtimeranges([[audioseekable.start(0) > mainseekable.start(0) ? audioseekable.start(0) : mainseekable.start(0), audioseekable.end(0) < mainseekable.end(0) ? audioseekable.end(0) : mainseekable.end(0)]]);
} // seekable is the same as last time
if (this.seekable_ && this.seekable_.length) {
if (this.seekable_.end(0) === oldend && this.seekable_.start(0) === oldstart) {
return;
}
}
this.logger_("seekable updated [" + printablerange(this.seekable_) + "]");
this.tech_.trigger('seekablechanged');
}
/**
* update the player duration
*/
;
_proto.updateduration = function updateduration(islive) {
if (this.updateduration_) {
this.mediasource.removeeventlistener('sourceopen', this.updateduration_);
this.updateduration_ = null;
}
if (this.mediasource.readystate !== 'open') {
this.updateduration_ = this.updateduration.bind(this, islive);
this.mediasource.addeventlistener('sourceopen', this.updateduration_);
return;
}
if (islive) {
var seekable = this.seekable();
if (!seekable.length) {
return;
} // even in the case of a live playlist, the native mediasource's duration should not
// be set to infinity (even though this would be expected for a live playlist), since
// setting the native mediasource's duration to infinity ends up with consequences to
// seekable behavior. see https://github.com/w3c/media-source/issues/5 for details.
//
// this is resolved in the spec by https://github.com/w3c/media-source/pull/92,
// however, few browsers have support for setliveseekablerange()
// https://developer.mozilla.org/en-us/docs/web/api/mediasource/setliveseekablerange
//
// until a time when the duration of the media source can be set to infinity, and a
// seekable range specified across browsers, the duration should be greater than or
// equal to the last possible seekable value.
// mediasource duration starts as nan
// it is possible (and probable) that this case will never be reached for many
// sources, since the mediasource reports duration as the highest value without
// accounting for timestamp offset. for example, if the timestamp offset is -100 and
// we buffered times 0 to 100 with real times of 100 to 200, even though current
// time will be between 0 and 100, the native media source may report the duration
// as 200. however, since we report duration separate from the media source (as
// infinity), and as long as the native media source duration value is greater than
// our reported seekable range, seeks will work as expected. the large number as
// duration for live is actually a strategy used by some players to work around the
// issue of live seekable ranges cited above.
if (isnan(this.mediasource.duration) || this.mediasource.duration < seekable.end(seekable.length - 1)) {
this.sourceupdater_.setduration(seekable.end(seekable.length - 1));
}
return;
}
var buffered = this.tech_.buffered();
var duration = vhs$1.playlist.duration(this.masterplaylistloader_.media());
if (buffered.length > 0) {
duration = math.max(duration, buffered.end(buffered.length - 1));
}
if (this.mediasource.duration !== duration) {
this.sourceupdater_.setduration(duration);
}
}
/**
* dispose of the masterplaylistcontroller and everything
* that it controls
*/
;
_proto.dispose = function dispose() {
var _this8 = this;
this.trigger('dispose');
this.decrypter_.terminate();
this.masterplaylistloader_.dispose();
this.mainsegmentloader_.dispose();
if (this.loadonplay_) {
this.tech_.off('play', this.loadonplay_);
}
['audio', 'subtitles'].foreach(function (type) {
var groups = _this8.mediatypes_[type].groups;
for (var id in groups) {
groups[id].foreach(function (group) {
if (group.playlistloader) {
group.playlistloader.dispose();
}
});
}
});
this.audiosegmentloader_.dispose();
this.subtitlesegmentloader_.dispose();
this.sourceupdater_.dispose();
this.timelinechangecontroller_.dispose();
this.stopabrtimer_();
if (this.updateduration_) {
this.mediasource.removeeventlistener('sourceopen', this.updateduration_);
}
this.mediasource.removeeventlistener('durationchange', this.handledurationchange_); // load the media source into the player
this.mediasource.removeeventlistener('sourceopen', this.handlesourceopen_);
this.mediasource.removeeventlistener('sourceended', this.handlesourceended_);
this.off();
}
/**
* return the master playlist object if we have one
*
* @return {object} the master playlist object that we parsed
*/
;
_proto.master = function master() {
return this.masterplaylistloader_.master;
}
/**
* return the currently selected playlist
*
* @return {object} the currently selected playlist object that we parsed
*/
;
_proto.media = function media() {
// playlist loader will not return media if it has not been fully loaded
return this.masterplaylistloader_.media() || this.initialmedia_;
};
_proto.aremediatypesknown_ = function aremediatypesknown_() {
var usingaudioloader = !!this.mediatypes_.audio.activeplaylistloader;
var hasmainmediainfo = !!this.mainsegmentloader_.getcurrentmediainfo_(); // if we are not using an audio loader, then we have audio media info
// otherwise check on the segment loader.
var hasaudiomediainfo = !usingaudioloader ? true : !!this.audiosegmentloader_.getcurrentmediainfo_(); // one or both loaders has not loaded sufficently to get codecs
if (!hasmainmediainfo || !hasaudiomediainfo) {
return false;
}
return true;
};
_proto.getcodecsorexclude_ = function getcodecsorexclude_() {
var _this9 = this;
var media = {
main: this.mainsegmentloader_.getcurrentmediainfo_() || {},
audio: this.audiosegmentloader_.getcurrentmediainfo_() || {}
};
var playlist = this.mainsegmentloader_.getpendingsegmentplaylist() || this.media(); // set "main" media equal to video
media.video = media.main;
var playlistcodecs = codecsforplaylist(this.master(), playlist);
var codecs = {};
var usingaudioloader = !!this.mediatypes_.audio.activeplaylistloader;
if (media.main.hasvideo) {
codecs.video = playlistcodecs.video || media.main.videocodec || _videojs_vhs_utils_es_codecs_js__webpack_imported_module_13__[/* default_video_codec */ "b"];
}
if (media.main.ismuxed) {
codecs.video += "," + (playlistcodecs.audio || media.main.audiocodec || _videojs_vhs_utils_es_codecs_js__webpack_imported_module_13__[/* default_audio_codec */ "a"]);
}
if (media.main.hasaudio && !media.main.ismuxed || media.audio.hasaudio || usingaudioloader) {
codecs.audio = playlistcodecs.audio || media.main.audiocodec || media.audio.audiocodec || _videojs_vhs_utils_es_codecs_js__webpack_imported_module_13__[/* default_audio_codec */ "a"]; // set audio isfmp4 so we use the correct "supports" function below
media.audio.isfmp4 = media.main.hasaudio && !media.main.ismuxed ? media.main.isfmp4 : media.audio.isfmp4;
} // no codecs, no playback.
if (!codecs.audio && !codecs.video) {
this.blacklistcurrentplaylist({
playlist: playlist,
message: 'could not determine codecs for playlist.',
blacklistduration: infinity
});
return;
} // fmp4 relies on browser support, while ts relies on muxer support
var supportfunction = function supportfunction(isfmp4, codec) {
return isfmp4 ? object(_videojs_vhs_utils_es_codecs_js__webpack_imported_module_13__[/* browsersupportscodec */ "c"])(codec) : object(_videojs_vhs_utils_es_codecs_js__webpack_imported_module_13__[/* muxersupportscodec */ "g"])(codec);
};
var unsupportedcodecs = {};
var unsupportedaudio;
['video', 'audio'].foreach(function (type) {
if (codecs.hasownproperty(type) && !supportfunction(media[type].isfmp4, codecs[type])) {
var supporter = media[type].isfmp4 ? 'browser' : 'muxer';
unsupportedcodecs[supporter] = unsupportedcodecs[supporter] || [];
unsupportedcodecs[supporter].push(codecs[type]);
if (type === 'audio') {
unsupportedaudio = supporter;
}
}
});
if (usingaudioloader && unsupportedaudio && playlist.attributes.audio) {
var audiogroup = playlist.attributes.audio;
this.master().playlists.foreach(function (variant) {
var variantaudiogroup = variant.attributes && variant.attributes.audio;
if (variantaudiogroup === audiogroup && variant !== playlist) {
variant.excludeuntil = infinity;
}
});
this.logger_("excluding audio group " + audiogroup + " as " + unsupportedaudio + " does not support codec(s): \"" + codecs.audio + "\"");
} // if we have any unsupported codecs blacklist this playlist.
if (object.keys(unsupportedcodecs).length) {
var message = object.keys(unsupportedcodecs).reduce(function (acc, supporter) {
if (acc) {
acc += ', ';
}
acc += supporter + " does not support codec(s): \"" + unsupportedcodecs[supporter].join(',') + "\"";
return acc;
}, '') + '.';
this.blacklistcurrentplaylist({
playlist: playlist,
internal: true,
message: message,
blacklistduration: infinity
});
return;
} // check if codec switching is happening
if (this.sourceupdater_.hascreatedsourcebuffers() && !this.sourceupdater_.canchangetype()) {
var switchmessages = [];
['video', 'audio'].foreach(function (type) {
var newcodec = (object(_videojs_vhs_utils_es_codecs_js__webpack_imported_module_13__[/* parsecodecs */ "h"])(_this9.sourceupdater_.codecs[type] || '')[0] || {}).type;
var oldcodec = (object(_videojs_vhs_utils_es_codecs_js__webpack_imported_module_13__[/* parsecodecs */ "h"])(codecs[type] || '')[0] || {}).type;
if (newcodec && oldcodec && newcodec.tolowercase() !== oldcodec.tolowercase()) {
switchmessages.push("\"" + _this9.sourceupdater_.codecs[type] + "\" -> \"" + codecs[type] + "\"");
}
});
if (switchmessages.length) {
this.blacklistcurrentplaylist({
playlist: playlist,
message: "codec switching not supported: " + switchmessages.join(', ') + ".",
blacklistduration: infinity,
internal: true
});
return;
}
} // todo: when using the muxer shouldn't we just return
// the codecs that the muxer outputs?
return codecs;
}
/**
* create source buffers and exlude any incompatible renditions.
*
* @private
*/
;
_proto.trytocreatesourcebuffers_ = function trytocreatesourcebuffers_() {
// media source is not ready yet or sourcebuffers are already
// created.
if (this.mediasource.readystate !== 'open' || this.sourceupdater_.hascreatedsourcebuffers()) {
return;
}
if (!this.aremediatypesknown_()) {
return;
}
var codecs = this.getcodecsorexclude_(); // no codecs means that the playlist was excluded
if (!codecs) {
return;
}
this.sourceupdater_.createsourcebuffers(codecs);
var codecstring = [codecs.video, codecs.audio].filter(boolean).join(',');
this.excludeincompatiblevariants_(codecstring);
}
/**
* excludes playlists with codecs that are unsupported by the muxer and browser.
*/
;
_proto.excludeunsupportedvariants_ = function excludeunsupportedvariants_() {
var _this10 = this;
var playlists = this.master().playlists;
var ids = []; // todo: why don't we have a property to loop through all
// playlist? why did we ever mix indexes and keys?
object.keys(playlists).foreach(function (key) {
var variant = playlists[key]; // check if we already processed this playlist.
if (ids.indexof(variant.id) !== -1) {
return;
}
ids.push(variant.id);
var codecs = codecsforplaylist(_this10.master, variant);
var unsupported = [];
if (codecs.audio && !object(_videojs_vhs_utils_es_codecs_js__webpack_imported_module_13__[/* muxersupportscodec */ "g"])(codecs.audio) && !object(_videojs_vhs_utils_es_codecs_js__webpack_imported_module_13__[/* browsersupportscodec */ "c"])(codecs.audio)) {
unsupported.push("audio codec " + codecs.audio);
}
if (codecs.video && !object(_videojs_vhs_utils_es_codecs_js__webpack_imported_module_13__[/* muxersupportscodec */ "g"])(codecs.video) && !object(_videojs_vhs_utils_es_codecs_js__webpack_imported_module_13__[/* browsersupportscodec */ "c"])(codecs.video)) {
unsupported.push("video codec " + codecs.video);
}
if (codecs.text && codecs.text === 'stpp.ttml.im1t') {
unsupported.push("text codec " + codecs.text);
}
if (unsupported.length) {
variant.excludeuntil = infinity;
_this10.logger_("excluding " + variant.id + " for unsupported: " + unsupported.join(', '));
}
});
}
/**
* blacklist playlists that are known to be codec or
* stream-incompatible with the sourcebuffer configuration. for
* instance, media source extensions would cause the video element to
* stall waiting for video data if you switched from a variant with
* video and audio to an audio-only one.
*
* @param {object} media a media playlist compatible with the current
* set of sourcebuffers. variants in the current master playlist that
* do not appear to have compatible codec or stream configurations
* will be excluded from the default playlist selection algorithm
* indefinitely.
* @private
*/
;
_proto.excludeincompatiblevariants_ = function excludeincompatiblevariants_(codecstring) {
var _this11 = this;
var ids = [];
var playlists = this.master().playlists;
var codecs = unwrapcodeclist(object(_videojs_vhs_utils_es_codecs_js__webpack_imported_module_13__[/* parsecodecs */ "h"])(codecstring));
var codeccount_ = codeccount(codecs);
var videodetails = codecs.video && object(_videojs_vhs_utils_es_codecs_js__webpack_imported_module_13__[/* parsecodecs */ "h"])(codecs.video)[0] || null;
var audiodetails = codecs.audio && object(_videojs_vhs_utils_es_codecs_js__webpack_imported_module_13__[/* parsecodecs */ "h"])(codecs.audio)[0] || null;
object.keys(playlists).foreach(function (key) {
var variant = playlists[key]; // check if we already processed this playlist.
// or it if it is already excluded forever.
if (ids.indexof(variant.id) !== -1 || variant.excludeuntil === infinity) {
return;
}
ids.push(variant.id);
var blacklistreasons = []; // get codecs from the playlist for this variant
var variantcodecs = codecsforplaylist(_this11.masterplaylistloader_.master, variant);
var variantcodeccount = codeccount(variantcodecs); // if no codecs are listed, we cannot determine that this
// variant is incompatible. wait for mux.js to probe
if (!variantcodecs.audio && !variantcodecs.video) {
return;
} // todo: we can support this by removing the
// old media source and creating a new one, but it will take some work.
// the number of streams cannot change
if (variantcodeccount !== codeccount_) {
blacklistreasons.push("codec count \"" + variantcodeccount + "\" !== \"" + codeccount_ + "\"");
} // only exclude playlists by codec change, if codecs cannot switch
// during playback.
if (!_this11.sourceupdater_.canchangetype()) {
var variantvideodetails = variantcodecs.video && object(_videojs_vhs_utils_es_codecs_js__webpack_imported_module_13__[/* parsecodecs */ "h"])(variantcodecs.video)[0] || null;
var variantaudiodetails = variantcodecs.audio && object(_videojs_vhs_utils_es_codecs_js__webpack_imported_module_13__[/* parsecodecs */ "h"])(variantcodecs.audio)[0] || null; // the video codec cannot change
if (variantvideodetails && videodetails && variantvideodetails.type.tolowercase() !== videodetails.type.tolowercase()) {
blacklistreasons.push("video codec \"" + variantvideodetails.type + "\" !== \"" + videodetails.type + "\"");
} // the audio codec cannot change
if (variantaudiodetails && audiodetails && variantaudiodetails.type.tolowercase() !== audiodetails.type.tolowercase()) {
blacklistreasons.push("audio codec \"" + variantaudiodetails.type + "\" !== \"" + audiodetails.type + "\"");
}
}
if (blacklistreasons.length) {
variant.excludeuntil = infinity;
_this11.logger_("blacklisting " + variant.id + ": " + blacklistreasons.join(' && '));
}
});
};
_proto.updateadcues_ = function updateadcues_(media) {
var offset = 0;
var seekable = this.seekable();
if (seekable.length) {
offset = seekable.start(0);
}
updateadcues(media, this.cuetagstrack_, offset);
}
/**
* calculates the desired forward buffer length based on current time
*
* @return {number} desired forward buffer length in seconds
*/
;
_proto.goalbufferlength = function goalbufferlength() {
var currenttime = this.tech_.currenttime();
var initial = config.goal_buffer_length;
var rate = config.goal_buffer_length_rate;
var max = math.max(initial, config.max_goal_buffer_length);
return math.min(initial + currenttime * rate, max);
}
/**
* calculates the desired buffer low water line based on current time
*
* @return {number} desired buffer low water line in seconds
*/
;
_proto.bufferlowwaterline = function bufferlowwaterline() {
var currenttime = this.tech_.currenttime();
var initial = config.buffer_low_water_line;
var rate = config.buffer_low_water_line_rate;
var max = math.max(initial, config.max_buffer_low_water_line);
var newmax = math.max(initial, config.experimental_max_buffer_low_water_line);
return math.min(initial + currenttime * rate, this.experimentalbufferbasedabr ? newmax : max);
};
_proto.bufferhighwaterline = function bufferhighwaterline() {
return config.buffer_high_water_line;
};
return masterplaylistcontroller;
}(videojs.eventtarget);
/**
* returns a function that acts as the enable/disable playlist function.
*
* @param {playlistloader} loader - the master playlist loader
* @param {string} playlistid - id of the playlist
* @param {function} changeplaylistfn - a function to be called after a
* playlist's enabled-state has been changed. will not be called if a
* playlist's enabled-state is unchanged
* @param {boolean=} enable - value to set the playlist enabled-state to
* or if undefined returns the current enabled-state for the playlist
* @return {function} function for setting/getting enabled
*/
var enablefunction = function enablefunction(loader, playlistid, changeplaylistfn) {
return function (enable) {
var playlist = loader.master.playlists[playlistid];
var incompatible = isincompatible(playlist);
var currentlyenabled = isenabled(playlist);
if (typeof enable === 'undefined') {
return currentlyenabled;
}
if (enable) {
delete playlist.disabled;
} else {
playlist.disabled = true;
}
if (enable !== currentlyenabled && !incompatible) {
// ensure the outside world knows about our changes
changeplaylistfn();
if (enable) {
loader.trigger('renditionenabled');
} else {
loader.trigger('renditiondisabled');
}
}
return enable;
};
};
/**
* the representation object encapsulates the publicly visible information
* in a media playlist along with a setter/getter-type function (enabled)
* for changing the enabled-state of a particular playlist entry
*
* @class representation
*/
var representation = function representation(vhshandler, playlist, id) {
var mpc = vhshandler.masterplaylistcontroller_,
smoothqualitychange = vhshandler.options_.smoothqualitychange; // get a reference to a bound version of the quality change function
var changetype = smoothqualitychange ? 'smooth' : 'fast';
var qualitychangefunction = mpc[changetype + "qualitychange_"].bind(mpc); // some playlist attributes are optional
if (playlist.attributes) {
var resolution = playlist.attributes.resolution;
this.width = resolution && resolution.width;
this.height = resolution && resolution.height;
this.bandwidth = playlist.attributes.bandwidth;
this.framerate = playlist.attributes['frame-rate'];
}
this.codecs = codecsforplaylist(mpc.master(), playlist);
this.playlist = playlist; // the id is simply the ordinality of the media playlist
// within the master playlist
this.id = id; // partially-apply the enablefunction to create a playlist-
// specific variant
this.enabled = enablefunction(vhshandler.playlists, playlist.id, qualitychangefunction);
};
/**
* a mixin function that adds the `representations` api to an instance
* of the vhshandler class
*
* @param {vhshandler} vhshandler - an instance of vhshandler to add the
* representation api into
*/
var renditionselectionmixin = function renditionselectionmixin(vhshandler) {
// add a single api-specific function to the vhshandler instance
vhshandler.representations = function () {
var master = vhshandler.masterplaylistcontroller_.master();
var playlists = isaudioonly(master) ? vhshandler.masterplaylistcontroller_.getaudiotrackplaylists_() : master.playlists;
if (!playlists) {
return [];
}
return playlists.filter(function (media) {
return !isincompatible(media);
}).map(function (e, i) {
return new representation(vhshandler, e, e.id);
});
};
};
/**
* @file playback-watcher.js
*
* playback starts, and now my watch begins. it shall not end until my death. i shall
* take no wait, hold no uncleared timeouts, father no bad seeks. i shall wear no crowns
* and win no glory. i shall live and die at my post. i am the corrector of the underflow.
* i am the watcher of gaps. i am the shield that guards the realms of seekable. i pledge
* my life and honor to the playback watch, for this player and all the players to come.
*/
var timercancelevents = ['seeking', 'seeked', 'pause', 'playing', 'error'];
/**
* @class playbackwatcher
*/
var playbackwatcher = /*#__pure__*/function () {
/**
* represents an playbackwatcher object.
*
* @class
* @param {object} options an object that includes the tech and settings
*/
function playbackwatcher(options) {
var _this = this;
this.masterplaylistcontroller_ = options.masterplaylistcontroller;
this.tech_ = options.tech;
this.seekable = options.seekable;
this.allowseekswithinunsafelivewindow = options.allowseekswithinunsafelivewindow;
this.liverangesafetimedelta = options.liverangesafetimedelta;
this.media = options.media;
this.consecutiveupdates = 0;
this.lastrecordedtime = null;
this.timer_ = null;
this.checkcurrenttimetimeout_ = null;
this.logger_ = logger('playbackwatcher');
this.logger_('initialize');
var playhandler = function playhandler() {
return _this.monitorcurrenttime_();
};
var canplayhandler = function canplayhandler() {
return _this.monitorcurrenttime_();
};
var waitinghandler = function waitinghandler() {
return _this.techwaiting_();
};
var canceltimerhandler = function canceltimerhandler() {
return _this.canceltimer_();
};
var mpc = this.masterplaylistcontroller_;
var loadertypes = ['main', 'subtitle', 'audio'];
var loaderchecks = {};
loadertypes.foreach(function (type) {
loaderchecks[type] = {
reset: function reset() {
return _this.resetsegmentdownloads_(type);
},
updateend: function updateend() {
return _this.checksegmentdownloads_(type);
}
};
mpc[type + "segmentloader_"].on('appendsdone', loaderchecks[type].updateend); // if a rendition switch happens during a playback stall where the buffer
// isn't changing we want to reset. we cannot assume that the new rendition
// will also be stalled, until after new appends.
mpc[type + "segmentloader_"].on('playlistupdate', loaderchecks[type].reset); // playback stalls should not be detected right after seeking.
// this prevents one segment playlists (single vtt or single segment content)
// from being detected as stalling. as the buffer will not change in those cases, since
// the buffer is the entire video duration.
_this.tech_.on(['seeked', 'seeking'], loaderchecks[type].reset);
});
/**
* we check if a seek was into a gap through the following steps:
* 1. we get a seeking event and we do not get a seeked event. this means that
* a seek was attempted but not completed.
* 2. we run `fixesbadseeks_` on segment loader appends. this means that we already
* removed everything from our buffer and appended a segment, and should be ready
* to check for gaps.
*/
var setseekinghandlers = function setseekinghandlers(fn) {
['main', 'audio'].foreach(function (type) {
mpc[type + "segmentloader_"][fn]('appended', _this.seekingappendcheck_);
});
};
this.seekingappendcheck_ = function () {
if (_this.fixesbadseeks_()) {
_this.consecutiveupdates = 0;
_this.lastrecordedtime = _this.tech_.currenttime();
setseekinghandlers('off');
}
};
this.clearseekingappendcheck_ = function () {
return setseekinghandlers('off');
};
this.watchforbadseeking_ = function () {
_this.clearseekingappendcheck_();
setseekinghandlers('on');
};
this.tech_.on('seeked', this.clearseekingappendcheck_);
this.tech_.on('seeking', this.watchforbadseeking_);
this.tech_.on('waiting', waitinghandler);
this.tech_.on(timercancelevents, canceltimerhandler);
this.tech_.on('canplay', canplayhandler);
/*
an edge case exists that results in gaps not being skipped when they exist at the beginning of a stream. this case
is surfaced in one of two ways:
1) the `waiting` event is fired before the player has buffered content, making it impossible
to find or skip the gap. the `waiting` event is followed by a `play` event. on first play
we can check if playback is stalled due to a gap, and skip the gap if necessary.
2) a source with a gap at the beginning of the stream is loaded programatically while the player
is in a playing state. to catch this case, it's important that our one-time play listener is setup
even if the player is in a playing state
*/
this.tech_.one('play', playhandler); // define the dispose function to clean up our events
this.dispose = function () {
_this.clearseekingappendcheck_();
_this.logger_('dispose');
_this.tech_.off('waiting', waitinghandler);
_this.tech_.off(timercancelevents, canceltimerhandler);
_this.tech_.off('canplay', canplayhandler);
_this.tech_.off('play', playhandler);
_this.tech_.off('seeking', _this.watchforbadseeking_);
_this.tech_.off('seeked', _this.clearseekingappendcheck_);
loadertypes.foreach(function (type) {
mpc[type + "segmentloader_"].off('appendsdone', loaderchecks[type].updateend);
mpc[type + "segmentloader_"].off('playlistupdate', loaderchecks[type].reset);
_this.tech_.off(['seeked', 'seeking'], loaderchecks[type].reset);
});
if (_this.checkcurrenttimetimeout_) {
global_window__webpack_imported_module_0___default.a.cleartimeout(_this.checkcurrenttimetimeout_);
}
_this.canceltimer_();
};
}
/**
* periodically check current time to see if playback stopped
*
* @private
*/
var _proto = playbackwatcher.prototype;
_proto.monitorcurrenttime_ = function monitorcurrenttime_() {
this.checkcurrenttime_();
if (this.checkcurrenttimetimeout_) {
global_window__webpack_imported_module_0___default.a.cleartimeout(this.checkcurrenttimetimeout_);
} // 42 = 24 fps // 250 is what webkit uses // ff uses 15
this.checkcurrenttimetimeout_ = global_window__webpack_imported_module_0___default.a.settimeout(this.monitorcurrenttime_.bind(this), 250);
}
/**
* reset stalled download stats for a specific type of loader
*
* @param {string} type
* the segment loader type to check.
*
* @listens segmentloader#playlistupdate
* @listens tech#seeking
* @listens tech#seeked
*/
;
_proto.resetsegmentdownloads_ = function resetsegmentdownloads_(type) {
var loader = this.masterplaylistcontroller_[type + "segmentloader_"];
if (this[type + "stalleddownloads_"] > 0) {
this.logger_("resetting possible stalled download count for " + type + " loader");
}
this[type + "stalleddownloads_"] = 0;
this[type + "buffered_"] = loader.buffered_();
}
/**
* checks on every segment `appendsdone` to see
* if segment appends are making progress. if they are not
* and we are still downloading bytes. we blacklist the playlist.
*
* @param {string} type
* the segment loader type to check.
*
* @listens segmentloader#appendsdone
*/
;
_proto.checksegmentdownloads_ = function checksegmentdownloads_(type) {
var mpc = this.masterplaylistcontroller_;
var loader = mpc[type + "segmentloader_"];
var buffered = loader.buffered_();
var isbuffereddifferent = israngedifferent(this[type + "buffered_"], buffered);
this[type + "buffered_"] = buffered; // if another watcher is going to fix the issue or
// the buffered value for this loader changed
// appends are working
if (isbuffereddifferent) {
this.resetsegmentdownloads_(type);
return;
}
this[type + "stalleddownloads_"]++;
this.logger_("found #" + this[type + "stalleddownloads_"] + " " + type + " appends that did not increase buffer (possible stalled download)", {
playlistid: loader.playlist_ && loader.playlist_.id,
buffered: timerangestoarray(buffered)
}); // after 10 possibly stalled appends with no reset, exclude
if (this[type + "stalleddownloads_"] < 10) {
return;
}
this.logger_(type + " loader stalled download exclusion");
this.resetsegmentdownloads_(type);
this.tech_.trigger({
type: 'usage',
name: "vhs-" + type + "-download-exclusion"
});
if (type === 'subtitle') {
return;
} // todo: should we exclude audio tracks rather than main tracks
// when type is audio?
mpc.blacklistcurrentplaylist({
message: "excessive " + type + " segment downloading detected."
}, infinity);
}
/**
* the purpose of this function is to emulate the "waiting" event on
* browsers that do not emit it when they are waiting for more
* data to continue playback
*
* @private
*/
;
_proto.checkcurrenttime_ = function checkcurrenttime_() {
if (this.tech_.paused() || this.tech_.seeking()) {
return;
}
var currenttime = this.tech_.currenttime();
var buffered = this.tech_.buffered();
if (this.lastrecordedtime === currenttime && (!buffered.length || currenttime + safe_time_delta >= buffered.end(buffered.length - 1))) {
// if current time is at the end of the final buffered region, then any playback
// stall is most likely caused by buffering in a low bandwidth environment. the tech
// should fire a `waiting` event in this scenario, but due to browser and tech
// inconsistencies. calling `techwaiting_` here allows us to simulate
// responding to a native `waiting` event when the tech fails to emit one.
return this.techwaiting_();
}
if (this.consecutiveupdates >= 5 && currenttime === this.lastrecordedtime) {
this.consecutiveupdates++;
this.waiting_();
} else if (currenttime === this.lastrecordedtime) {
this.consecutiveupdates++;
} else {
this.consecutiveupdates = 0;
this.lastrecordedtime = currenttime;
}
}
/**
* cancels any pending timers and resets the 'timeupdate' mechanism
* designed to detect that we are stalled
*
* @private
*/
;
_proto.canceltimer_ = function canceltimer_() {
this.consecutiveupdates = 0;
if (this.timer_) {
this.logger_('canceltimer_');
cleartimeout(this.timer_);
}
this.timer_ = null;
}
/**
* fixes situations where there's a bad seek
*
* @return {boolean} whether an action was taken to fix the seek
* @private
*/
;
_proto.fixesbadseeks_ = function fixesbadseeks_() {
var seeking = this.tech_.seeking();
if (!seeking) {
return false;
} // todo: it's possible that these seekable checks should be moved out of this function
// and into a function that runs on seekablechange. it's also possible that we only need
// afterseekablewindow as the buffered check at the bottom is good enough to handle before
// seekable range.
var seekable = this.seekable();
var currenttime = this.tech_.currenttime();
var isafterseekablerange = this.afterseekablewindow_(seekable, currenttime, this.media(), this.allowseekswithinunsafelivewindow);
var seekto;
if (isafterseekablerange) {
var seekableend = seekable.end(seekable.length - 1); // sync to live point (if vod, our seekable was updated and we're simply adjusting)
seekto = seekableend;
}
if (this.beforeseekablewindow_(seekable, currenttime)) {
var seekablestart = seekable.start(0); // sync to the beginning of the live window
// provide a buffer of .1 seconds to handle rounding/imprecise numbers
seekto = seekablestart + ( // if the playlist is too short and the seekable range is an exact time (can
// happen in live with a 3 segment playlist), then don't use a time delta
seekablestart === seekable.end(0) ? 0 : safe_time_delta);
}
if (typeof seekto !== 'undefined') {
this.logger_("trying to seek outside of seekable at time " + currenttime + " with " + ("seekable range " + printablerange(seekable) + ". seeking to ") + (seekto + "."));
this.tech_.setcurrenttime(seekto);
return true;
}
var sourceupdater = this.masterplaylistcontroller_.sourceupdater_;
var buffered = this.tech_.buffered();
var audiobuffered = sourceupdater.audiobuffer ? sourceupdater.audiobuffered() : null;
var videobuffered = sourceupdater.videobuffer ? sourceupdater.videobuffered() : null;
var media = this.media(); // verify that at least two segment durations or one part duration have been
// appended before checking for a gap.
var minappendedduration = media.parttargetduration ? media.parttargetduration : (media.targetduration - time_fudge_factor) * 2; // verify that at least two segment durations have been
// appended before checking for a gap.
var bufferedtocheck = [audiobuffered, videobuffered];
for (var i = 0; i < bufferedtocheck.length; i++) {
// skip null buffered
if (!bufferedtocheck[i]) {
continue;
}
var timeahead = timeaheadof(bufferedtocheck[i], currenttime); // if we are less than two video/audio segment durations or one part
// duration behind we haven't appended enough to call this a bad seek.
if (timeahead < minappendedduration) {
return false;
}
}
var nextrange = findnextrange(buffered, currenttime); // we have appended enough content, but we don't have anything buffered
// to seek over the gap
if (nextrange.length === 0) {
return false;
}
seekto = nextrange.start(0) + safe_time_delta;
this.logger_("buffered region starts (" + nextrange.start(0) + ") " + (" just beyond seek point (" + currenttime + "). seeking to " + seekto + "."));
this.tech_.setcurrenttime(seekto);
return true;
}
/**
* handler for situations when we determine the player is waiting.
*
* @private
*/
;
_proto.waiting_ = function waiting_() {
if (this.techwaiting_()) {
return;
} // all tech waiting checks failed. use last resort correction
var currenttime = this.tech_.currenttime();
var buffered = this.tech_.buffered();
var currentrange = findrange(buffered, currenttime); // sometimes the player can stall for unknown reasons within a contiguous buffered
// region with no indication that anything is amiss (seen in firefox). seeking to
// currenttime is usually enough to kickstart the player. this checks that the player
// is currently within a buffered region before attempting a corrective seek.
// chrome does not appear to continue `timeupdate` events after a `waiting` event
// until there is ~ 3 seconds of forward buffer available. playbackwatcher should also
// make sure there is ~3 seconds of forward buffer before taking any corrective action
// to avoid triggering an `unknownwaiting` event when the network is slow.
if (currentrange.length && currenttime + 3 <= currentrange.end(0)) {
this.canceltimer_();
this.tech_.setcurrenttime(currenttime);
this.logger_("stopped at " + currenttime + " while inside a buffered region " + ("[" + currentrange.start(0) + " -> " + currentrange.end(0) + "]. attempting to resume ") + 'playback by seeking to the current time.'); // unknown waiting corrections may be useful for monitoring qos
this.tech_.trigger({
type: 'usage',
name: 'vhs-unknown-waiting'
});
this.tech_.trigger({
type: 'usage',
name: 'hls-unknown-waiting'
});
return;
}
}
/**
* handler for situations when the tech fires a `waiting` event
*
* @return {boolean}
* true if an action (or none) was needed to correct the waiting. false if no
* checks passed
* @private
*/
;
_proto.techwaiting_ = function techwaiting_() {
var seekable = this.seekable();
var currenttime = this.tech_.currenttime();
if (this.tech_.seeking() || this.timer_ !== null) {
// tech is seeking or already waiting on another action, no action needed
return true;
}
if (this.beforeseekablewindow_(seekable, currenttime)) {
var livepoint = seekable.end(seekable.length - 1);
this.logger_("fell out of live window at time " + currenttime + ". seeking to " + ("live point (seekable end) " + livepoint));
this.canceltimer_();
this.tech_.setcurrenttime(livepoint); // live window resyncs may be useful for monitoring qos
this.tech_.trigger({
type: 'usage',
name: 'vhs-live-resync'
});
this.tech_.trigger({
type: 'usage',
name: 'hls-live-resync'
});
return true;
}
var sourceupdater = this.tech_.vhs.masterplaylistcontroller_.sourceupdater_;
var buffered = this.tech_.buffered();
var videounderflow = this.videounderflow_({
audiobuffered: sourceupdater.audiobuffered(),
videobuffered: sourceupdater.videobuffered(),
currenttime: currenttime
});
if (videounderflow) {
// even though the video underflowed and was stuck in a gap, the audio overplayed
// the gap, leading currenttime into a buffered range. seeking to currenttime
// allows the video to catch up to the audio position without losing any audio
// (only suffering ~3 seconds of frozen video and a pause in audio playback).
this.canceltimer_();
this.tech_.setcurrenttime(currenttime); // video underflow may be useful for monitoring qos
this.tech_.trigger({
type: 'usage',
name: 'vhs-video-underflow'
});
this.tech_.trigger({
type: 'usage',
name: 'hls-video-underflow'
});
return true;
}
var nextrange = findnextrange(buffered, currenttime); // check for gap
if (nextrange.length > 0) {
var difference = nextrange.start(0) - currenttime;
this.logger_("stopped at " + currenttime + ", setting timer for " + difference + ", seeking " + ("to " + nextrange.start(0)));
this.canceltimer_();
this.timer_ = settimeout(this.skipthegap_.bind(this), difference * 1000, currenttime);
return true;
} // all checks failed. returning false to indicate failure to correct waiting
return false;
};
_proto.afterseekablewindow_ = function afterseekablewindow_(seekable, currenttime, playlist, allowseekswithinunsafelivewindow) {
if (allowseekswithinunsafelivewindow === void 0) {
allowseekswithinunsafelivewindow = false;
}
if (!seekable.length) {
// we can't make a solid case if there's no seekable, default to false
return false;
}
var allowedend = seekable.end(seekable.length - 1) + safe_time_delta;
var islive = !playlist.endlist;
if (islive && allowseekswithinunsafelivewindow) {
allowedend = seekable.end(seekable.length - 1) + playlist.targetduration * 3;
}
if (currenttime > allowedend) {
return true;
}
return false;
};
_proto.beforeseekablewindow_ = function beforeseekablewindow_(seekable, currenttime) {
if (seekable.length && // can't fall before 0 and 0 seekable start identifies vod stream
seekable.start(0) > 0 && currenttime < seekable.start(0) - this.liverangesafetimedelta) {
return true;
}
return false;
};
_proto.videounderflow_ = function videounderflow_(_ref) {
var videobuffered = _ref.videobuffered,
audiobuffered = _ref.audiobuffered,
currenttime = _ref.currenttime; // audio only content will not have video underflow :)
if (!videobuffered) {
return;
}
var gap; // find a gap in demuxed content.
if (videobuffered.length && audiobuffered.length) {
// in chrome audio will continue to play for ~3s when we run out of video
// so we have to check that the video buffer did have some buffer in the
// past.
var lastvideorange = findrange(videobuffered, currenttime - 3);
var videorange = findrange(videobuffered, currenttime);
var audiorange = findrange(audiobuffered, currenttime);
if (audiorange.length && !videorange.length && lastvideorange.length) {
gap = {
start: lastvideorange.end(0),
end: audiorange.end(0)
};
} // find a gap in muxed content.
} else {
var nextrange = findnextrange(videobuffered, currenttime); // even if there is no available next range, there is still a possibility we are
// stuck in a gap due to video underflow.
if (!nextrange.length) {
gap = this.gapfromvideounderflow_(videobuffered, currenttime);
}
}
if (gap) {
this.logger_("encountered a gap in video from " + gap.start + " to " + gap.end + ". " + ("seeking to current time " + currenttime));
return true;
}
return false;
}
/**
* timer callback. if playback still has not proceeded, then we seek
* to the start of the next buffered region.
*
* @private
*/
;
_proto.skipthegap_ = function skipthegap_(scheduledcurrenttime) {
var buffered = this.tech_.buffered();
var currenttime = this.tech_.currenttime();
var nextrange = findnextrange(buffered, currenttime);
this.canceltimer_();
if (nextrange.length === 0 || currenttime !== scheduledcurrenttime) {
return;
}
this.logger_('skipthegap_:', 'currenttime:', currenttime, 'scheduled currenttime:', scheduledcurrenttime, 'nextrange start:', nextrange.start(0)); // only seek if we still have not played
this.tech_.setcurrenttime(nextrange.start(0) + time_fudge_factor);
this.tech_.trigger({
type: 'usage',
name: 'vhs-gap-skip'
});
this.tech_.trigger({
type: 'usage',
name: 'hls-gap-skip'
});
};
_proto.gapfromvideounderflow_ = function gapfromvideounderflow_(buffered, currenttime) {
// at least in chrome, if there is a gap in the video buffer, the audio will continue
// playing for ~3 seconds after the video gap starts. this is done to account for
// video buffer underflow/underrun (note that this is not done when there is audio
// buffer underflow/underrun -- in that case the video will stop as soon as it
// encounters the gap, as audio stalls are more noticeable/jarring to a user than
// video stalls). the player's time will reflect the playthrough of audio, so the
// time will appear as if we are in a buffered region, even if we are stuck in a
// "gap."
//
// example:
// video buffer: 0 => 10.1, 10.2 => 20
// audio buffer: 0 => 20
// overall buffer: 0 => 10.1, 10.2 => 20
// current time: 13
//
// chrome's video froze at 10 seconds, where the video buffer encountered the gap,
// however, the audio continued playing until it reached ~3 seconds past the gap
// (13 seconds), at which point it stops as well. since current time is past the
// gap, findnextrange will return no ranges.
//
// to check for this issue, we see if there is a gap that starts somewhere within
// a 3 second range (3 seconds +/- 1 second) back from our current time.
var gaps = findgaps(buffered);
for (var i = 0; i < gaps.length; i++) {
var start = gaps.start(i);
var end = gaps.end(i); // gap is starts no more than 4 seconds back
if (currenttime - start < 4 && currenttime - start > 2) {
return {
start: start,
end: end
};
}
}
return null;
};
return playbackwatcher;
}();
var defaultoptions = {
errorinterval: 30,
getsource: function getsource(next) {
var tech = this.tech({
iwillnotusethisinplugins: true
});
var sourceobj = tech.currentsource_ || this.currentsource();
return next(sourceobj);
}
};
/**
* main entry point for the plugin
*
* @param {player} player a reference to a videojs player instance
* @param {object} [options] an object with plugin options
* @private
*/
var initplugin = function initplugin(player, options) {
var lastcalled = 0;
var seekto = 0;
var localoptions = videojs.mergeoptions(defaultoptions, options);
player.ready(function () {
player.trigger({
type: 'usage',
name: 'vhs-error-reload-initialized'
});
player.trigger({
type: 'usage',
name: 'hls-error-reload-initialized'
});
});
/**
* player modifications to perform that must wait until `loadedmetadata`
* has been triggered
*
* @private
*/
var loadedmetadatahandler = function loadedmetadatahandler() {
if (seekto) {
player.currenttime(seekto);
}
};
/**
* set the source on the player element, play, and seek if necessary
*
* @param {object} sourceobj an object specifying the source url and mime-type to play
* @private
*/
var setsource = function setsource(sourceobj) {
if (sourceobj === null || sourceobj === undefined) {
return;
}
seekto = player.duration() !== infinity && player.currenttime() || 0;
player.one('loadedmetadata', loadedmetadatahandler);
player.src(sourceobj);
player.trigger({
type: 'usage',
name: 'vhs-error-reload'
});
player.trigger({
type: 'usage',
name: 'hls-error-reload'
});
player.play();
};
/**
* attempt to get a source from either the built-in getsource function
* or a custom function provided via the options
*
* @private
*/
var errorhandler = function errorhandler() {
// do not attempt to reload the source if a source-reload occurred before
// 'errorinterval' time has elapsed since the last source-reload
if (date.now() - lastcalled < localoptions.errorinterval * 1000) {
player.trigger({
type: 'usage',
name: 'vhs-error-reload-canceled'
});
player.trigger({
type: 'usage',
name: 'hls-error-reload-canceled'
});
return;
}
if (!localoptions.getsource || typeof localoptions.getsource !== 'function') {
videojs.log.error('error: reloadsourceonerror - the option getsource must be a function!');
return;
}
lastcalled = date.now();
return localoptions.getsource.call(player, setsource);
};
/**
* unbind any event handlers that were bound by the plugin
*
* @private
*/
var cleanupevents = function cleanupevents() {
player.off('loadedmetadata', loadedmetadatahandler);
player.off('error', errorhandler);
player.off('dispose', cleanupevents);
};
/**
* cleanup before re-initializing the plugin
*
* @param {object} [newoptions] an object with plugin options
* @private
*/
var reinitplugin = function reinitplugin(newoptions) {
cleanupevents();
initplugin(player, newoptions);
};
player.on('error', errorhandler);
player.on('dispose', cleanupevents); // overwrite the plugin function so that we can correctly cleanup before
// initializing the plugin
player.reloadsourceonerror = reinitplugin;
};
/**
* reload the source when an error is detected as long as there
* wasn't an error previously within the last 30 seconds
*
* @param {object} [options] an object with plugin options
*/
var reloadsourceonerror = function reloadsourceonerror(options) {
initplugin(this, options);
};
var version$4 = "2.16.3";
var version$3 = "6.0.1";
var version$2 = "0.22.1";
var version$1 = "4.8.0";
var version = "3.1.3";
var vhs = {
playlistloader: playlistloader,
playlist: playlist,
utils: utils,
standard_playlist_selector: lastbandwidthselector,
initial_playlist_selector: lowestbitratecompatiblevariantselector,
lastbandwidthselector: lastbandwidthselector,
movingaveragebandwidthselector: movingaveragebandwidthselector,
compareplaylistbandwidth: compareplaylistbandwidth,
compareplaylistresolution: compareplaylistresolution,
xhr: xhrfactory()
}; // define getter/setters for config properties
object.keys(config).foreach(function (prop) {
object.defineproperty(vhs, prop, {
get: function get() {
videojs.log.warn("using vhs." + prop + " is unsafe be sure you know what you are doing");
return config[prop];
},
set: function set(value) {
videojs.log.warn("using vhs." + prop + " is unsafe be sure you know what you are doing");
if (typeof value !== 'number' || value < 0) {
videojs.log.warn("value of vhs." + prop + " must be greater than or equal to 0");
return;
}
config[prop] = value;
}
});
});
var local_storage_key = 'videojs-vhs';
/**
* updates the selectedindex of the qualitylevellist when a mediachange happens in vhs.
*
* @param {qualitylevellist} qualitylevels the qualitylevellist to update.
* @param {playlistloader} playlistloader playlistloader containing the new media info.
* @function handlevhsmediachange
*/
var handlevhsmediachange = function handlevhsmediachange(qualitylevels, playlistloader) {
var newplaylist = playlistloader.media();
var selectedindex = -1;
for (var i = 0; i < qualitylevels.length; i++) {
if (qualitylevels[i].id === newplaylist.id) {
selectedindex = i;
break;
}
}
qualitylevels.selectedindex_ = selectedindex;
qualitylevels.trigger({
selectedindex: selectedindex,
type: 'change'
});
};
/**
* adds quality levels to list once playlist metadata is available
*
* @param {qualitylevellist} qualitylevels the qualitylevellist to attach events to.
* @param {object} vhs vhs object to listen to for media events.
* @function handlevhsloadedmetadata
*/
var handlevhsloadedmetadata = function handlevhsloadedmetadata(qualitylevels, vhs) {
vhs.representations().foreach(function (rep) {
qualitylevels.addqualitylevel(rep);
});
handlevhsmediachange(qualitylevels, vhs.playlists);
}; // hls is a source handler, not a tech. make sure attempts to use it
// as one do not cause exceptions.
vhs.canplaysource = function () {
return videojs.log.warn('hls is no longer a tech. please remove it from ' + 'your player\'s techorder.');
};
var emekeysystems = function emekeysystems(keysystemoptions, mainplaylist, audioplaylist) {
if (!keysystemoptions) {
return keysystemoptions;
}
var codecs = {};
if (mainplaylist && mainplaylist.attributes && mainplaylist.attributes.codecs) {
codecs = unwrapcodeclist(object(_videojs_vhs_utils_es_codecs_js__webpack_imported_module_13__[/* parsecodecs */ "h"])(mainplaylist.attributes.codecs));
}
if (audioplaylist && audioplaylist.attributes && audioplaylist.attributes.codecs) {
codecs.audio = audioplaylist.attributes.codecs;
}
var videocontenttype = object(_videojs_vhs_utils_es_codecs_js__webpack_imported_module_13__[/* getmimeforcodec */ "e"])(codecs.video);
var audiocontenttype = object(_videojs_vhs_utils_es_codecs_js__webpack_imported_module_13__[/* getmimeforcodec */ "e"])(codecs.audio); // upsert the content types based on the selected playlist
var keysystemcontenttypes = {};
for (var keysystem in keysystemoptions) {
keysystemcontenttypes[keysystem] = {};
if (audiocontenttype) {
keysystemcontenttypes[keysystem].audiocontenttype = audiocontenttype;
}
if (videocontenttype) {
keysystemcontenttypes[keysystem].videocontenttype = videocontenttype;
} // default to using the video playlist's pssh even though they may be different, as
// videojs-contrib-eme will only accept one in the options.
//
// this shouldn't be an issue for most cases as early intialization will handle all
// unique pssh values, and if they aren't, then encrypted events should have the
// specific information needed for the unique license.
if (mainplaylist.contentprotection && mainplaylist.contentprotection[keysystem] && mainplaylist.contentprotection[keysystem].pssh) {
keysystemcontenttypes[keysystem].pssh = mainplaylist.contentprotection[keysystem].pssh;
} // videojs-contrib-eme accepts the option of specifying: 'com.some.cdm': 'url'
// so we need to prevent overwriting the url entirely
if (typeof keysystemoptions[keysystem] === 'string') {
keysystemcontenttypes[keysystem].url = keysystemoptions[keysystem];
}
}
return videojs.mergeoptions(keysystemoptions, keysystemcontenttypes);
};
/**
* @typedef {object} keysystems
*
* keysystems configuration for https://github.com/videojs/videojs-contrib-eme
* note: not all options are listed here.
*
* @property {uint8array} [pssh]
* protection system specific header
*/
/**
* goes through all the playlists and collects an array of keysystems options objects
* containing each playlist's keysystems and their pssh values, if available.
*
* @param {object[]} playlists
* the playlists to look through
* @param {string[]} keysystems
* the keysystems to collect pssh values for
*
* @return {keysystems[]}
* an array of keysystems objects containing available key systems and their
* pssh values
*/
var getallpsshkeysystemsoptions = function getallpsshkeysystemsoptions(playlists, keysystems) {
return playlists.reduce(function (keysystemsarr, playlist) {
if (!playlist.contentprotection) {
return keysystemsarr;
}
var keysystemsoptions = keysystems.reduce(function (keysystemsobj, keysystem) {
var keysystemoptions = playlist.contentprotection[keysystem];
if (keysystemoptions && keysystemoptions.pssh) {
keysystemsobj[keysystem] = {
pssh: keysystemoptions.pssh
};
}
return keysystemsobj;
}, {});
if (object.keys(keysystemsoptions).length) {
keysystemsarr.push(keysystemsoptions);
}
return keysystemsarr;
}, []);
};
/**
* returns a promise that waits for the
* [eme plugin](https://github.com/videojs/videojs-contrib-eme) to create a key session.
*
* works around https://bugs.chromium.org/p/chromium/issues/detail?id=895449 in non-ie11
* browsers.
*
* as per the above ticket, this is particularly important for chrome, where, if
* unencrypted content is appended before encrypted content and the key session has not
* been created, a media_err_decode will be thrown once the encrypted content is reached
* during playback.
*
* @param {object} player
* the player instance
* @param {object[]} sourcekeysystems
* the key systems options from the player source
* @param {object} [audiomedia]
* the active audio media playlist (optional)
* @param {object[]} mainplaylists
* the playlists found on the master playlist object
*
* @return {object}
* promise that resolves when the key session has been created
*/
var waitforkeysessioncreation = function waitforkeysessioncreation(_ref) {
var player = _ref.player,
sourcekeysystems = _ref.sourcekeysystems,
audiomedia = _ref.audiomedia,
mainplaylists = _ref.mainplaylists;
if (!player.eme.initializemediakeys) {
return promise.resolve();
} // todo should all audio pssh values be initialized for drm?
//
// all unique video rendition pssh values are initialized for drm, but here only
// the initial audio playlist license is initialized. in theory, an encrypted
// event should be fired if the user switches to an alternative audio playlist
// where a license is required, but this case hasn't yet been tested. in addition, there
// may be many alternate audio playlists unlikely to be used (e.g., multiple different
// languages).
var playlists = audiomedia ? mainplaylists.concat([audiomedia]) : mainplaylists;
var keysystemsoptionsarr = getallpsshkeysystemsoptions(playlists, object.keys(sourcekeysystems));
var initializationfinishedpromises = [];
var keysessioncreatedpromises = []; // since pssh values are interpreted as initdata, eme will dedupe any duplicates. the
// only place where it should not be deduped is for ms-prefixed apis, but the early
// return for ie11 above, and the existence of modern eme apis in addition to
// ms-prefixed apis on edge should prevent this from being a concern.
// initializemediakeys also won't use the webkit-prefixed apis.
keysystemsoptionsarr.foreach(function (keysystemsoptions) {
keysessioncreatedpromises.push(new promise(function (resolve, reject) {
player.tech_.one('keysessioncreated', resolve);
}));
initializationfinishedpromises.push(new promise(function (resolve, reject) {
player.eme.initializemediakeys({
keysystems: keysystemsoptions
}, function (err) {
if (err) {
reject(err);
return;
}
resolve();
});
}));
}); // the reasons promise.race is chosen over promise.any:
//
// * promise.any is only available in safari 14+.
// * none of these promises are expected to reject. if they do reject, it might be
// better here for the race to surface the rejection, rather than mask it by using
// promise.any.
return promise.race([// if a session was previously created, these will all finish resolving without
// creating a new session, otherwise it will take until the end of all license
// requests, which is why the key session check is used (to make setup much faster).
promise.all(initializationfinishedpromises), // once a single session is created, the browser knows drm will be used.
promise.race(keysessioncreatedpromises)]);
};
/**
* if the [eme](https://github.com/videojs/videojs-contrib-eme) plugin is available, and
* there are keysystems on the source, sets up source options to prepare the source for
* eme.
*
* @param {object} player
* the player instance
* @param {object[]} sourcekeysystems
* the key systems options from the player source
* @param {object} media
* the active media playlist
* @param {object} [audiomedia]
* the active audio media playlist (optional)
*
* @return {boolean}
* whether or not options were configured and eme is available
*/
var setupemeoptions = function setupemeoptions(_ref2) {
var player = _ref2.player,
sourcekeysystems = _ref2.sourcekeysystems,
media = _ref2.media,
audiomedia = _ref2.audiomedia;
var sourceoptions = emekeysystems(sourcekeysystems, media, audiomedia);
if (!sourceoptions) {
return false;
}
player.currentsource().keysystems = sourceoptions; // eme handles the rest of the setup, so if it is missing
// do nothing.
if (sourceoptions && !player.eme) {
videojs.log.warn('drm encrypted source cannot be decrypted without a drm plugin');
return false;
}
return true;
};
var getvhslocalstorage = function getvhslocalstorage() {
if (!global_window__webpack_imported_module_0___default.a.localstorage) {
return null;
}
var storedobject = global_window__webpack_imported_module_0___default.a.localstorage.getitem(local_storage_key);
if (!storedobject) {
return null;
}
try {
return json.parse(storedobject);
} catch (e) {
// someone may have tampered with the value
return null;
}
};
var updatevhslocalstorage = function updatevhslocalstorage(options) {
if (!global_window__webpack_imported_module_0___default.a.localstorage) {
return false;
}
var objecttostore = getvhslocalstorage();
objecttostore = objecttostore ? videojs.mergeoptions(objecttostore, options) : options;
try {
global_window__webpack_imported_module_0___default.a.localstorage.setitem(local_storage_key, json.stringify(objecttostore));
} catch (e) {
// throws if storage is full (e.g., always on ios 5+ safari private mode, where
// storage is set to 0).
// https://developer.mozilla.org/en-us/docs/web/api/storage/setitem#exceptions
// no need to perform any operation.
return false;
}
return objecttostore;
};
/**
* parses vhs-supported media types from data uris. see
* https://developer.mozilla.org/en-us/docs/web/http/basics_of_http/data_uris
* for information on data uris.
*
* @param {string} datauri
* the data uri
*
* @return {string|object}
* the parsed object/string, or the original string if no supported media type
* was found
*/
var expanddatauri = function expanddatauri(datauri) {
if (datauri.tolowercase().indexof('data:application/vnd.videojs.vhs+json,') === 0) {
return json.parse(datauri.substring(datauri.indexof(',') + 1));
} // no known case for this data uri, return the string as-is
return datauri;
};
/**
* whether the browser has built-in hls support.
*/
vhs.supportsnativehls = function () {
if (!global_document__webpack_imported_module_1___default.a || !global_document__webpack_imported_module_1___default.a.createelement) {
return false;
}
var video = global_document__webpack_imported_module_1___default.a.createelement('video'); // native hls is definitely not supported if html5 video isn't
if (!videojs.gettech('html5').issupported()) {
return false;
} // hls manifests can go by many mime-types
var canplay = [// apple santioned
'application/vnd.apple.mpegurl', // apple sanctioned for backwards compatibility
'audio/mpegurl', // very common
'audio/x-mpegurl', // very common
'application/x-mpegurl', // included for completeness
'video/x-mpegurl', 'video/mpegurl', 'application/mpegurl'];
return canplay.some(function (canitplay) {
return /maybe|probably/i.test(video.canplaytype(canitplay));
});
}();
vhs.supportsnativedash = function () {
if (!global_document__webpack_imported_module_1___default.a || !global_document__webpack_imported_module_1___default.a.createelement || !videojs.gettech('html5').issupported()) {
return false;
}
return /maybe|probably/i.test(global_document__webpack_imported_module_1___default.a.createelement('video').canplaytype('application/dash+xml'));
}();
vhs.supportstypenatively = function (type) {
if (type === 'hls') {
return vhs.supportsnativehls;
}
if (type === 'dash') {
return vhs.supportsnativedash;
}
return false;
};
/**
* hls is a source handler, not a tech. make sure attempts to use it
* as one do not cause exceptions.
*/
vhs.issupported = function () {
return videojs.log.warn('hls is no longer a tech. please remove it from ' + 'your player\'s techorder.');
};
var component = videojs.getcomponent('component');
/**
* the vhs handler object, where we orchestrate all of the parts
* of hls to interact with video.js
*
* @class vhshandler
* @extends videojs.component
* @param {object} source the soruce object
* @param {tech} tech the parent tech object
* @param {object} options optional and required options
*/
var vhshandler = /*#__pure__*/function (_component) {
_babel_runtime_helpers_inheritsloose__webpack_imported_module_5___default()(vhshandler, _component);
function vhshandler(source, tech, options) {
var _this;
_this = _component.call(this, tech, videojs.mergeoptions(options.hls, options.vhs)) || this;
if (options.hls && object.keys(options.hls).length) {
videojs.log.warn('using hls options is deprecated. please rename `hls` to `vhs` in your options object.');
} // if a tech level `initialbandwidth` option was passed
// use that over the vhs level `bandwidth` option
if (typeof options.initialbandwidth === 'number') {
_this.options_.bandwidth = options.initialbandwidth;
}
_this.logger_ = logger('vhshandler'); // tech.player() is deprecated but setup a reference to hls for
// backwards-compatibility
if (tech.options_ && tech.options_.playerid) {
var _player = videojs(tech.options_.playerid);
if (!_player.hasownproperty('hls')) {
object.defineproperty(_player, 'hls', {
get: function get() {
videojs.log.warn('player.hls is deprecated. use player.tech().vhs instead.');
tech.trigger({
type: 'usage',
name: 'hls-player-access'
});
return _babel_runtime_helpers_assertthisinitialized__webpack_imported_module_4___default()(_this);
},
configurable: true
});
}
if (!_player.hasownproperty('vhs')) {
object.defineproperty(_player, 'vhs', {
get: function get() {
videojs.log.warn('player.vhs is deprecated. use player.tech().vhs instead.');
tech.trigger({
type: 'usage',
name: 'vhs-player-access'
});
return _babel_runtime_helpers_assertthisinitialized__webpack_imported_module_4___default()(_this);
},
configurable: true
});
}
if (!_player.hasownproperty('dash')) {
object.defineproperty(_player, 'dash', {
get: function get() {
videojs.log.warn('player.dash is deprecated. use player.tech().vhs instead.');
return _babel_runtime_helpers_assertthisinitialized__webpack_imported_module_4___default()(_this);
},
configurable: true
});
}
_this.player_ = _player;
}
_this.tech_ = tech;
_this.source_ = source;
_this.stats = {};
_this.ignorenextseekingevent_ = false;
_this.setoptions_();
if (_this.options_.overridenative && tech.overridenativeaudiotracks && tech.overridenativevideotracks) {
tech.overridenativeaudiotracks(true);
tech.overridenativevideotracks(true);
} else if (_this.options_.overridenative && (tech.featuresnativevideotracks || tech.featuresnativeaudiotracks)) {
// overriding native hls only works if audio tracks have been emulated
// error early if we're misconfigured
throw new error('overriding native hls requires emulated tracks. ' + 'see https://git.io/vmpjb');
} // listen for fullscreenchange events for this player so that we
// can adjust our quality selection quickly
_this.on(global_document__webpack_imported_module_1___default.a, ['fullscreenchange', 'webkitfullscreenchange', 'mozfullscreenchange', 'msfullscreenchange'], function (event) {
var fullscreenelement = global_document__webpack_imported_module_1___default.a.fullscreenelement || global_document__webpack_imported_module_1___default.a.webkitfullscreenelement || global_document__webpack_imported_module_1___default.a.mozfullscreenelement || global_document__webpack_imported_module_1___default.a.msfullscreenelement;
if (fullscreenelement && fullscreenelement.contains(_this.tech_.el())) {
_this.masterplaylistcontroller_.fastqualitychange_();
} else {
// when leaving fullscreen, since the in page pixel dimensions should be smaller
// than full screen, see if there should be a rendition switch down to preserve
// bandwidth.
_this.masterplaylistcontroller_.checkabr_();
}
});
_this.on(_this.tech_, 'seeking', function () {
if (this.ignorenextseekingevent_) {
this.ignorenextseekingevent_ = false;
return;
}
this.setcurrenttime(this.tech_.currenttime());
});
_this.on(_this.tech_, 'error', function () {
// verify that the error was real and we are loaded
// enough to have mpc loaded.
if (this.tech_.error() && this.masterplaylistcontroller_) {
this.masterplaylistcontroller_.pauseloading();
}
});
_this.on(_this.tech_, 'play', _this.play);
return _this;
}
var _proto = vhshandler.prototype;
_proto.setoptions_ = function setoptions_() {
var _this2 = this; // defaults
this.options_.withcredentials = this.options_.withcredentials || false;
this.options_.handlemanifestredirects = this.options_.handlemanifestredirects === false ? false : true;
this.options_.limitrenditionbyplayerdimensions = this.options_.limitrenditionbyplayerdimensions === false ? false : true;
this.options_.usedevicepixelratio = this.options_.usedevicepixelratio || false;
this.options_.smoothqualitychange = this.options_.smoothqualitychange || false;
this.options_.usebandwidthfromlocalstorage = typeof this.source_.usebandwidthfromlocalstorage !== 'undefined' ? this.source_.usebandwidthfromlocalstorage : this.options_.usebandwidthfromlocalstorage || false;
this.options_.usenetworkinformationapi = this.options_.usenetworkinformationapi || false;
this.options_.usedtsfortimestampoffset = this.options_.usedtsfortimestampoffset || false;
this.options_.customtagparsers = this.options_.customtagparsers || [];
this.options_.customtagmappers = this.options_.customtagmappers || [];
this.options_.cacheencryptionkeys = this.options_.cacheencryptionkeys || false;
if (typeof this.options_.blacklistduration !== 'number') {
this.options_.blacklistduration = 5 * 60;
}
if (typeof this.options_.bandwidth !== 'number') {
if (this.options_.usebandwidthfromlocalstorage) {
var storedobject = getvhslocalstorage();
if (storedobject && storedobject.bandwidth) {
this.options_.bandwidth = storedobject.bandwidth;
this.tech_.trigger({
type: 'usage',
name: 'vhs-bandwidth-from-local-storage'
});
this.tech_.trigger({
type: 'usage',
name: 'hls-bandwidth-from-local-storage'
});
}
if (storedobject && storedobject.throughput) {
this.options_.throughput = storedobject.throughput;
this.tech_.trigger({
type: 'usage',
name: 'vhs-throughput-from-local-storage'
});
this.tech_.trigger({
type: 'usage',
name: 'hls-throughput-from-local-storage'
});
}
}
} // if bandwidth was not set by options or pulled from local storage, start playlist
// selection at a reasonable bandwidth
if (typeof this.options_.bandwidth !== 'number') {
this.options_.bandwidth = config.initial_bandwidth;
} // if the bandwidth number is unchanged from the initial setting
// then this takes precedence over the enablelowinitialplaylist option
this.options_.enablelowinitialplaylist = this.options_.enablelowinitialplaylist && this.options_.bandwidth === config.initial_bandwidth; // grab options passed to player.src
['withcredentials', 'usedevicepixelratio', 'limitrenditionbyplayerdimensions', 'bandwidth', 'smoothqualitychange', 'customtagparsers', 'customtagmappers', 'handlemanifestredirects', 'cacheencryptionkeys', 'playlistselector', 'initialplaylistselector', 'experimentalbufferbasedabr', 'liverangesafetimedelta', 'experimentalllhls', 'usenetworkinformationapi', 'usedtsfortimestampoffset', 'experimentalexactmanifesttimings', 'experimentalleastpixeldiffselector'].foreach(function (option) {
if (typeof _this2.source_[option] !== 'undefined') {
_this2.options_[option] = _this2.source_[option];
}
});
this.limitrenditionbyplayerdimensions = this.options_.limitrenditionbyplayerdimensions;
this.usedevicepixelratio = this.options_.usedevicepixelratio;
}
/**
* called when player.src gets called, handle a new source
*
* @param {object} src the source object to handle
*/
;
_proto.src = function src(_src, type) {
var _this3 = this; // do nothing if the src is falsey
if (!_src) {
return;
}
this.setoptions_(); // add master playlist controller options
this.options_.src = expanddatauri(this.source_.src);
this.options_.tech = this.tech_;
this.options_.externvhs = vhs;
this.options_.sourcetype = object(_videojs_vhs_utils_es_media_types_js__webpack_imported_module_14__[/* simpletypefromsourcetype */ "a"])(type); // whenever we seek internally, we should update the tech
this.options_.seekto = function (time) {
_this3.tech_.setcurrenttime(time);
};
if (this.options_.smoothqualitychange) {
videojs.log.warn('smoothqualitychange is deprecated and will be removed in the next major version');
}
this.masterplaylistcontroller_ = new masterplaylistcontroller(this.options_);
var playbackwatcheroptions = videojs.mergeoptions({
liverangesafetimedelta: safe_time_delta
}, this.options_, {
seekable: function seekable() {
return _this3.seekable();
},
media: function media() {
return _this3.masterplaylistcontroller_.media();
},
masterplaylistcontroller: this.masterplaylistcontroller_
});
this.playbackwatcher_ = new playbackwatcher(playbackwatcheroptions);
this.masterplaylistcontroller_.on('error', function () {
var player = videojs.players[_this3.tech_.options_.playerid];
var error = _this3.masterplaylistcontroller_.error;
if (typeof error === 'object' && !error.code) {
error.code = 3;
} else if (typeof error === 'string') {
error = {
message: error,
code: 3
};
}
player.error(error);
});
var defaultselector = this.options_.experimentalbufferbasedabr ? vhs.movingaveragebandwidthselector(0.55) : vhs.standard_playlist_selector; // `this` in selectplaylist should be the vhshandler for backwards
// compatibility with < v2
this.masterplaylistcontroller_.selectplaylist = this.selectplaylist ? this.selectplaylist.bind(this) : defaultselector.bind(this);
this.masterplaylistcontroller_.selectinitialplaylist = vhs.initial_playlist_selector.bind(this); // re-expose some internal objects for backwards compatibility with < v2
this.playlists = this.masterplaylistcontroller_.masterplaylistloader_;
this.mediasource = this.masterplaylistcontroller_.mediasource; // proxy assignment of some properties to the master playlist
// controller. using a custom property for backwards compatibility
// with < v2
object.defineproperties(this, {
selectplaylist: {
get: function get() {
return this.masterplaylistcontroller_.selectplaylist;
},
set: function set(selectplaylist) {
this.masterplaylistcontroller_.selectplaylist = selectplaylist.bind(this);
}
},
throughput: {
get: function get() {
return this.masterplaylistcontroller_.mainsegmentloader_.throughput.rate;
},
set: function set(throughput) {
this.masterplaylistcontroller_.mainsegmentloader_.throughput.rate = throughput; // by setting `count` to 1 the throughput value becomes the starting value
// for the cumulative average
this.masterplaylistcontroller_.mainsegmentloader_.throughput.count = 1;
}
},
bandwidth: {
get: function get() {
var playerbandwidthest = this.masterplaylistcontroller_.mainsegmentloader_.bandwidth;
var networkinformation = global_window__webpack_imported_module_0___default.a.navigator.connection || global_window__webpack_imported_module_0___default.a.navigator.mozconnection || global_window__webpack_imported_module_0___default.a.navigator.webkitconnection;
var tenmbpsasbitspersecond = 10e6;
if (this.options_.usenetworkinformationapi && networkinformation) {
// downlink returns mbps
// https://developer.mozilla.org/en-us/docs/web/api/networkinformation/downlink
var networkinfobandwidthestbitspersec = networkinformation.downlink * 1000 * 1000; // downlink maxes out at 10 mbps. in the event that both networkinformationapi and the player
// estimate a bandwidth greater than 10 mbps, use the larger of the two estimates to ensure that
// high quality streams are not filtered out.
if (networkinfobandwidthestbitspersec >= tenmbpsasbitspersecond && playerbandwidthest >= tenmbpsasbitspersecond) {
playerbandwidthest = math.max(playerbandwidthest, networkinfobandwidthestbitspersec);
} else {
playerbandwidthest = networkinfobandwidthestbitspersec;
}
}
return playerbandwidthest;
},
set: function set(bandwidth) {
this.masterplaylistcontroller_.mainsegmentloader_.bandwidth = bandwidth; // setting the bandwidth manually resets the throughput counter
// `count` is set to zero that current value of `rate` isn't included
// in the cumulative average
this.masterplaylistcontroller_.mainsegmentloader_.throughput = {
rate: 0,
count: 0
};
}
},
/**
* `systembandwidth` is a combination of two serial processes bit-rates. the first
* is the network bitrate provided by `bandwidth` and the second is the bitrate of
* the entire process after that - decryption, transmuxing, and appending - provided
* by `throughput`.
*
* since the two process are serial, the overall system bandwidth is given by:
* sysbandwidth = 1 / (1 / bandwidth + 1 / throughput)
*/
systembandwidth: {
get: function get() {
var invbandwidth = 1 / (this.bandwidth || 1);
var invthroughput;
if (this.throughput > 0) {
invthroughput = 1 / this.throughput;
} else {
invthroughput = 0;
}
var systembitrate = math.floor(1 / (invbandwidth + invthroughput));
return systembitrate;
},
set: function set() {
videojs.log.error('the "systembandwidth" property is read-only');
}
}
});
if (this.options_.bandwidth) {
this.bandwidth = this.options_.bandwidth;
}
if (this.options_.throughput) {
this.throughput = this.options_.throughput;
}
object.defineproperties(this.stats, {
bandwidth: {
get: function get() {
return _this3.bandwidth || 0;
},
enumerable: true
},
mediarequests: {
get: function get() {
return _this3.masterplaylistcontroller_.mediarequests_() || 0;
},
enumerable: true
},
mediarequestsaborted: {
get: function get() {
return _this3.masterplaylistcontroller_.mediarequestsaborted_() || 0;
},
enumerable: true
},
mediarequeststimedout: {
get: function get() {
return _this3.masterplaylistcontroller_.mediarequeststimedout_() || 0;
},
enumerable: true
},
mediarequestserrored: {
get: function get() {
return _this3.masterplaylistcontroller_.mediarequestserrored_() || 0;
},
enumerable: true
},
mediatransferduration: {
get: function get() {
return _this3.masterplaylistcontroller_.mediatransferduration_() || 0;
},
enumerable: true
},
mediabytestransferred: {
get: function get() {
return _this3.masterplaylistcontroller_.mediabytestransferred_() || 0;
},
enumerable: true
},
mediasecondsloaded: {
get: function get() {
return _this3.masterplaylistcontroller_.mediasecondsloaded_() || 0;
},
enumerable: true
},
mediaappends: {
get: function get() {
return _this3.masterplaylistcontroller_.mediaappends_() || 0;
},
enumerable: true
},
mainappendstoloadeddata: {
get: function get() {
return _this3.masterplaylistcontroller_.mainappendstoloadeddata_() || 0;
},
enumerable: true
},
audioappendstoloadeddata: {
get: function get() {
return _this3.masterplaylistcontroller_.audioappendstoloadeddata_() || 0;
},
enumerable: true
},
appendstoloadeddata: {
get: function get() {
return _this3.masterplaylistcontroller_.appendstoloadeddata_() || 0;
},
enumerable: true
},
timetoloadeddata: {
get: function get() {
return _this3.masterplaylistcontroller_.timetoloadeddata_() || 0;
},
enumerable: true
},
buffered: {
get: function get() {
return timerangestoarray(_this3.tech_.buffered());
},
enumerable: true
},
currenttime: {
get: function get() {
return _this3.tech_.currenttime();
},
enumerable: true
},
currentsource: {
get: function get() {
return _this3.tech_.currentsource_;
},
enumerable: true
},
currenttech: {
get: function get() {
return _this3.tech_.name_;
},
enumerable: true
},
duration: {
get: function get() {
return _this3.tech_.duration();
},
enumerable: true
},
master: {
get: function get() {
return _this3.playlists.master;
},
enumerable: true
},
playerdimensions: {
get: function get() {
return _this3.tech_.currentdimensions();
},
enumerable: true
},
seekable: {
get: function get() {
return timerangestoarray(_this3.tech_.seekable());
},
enumerable: true
},
timestamp: {
get: function get() {
return date.now();
},
enumerable: true
},
videoplaybackquality: {
get: function get() {
return _this3.tech_.getvideoplaybackquality();
},
enumerable: true
}
});
this.tech_.one('canplay', this.masterplaylistcontroller_.setupfirstplay.bind(this.masterplaylistcontroller_));
this.tech_.on('bandwidthupdate', function () {
if (_this3.options_.usebandwidthfromlocalstorage) {
updatevhslocalstorage({
bandwidth: _this3.bandwidth,
throughput: math.round(_this3.throughput)
});
}
});
this.masterplaylistcontroller_.on('selectedinitialmedia', function () {
// add the manual rendition mix-in to vhshandler
renditionselectionmixin(_this3);
});
this.masterplaylistcontroller_.sourceupdater_.on('createdsourcebuffers', function () {
_this3.setupeme_();
}); // the bandwidth of the primary segment loader is our best
// estimate of overall bandwidth
this.on(this.masterplaylistcontroller_, 'progress', function () {
this.tech_.trigger('progress');
}); // in the live case, we need to ignore the very first `seeking` event since
// that will be the result of the seek-to-live behavior
this.on(this.masterplaylistcontroller_, 'firstplay', function () {
this.ignorenextseekingevent_ = true;
});
this.setupqualitylevels_(); // do nothing if the tech has been disposed already
// this can occur if someone sets the src in player.ready(), for instance
if (!this.tech_.el()) {
return;
}
this.mediasourceurl_ = global_window__webpack_imported_module_0___default.a.url.createobjecturl(this.masterplaylistcontroller_.mediasource);
this.tech_.src(this.mediasourceurl_);
};
_proto.createkeysessions_ = function createkeysessions_() {
var _this4 = this;
var audioplaylistloader = this.masterplaylistcontroller_.mediatypes_.audio.activeplaylistloader;
this.logger_('waiting for eme key session creation');
waitforkeysessioncreation({
player: this.player_,
sourcekeysystems: this.source_.keysystems,
audiomedia: audioplaylistloader && audioplaylistloader.media(),
mainplaylists: this.playlists.master.playlists
}).then(function () {
_this4.logger_('created eme key session');
_this4.masterplaylistcontroller_.sourceupdater_.initializedeme();
})["catch"](function (err) {
_this4.logger_('error while creating eme key session', err);
_this4.player_.error({
message: 'failed to initialize media keys for eme',
code: 3
});
});
};
_proto.handlewaitingforkey_ = function handlewaitingforkey_() {
// if waitingforkey is fired, it's possible that the data that's necessary to retrieve
// the key is in the manifest. while this should've happened on initial source load, it
// may happen again in live streams where the keys change, and the manifest info
// reflects the update.
//
// because videojs-contrib-eme compares the pssh data we send to that of pssh data it's
// already requested keys for, we don't have to worry about this generating extraneous
// requests.
this.logger_('waitingforkey fired, attempting to create any new key sessions');
this.createkeysessions_();
}
/**
* if necessary and eme is available, sets up eme options and waits for key session
* creation.
*
* this function also updates the source updater so taht it can be used, as for some
* browsers, eme must be configured before content is appended (if appending unencrypted
* content before encrypted content).
*/
;
_proto.setupeme_ = function setupeme_() {
var _this5 = this;
var audioplaylistloader = this.masterplaylistcontroller_.mediatypes_.audio.activeplaylistloader;
var didsetupemeoptions = setupemeoptions({
player: this.player_,
sourcekeysystems: this.source_.keysystems,
media: this.playlists.media(),
audiomedia: audioplaylistloader && audioplaylistloader.media()
});
this.player_.tech_.on('keystatuschange', function (e) {
if (e.status !== 'output-restricted') {
return;
}
var masterplaylist = _this5.masterplaylistcontroller_.master();
if (!masterplaylist || !masterplaylist.playlists) {
return;
}
var excludedhdplaylists = []; // assume all hd streams are unplayable and exclude them from abr selection
masterplaylist.playlists.foreach(function (playlist) {
if (playlist && playlist.attributes && playlist.attributes.resolution && playlist.attributes.resolution.height >= 720) {
if (!playlist.excludeuntil || playlist.excludeuntil < infinity) {
playlist.excludeuntil = infinity;
excludedhdplaylists.push(playlist);
}
}
});
if (excludedhdplaylists.length) {
var _videojs$log;
(_videojs$log = videojs.log).warn.apply(_videojs$log, ['drm keystatus changed to "output-restricted." removing the following hd playlists ' + 'that will most likely fail to play and clearing the buffer. ' + 'this may be due to hdcp restrictions on the stream and the capabilities of the current device.'].concat(excludedhdplaylists)); // clear the buffer before switching playlists, since it may already contain unplayable segments
_this5.masterplaylistcontroller_.fastqualitychange_();
}
});
this.handlewaitingforkey_ = this.handlewaitingforkey_.bind(this);
this.player_.tech_.on('waitingforkey', this.handlewaitingforkey_); // in ie11 this is too early to initialize media keys, and ie11 does not support
// promises.
if (videojs.browser.ie_version === 11 || !didsetupemeoptions) {
// if eme options were not set up, we've done all we could to initialize eme.
this.masterplaylistcontroller_.sourceupdater_.initializedeme();
return;
}
this.createkeysessions_();
}
/**
* initializes the quality levels and sets listeners to update them.
*
* @method setupqualitylevels_
* @private
*/
;
_proto.setupqualitylevels_ = function setupqualitylevels_() {
var _this6 = this;
var player = videojs.players[this.tech_.options_.playerid]; // if there isn't a player or there isn't a qualitylevels plugin
// or qualitylevels_ listeners have already been setup, do nothing.
if (!player || !player.qualitylevels || this.qualitylevels_) {
return;
}
this.qualitylevels_ = player.qualitylevels();
this.masterplaylistcontroller_.on('selectedinitialmedia', function () {
handlevhsloadedmetadata(_this6.qualitylevels_, _this6);
});
this.playlists.on('mediachange', function () {
handlevhsmediachange(_this6.qualitylevels_, _this6.playlists);
});
}
/**
* return the version
*/
;
vhshandler.version = function version$5() {
return {
'@videojs/http-streaming': version$4,
'mux.js': version$3,
'mpd-parser': version$2,
'm3u8-parser': version$1,
'aes-decrypter': version
};
}
/**
* return the version
*/
;
_proto.version = function version() {
return this.constructor.version();
};
_proto.canchangetype = function canchangetype() {
return sourceupdater.canchangetype();
}
/**
* begin playing the video.
*/
;
_proto.play = function play() {
this.masterplaylistcontroller_.play();
}
/**
* a wrapper around the function in masterplaylistcontroller
*/
;
_proto.setcurrenttime = function setcurrenttime(currenttime) {
this.masterplaylistcontroller_.setcurrenttime(currenttime);
}
/**
* a wrapper around the function in masterplaylistcontroller
*/
;
_proto.duration = function duration() {
return this.masterplaylistcontroller_.duration();
}
/**
* a wrapper around the function in masterplaylistcontroller
*/
;
_proto.seekable = function seekable() {
return this.masterplaylistcontroller_.seekable();
}
/**
* abort all outstanding work and cleanup.
*/
;
_proto.dispose = function dispose() {
if (this.playbackwatcher_) {
this.playbackwatcher_.dispose();
}
if (this.masterplaylistcontroller_) {
this.masterplaylistcontroller_.dispose();
}
if (this.qualitylevels_) {
this.qualitylevels_.dispose();
}
if (this.player_) {
delete this.player_.vhs;
delete this.player_.dash;
delete this.player_.hls;
}
if (this.tech_ && this.tech_.vhs) {
delete this.tech_.vhs;
} // don't check this.tech_.hls as it will log a deprecated warning
if (this.tech_) {
delete this.tech_.hls;
}
if (this.mediasourceurl_ && global_window__webpack_imported_module_0___default.a.url.revokeobjecturl) {
global_window__webpack_imported_module_0___default.a.url.revokeobjecturl(this.mediasourceurl_);
this.mediasourceurl_ = null;
}
if (this.tech_) {
this.tech_.off('waitingforkey', this.handlewaitingforkey_);
}
_component.prototype.dispose.call(this);
};
_proto.converttoprogramtime = function converttoprogramtime(time, callback) {
return getprogramtime({
playlist: this.masterplaylistcontroller_.media(),
time: time,
callback: callback
});
} // the player must be playing before calling this
;
_proto.seektoprogramtime = function seektoprogramtime$1(programtime, callback, pauseafterseek, retrycount) {
if (pauseafterseek === void 0) {
pauseafterseek = true;
}
if (retrycount === void 0) {
retrycount = 2;
}
return seektoprogramtime({
programtime: programtime,
playlist: this.masterplaylistcontroller_.media(),
retrycount: retrycount,
pauseafterseek: pauseafterseek,
seekto: this.options_.seekto,
tech: this.options_.tech,
callback: callback
});
};
return vhshandler;
}(component);
/**
* the source handler object, which informs video.js what additional
* mime types are supported and sets up playback. it is registered
* automatically to the appropriate tech based on the capabilities of
* the browser it is running in. it is not necessary to use or modify
* this object in normal usage.
*/
var vhssourcehandler = {
name: 'videojs-http-streaming',
version: version$4,
canhandlesource: function canhandlesource(srcobj, options) {
if (options === void 0) {
options = {};
}
var localoptions = videojs.mergeoptions(videojs.options, options);
return vhssourcehandler.canplaytype(srcobj.type, localoptions);
},
handlesource: function handlesource(source, tech, options) {
if (options === void 0) {
options = {};
}
var localoptions = videojs.mergeoptions(videojs.options, options);
tech.vhs = new vhshandler(source, tech, localoptions);
if (!videojs.hasownproperty('hls')) {
object.defineproperty(tech, 'hls', {
get: function get() {
videojs.log.warn('player.tech().hls is deprecated. use player.tech().vhs instead.');
return tech.vhs;
},
configurable: true
});
}
tech.vhs.xhr = xhrfactory();
tech.vhs.src(source.src, source.type);
return tech.vhs;
},
canplaytype: function canplaytype(type, options) {
var simpletype = object(_videojs_vhs_utils_es_media_types_js__webpack_imported_module_14__[/* simpletypefromsourcetype */ "a"])(type);
if (!simpletype) {
return '';
}
var overridenative = vhssourcehandler.getoverridenative(options);
var supportstypenatively = vhs.supportstypenatively(simpletype);
var canusemseplayback = !supportstypenatively || overridenative;
return canusemseplayback ? 'maybe' : '';
},
getoverridenative: function getoverridenative(options) {
if (options === void 0) {
options = {};
}
var _options = options,
_options$vhs = _options.vhs,
vhs = _options$vhs === void 0 ? {} : _options$vhs,
_options$hls = _options.hls,
hls = _options$hls === void 0 ? {} : _options$hls;
var defaultoverridenative = !(videojs.browser.is_any_safari || videojs.browser.is_ios);
var _vhs$overridenative = vhs.overridenative,
overridenative = _vhs$overridenative === void 0 ? defaultoverridenative : _vhs$overridenative;
var _hls$overridenative = hls.overridenative,
legacyoverridenative = _hls$overridenative === void 0 ? false : _hls$overridenative;
return legacyoverridenative || overridenative;
}
};
/**
* check to see if the native mediasource object exists and supports
* an mp4 container with both h.264 video and aac-lc audio.
*
* @return {boolean} if native media sources are supported
*/
var supportsnativemediasources = function supportsnativemediasources() {
return object(_videojs_vhs_utils_es_codecs_js__webpack_imported_module_13__[/* browsersupportscodec */ "c"])('avc1.4d400d,mp4a.40.2');
}; // register source handlers with the appropriate techs
if (supportsnativemediasources()) {
videojs.gettech('html5').registersourcehandler(vhssourcehandler, 0);
}
videojs.vhshandler = vhshandler;
object.defineproperty(videojs, 'hlshandler', {
get: function get() {
videojs.log.warn('videojs.hlshandler is deprecated. use videojs.vhshandler instead.');
return vhshandler;
},
configurable: true
});
videojs.vhssourcehandler = vhssourcehandler;
object.defineproperty(videojs, 'hlssourcehandler', {
get: function get() {
videojs.log.warn('videojs.hlssourcehandler is deprecated. ' + 'use videojs.vhssourcehandler instead.');
return vhssourcehandler;
},
configurable: true
});
videojs.vhs = vhs;
object.defineproperty(videojs, 'hls', {
get: function get() {
videojs.log.warn('videojs.hls is deprecated. use videojs.vhs instead.');
return vhs;
},
configurable: true
});
if (!videojs.use) {
videojs.registercomponent('hls', vhs);
videojs.registercomponent('vhs', vhs);
}
videojs.options.vhs = videojs.options.vhs || {};
videojs.options.hls = videojs.options.hls || {};
if (!videojs.getplugin || !videojs.getplugin('reloadsourceonerror')) {
var registerplugin = videojs.registerplugin || videojs.plugin;
registerplugin('reloadsourceonerror', reloadsourceonerror);
}
/* harmony default export */ __webpack_exports__["a"] = (videojs);
/* webpack var injection */}.call(this, __webpack_require__(18)))
/***/ })
}]);