dashjs
Version:
A reference client implementation for the playback of MPEG DASH via Javascript and compliant browsers.
1,422 lines (1,173 loc) • 1.29 MB
JavaScript
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else if(typeof exports === 'object')
exports["dashjs"] = factory();
else
root["dashjs"] = factory();
})(self, function() {
return /******/ (function() { // webpackBootstrap
/******/ var __webpack_modules__ = ({
/***/ "./externals/xml2json.js":
/*!*******************************!*\
!*** ./externals/xml2json.js ***!
\*******************************/
/***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/*
Copyright 2011-2013 Abdulla Abdurakhmanov
Original sources are available at https://code.google.com/p/x2js/
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
Further modified for dashjs to:
- keep track of children nodes in order in attribute __children.
- add type conversion matchers
- re-add ignoreRoot
- allow zero-length attributePrefix
- don't add white-space text nodes
- remove explicit RequireJS support
*/
function X2JS(config) {
'use strict';
var VERSION = "1.2.0";
config = config || {};
initConfigDefaults();
initRequiredPolyfills();
function initConfigDefaults() {
if (config.escapeMode === undefined) {
config.escapeMode = true;
}
if (config.attributePrefix === undefined) {
config.attributePrefix = "_";
}
config.arrayAccessForm = config.arrayAccessForm || "none";
config.emptyNodeForm = config.emptyNodeForm || "text";
if (config.enableToStringFunc === undefined) {
config.enableToStringFunc = true;
}
config.arrayAccessFormPaths = config.arrayAccessFormPaths || [];
if (config.skipEmptyTextNodesForObj === undefined) {
config.skipEmptyTextNodesForObj = true;
}
if (config.stripWhitespaces === undefined) {
config.stripWhitespaces = true;
}
config.datetimeAccessFormPaths = config.datetimeAccessFormPaths || [];
if (config.useDoubleQuotes === undefined) {
config.useDoubleQuotes = false;
}
config.xmlElementsFilter = config.xmlElementsFilter || [];
config.jsonPropertiesFilter = config.jsonPropertiesFilter || [];
if (config.keepCData === undefined) {
config.keepCData = false;
}
if (config.ignoreRoot === undefined) {
config.ignoreRoot = false;
}
}
var DOMNodeTypes = {
ELEMENT_NODE: 1,
TEXT_NODE: 3,
CDATA_SECTION_NODE: 4,
COMMENT_NODE: 8,
DOCUMENT_NODE: 9
};
function initRequiredPolyfills() {}
function getNodeLocalName(node) {
var nodeLocalName = node.localName;
if (nodeLocalName == null) // Yeah, this is IE!!
nodeLocalName = node.baseName;
if (nodeLocalName == null || nodeLocalName == "") // =="" is IE too
nodeLocalName = node.nodeName;
return nodeLocalName;
}
function getNodePrefix(node) {
return node.prefix;
}
function escapeXmlChars(str) {
if (typeof str == "string") return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, ''');else return str;
}
function unescapeXmlChars(str) {
return str.replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, "'").replace(/&/g, '&');
}
function checkInStdFiltersArrayForm(stdFiltersArrayForm, obj, name, path) {
var idx = 0;
for (; idx < stdFiltersArrayForm.length; idx++) {
var filterPath = stdFiltersArrayForm[idx];
if (typeof filterPath === "string") {
if (filterPath == path) break;
} else if (filterPath instanceof RegExp) {
if (filterPath.test(path)) break;
} else if (typeof filterPath === "function") {
if (filterPath(obj, name, path)) break;
}
}
return idx != stdFiltersArrayForm.length;
}
function toArrayAccessForm(obj, childName, path) {
switch (config.arrayAccessForm) {
case "property":
if (!(obj[childName] instanceof Array)) obj[childName + "_asArray"] = [obj[childName]];else obj[childName + "_asArray"] = obj[childName];
break;
/*case "none":
break;*/
}
if (!(obj[childName] instanceof Array) && config.arrayAccessFormPaths.length > 0) {
if (checkInStdFiltersArrayForm(config.arrayAccessFormPaths, obj, childName, path)) {
obj[childName] = [obj[childName]];
}
}
}
function fromXmlDateTime(prop) {
// Implementation based up on http://stackoverflow.com/questions/8178598/xml-datetime-to-javascript-date-object
// Improved to support full spec and optional parts
var bits = prop.split(/[-T:+Z]/g);
var d = new Date(bits[0], bits[1] - 1, bits[2]);
var secondBits = bits[5].split("\.");
d.setHours(bits[3], bits[4], secondBits[0]);
if (secondBits.length > 1) d.setMilliseconds(secondBits[1]); // Get supplied time zone offset in minutes
if (bits[6] && bits[7]) {
var offsetMinutes = bits[6] * 60 + Number(bits[7]);
var sign = /\d\d-\d\d:\d\d$/.test(prop) ? '-' : '+'; // Apply the sign
offsetMinutes = 0 + (sign == '-' ? -1 * offsetMinutes : offsetMinutes); // Apply offset and local timezone
d.setMinutes(d.getMinutes() - offsetMinutes - d.getTimezoneOffset());
} else if (prop.indexOf("Z", prop.length - 1) !== -1) {
d = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours(), d.getMinutes(), d.getSeconds(), d.getMilliseconds()));
} // d is now a local time equivalent to the supplied time
return d;
}
function checkFromXmlDateTimePaths(value, childName, fullPath) {
if (config.datetimeAccessFormPaths.length > 0) {
var path = fullPath.split("\.#")[0];
if (checkInStdFiltersArrayForm(config.datetimeAccessFormPaths, value, childName, path)) {
return fromXmlDateTime(value);
} else return value;
} else return value;
}
function checkXmlElementsFilter(obj, childType, childName, childPath) {
if (childType == DOMNodeTypes.ELEMENT_NODE && config.xmlElementsFilter.length > 0) {
return checkInStdFiltersArrayForm(config.xmlElementsFilter, obj, childName, childPath);
} else return true;
}
function parseDOMChildren(node, path) {
if (node.nodeType == DOMNodeTypes.DOCUMENT_NODE) {
var result = new Object();
var nodeChildren = node.childNodes; // Alternative for firstElementChild which is not supported in some environments
for (var cidx = 0; cidx < nodeChildren.length; cidx++) {
var child = nodeChildren[cidx];
if (child.nodeType == DOMNodeTypes.ELEMENT_NODE) {
if (config.ignoreRoot) {
result = parseDOMChildren(child);
} else {
result = {};
var childName = getNodeLocalName(child);
result[childName] = parseDOMChildren(child);
}
}
}
return result;
} else if (node.nodeType == DOMNodeTypes.ELEMENT_NODE) {
var result = new Object();
result.__cnt = 0;
var children = [];
var nodeChildren = node.childNodes; // Children nodes
for (var cidx = 0; cidx < nodeChildren.length; cidx++) {
var child = nodeChildren[cidx];
var childName = getNodeLocalName(child);
if (child.nodeType != DOMNodeTypes.COMMENT_NODE) {
var childPath = path + "." + childName;
if (checkXmlElementsFilter(result, child.nodeType, childName, childPath)) {
result.__cnt++;
if (result[childName] == null) {
var c = parseDOMChildren(child, childPath);
if (childName != "#text" || /[^\s]/.test(c)) {
var o = {};
o[childName] = c;
children.push(o);
}
result[childName] = c;
toArrayAccessForm(result, childName, childPath);
} else {
if (result[childName] != null) {
if (!(result[childName] instanceof Array)) {
result[childName] = [result[childName]];
toArrayAccessForm(result, childName, childPath);
}
}
var c = parseDOMChildren(child, childPath);
if (childName != "#text" || /[^\s]/.test(c)) {
// Don't add white-space text nodes
var o = {};
o[childName] = c;
children.push(o);
}
result[childName][result[childName].length] = c;
}
}
}
}
result.__children = children; // Attributes
var nodeLocalName = getNodeLocalName(node);
for (var aidx = 0; aidx < node.attributes.length; aidx++) {
var attr = node.attributes[aidx];
result.__cnt++;
var value2 = attr.value;
for (var m = 0, ml = config.matchers.length; m < ml; m++) {
var matchobj = config.matchers[m];
if (matchobj.test(attr, nodeLocalName)) value2 = matchobj.converter(attr.value);
}
result[config.attributePrefix + attr.name] = value2;
} // Node namespace prefix
var nodePrefix = getNodePrefix(node);
if (nodePrefix != null && nodePrefix != "") {
result.__cnt++;
result.__prefix = nodePrefix;
}
if (result["#text"] != null) {
result.__text = result["#text"];
if (result.__text instanceof Array) {
result.__text = result.__text.join("\n");
} //if(config.escapeMode)
// result.__text = unescapeXmlChars(result.__text);
if (config.stripWhitespaces) result.__text = result.__text.trim();
delete result["#text"];
if (config.arrayAccessForm == "property") delete result["#text_asArray"];
result.__text = checkFromXmlDateTimePaths(result.__text, childName, path + "." + childName);
}
if (result["#cdata-section"] != null) {
result.__cdata = result["#cdata-section"];
delete result["#cdata-section"];
if (config.arrayAccessForm == "property") delete result["#cdata-section_asArray"];
}
if (result.__cnt == 0 && config.emptyNodeForm == "text") {
result = '';
} else if (result.__cnt == 1 && result.__text != null) {
result = result.__text;
} else if (result.__cnt == 1 && result.__cdata != null && !config.keepCData) {
result = result.__cdata;
} else if (result.__cnt > 1 && result.__text != null && config.skipEmptyTextNodesForObj) {
if (config.stripWhitespaces && result.__text == "" || result.__text.trim() == "") {
delete result.__text;
}
}
delete result.__cnt;
if (config.enableToStringFunc && (result.__text != null || result.__cdata != null)) {
result.toString = function () {
return (this.__text != null ? this.__text : '') + (this.__cdata != null ? this.__cdata : '');
};
}
return result;
} else if (node.nodeType == DOMNodeTypes.TEXT_NODE || node.nodeType == DOMNodeTypes.CDATA_SECTION_NODE) {
return node.nodeValue;
}
}
function startTag(jsonObj, element, attrList, closed) {
var resultStr = "<" + (jsonObj != null && jsonObj.__prefix != null ? jsonObj.__prefix + ":" : "") + element;
if (attrList != null) {
for (var aidx = 0; aidx < attrList.length; aidx++) {
var attrName = attrList[aidx];
var attrVal = jsonObj[attrName];
if (config.escapeMode) attrVal = escapeXmlChars(attrVal);
resultStr += " " + attrName.substr(config.attributePrefix.length) + "=";
if (config.useDoubleQuotes) resultStr += '"' + attrVal + '"';else resultStr += "'" + attrVal + "'";
}
}
if (!closed) resultStr += ">";else resultStr += "/>";
return resultStr;
}
function endTag(jsonObj, elementName) {
return "</" + (jsonObj.__prefix != null ? jsonObj.__prefix + ":" : "") + elementName + ">";
}
function endsWith(str, suffix) {
return str.indexOf(suffix, str.length - suffix.length) !== -1;
}
function jsonXmlSpecialElem(jsonObj, jsonObjField) {
if (config.arrayAccessForm == "property" && endsWith(jsonObjField.toString(), "_asArray") || jsonObjField.toString().indexOf(config.attributePrefix) == 0 || jsonObjField.toString().indexOf("__") == 0 || jsonObj[jsonObjField] instanceof Function) return true;else return false;
}
function jsonXmlElemCount(jsonObj) {
var elementsCnt = 0;
if (jsonObj instanceof Object) {
for (var it in jsonObj) {
if (jsonXmlSpecialElem(jsonObj, it)) continue;
elementsCnt++;
}
}
return elementsCnt;
}
function checkJsonObjPropertiesFilter(jsonObj, propertyName, jsonObjPath) {
return config.jsonPropertiesFilter.length == 0 || jsonObjPath == "" || checkInStdFiltersArrayForm(config.jsonPropertiesFilter, jsonObj, propertyName, jsonObjPath);
}
function parseJSONAttributes(jsonObj) {
var attrList = [];
if (jsonObj instanceof Object) {
for (var ait in jsonObj) {
if (ait.toString().indexOf("__") == -1 && ait.toString().indexOf(config.attributePrefix) == 0) {
attrList.push(ait);
}
}
}
return attrList;
}
function parseJSONTextAttrs(jsonTxtObj) {
var result = "";
if (jsonTxtObj.__cdata != null) {
result += "<![CDATA[" + jsonTxtObj.__cdata + "]]>";
}
if (jsonTxtObj.__text != null) {
if (config.escapeMode) result += escapeXmlChars(jsonTxtObj.__text);else result += jsonTxtObj.__text;
}
return result;
}
function parseJSONTextObject(jsonTxtObj) {
var result = "";
if (jsonTxtObj instanceof Object) {
result += parseJSONTextAttrs(jsonTxtObj);
} else if (jsonTxtObj != null) {
if (config.escapeMode) result += escapeXmlChars(jsonTxtObj);else result += jsonTxtObj;
}
return result;
}
function getJsonPropertyPath(jsonObjPath, jsonPropName) {
if (jsonObjPath === "") {
return jsonPropName;
} else return jsonObjPath + "." + jsonPropName;
}
function parseJSONArray(jsonArrRoot, jsonArrObj, attrList, jsonObjPath) {
var result = "";
if (jsonArrRoot.length == 0) {
result += startTag(jsonArrRoot, jsonArrObj, attrList, true);
} else {
for (var arIdx = 0; arIdx < jsonArrRoot.length; arIdx++) {
result += startTag(jsonArrRoot[arIdx], jsonArrObj, parseJSONAttributes(jsonArrRoot[arIdx]), false);
result += parseJSONObject(jsonArrRoot[arIdx], getJsonPropertyPath(jsonObjPath, jsonArrObj));
result += endTag(jsonArrRoot[arIdx], jsonArrObj);
}
}
return result;
}
function parseJSONObject(jsonObj, jsonObjPath) {
var result = "";
var elementsCnt = jsonXmlElemCount(jsonObj);
if (elementsCnt > 0) {
for (var it in jsonObj) {
if (jsonXmlSpecialElem(jsonObj, it) || jsonObjPath != "" && !checkJsonObjPropertiesFilter(jsonObj, it, getJsonPropertyPath(jsonObjPath, it))) continue;
var subObj = jsonObj[it];
var attrList = parseJSONAttributes(subObj);
if (subObj == null || subObj == undefined) {
result += startTag(subObj, it, attrList, true);
} else if (subObj instanceof Object) {
if (subObj instanceof Array) {
result += parseJSONArray(subObj, it, attrList, jsonObjPath);
} else if (subObj instanceof Date) {
result += startTag(subObj, it, attrList, false);
result += subObj.toISOString();
result += endTag(subObj, it);
} else {
var subObjElementsCnt = jsonXmlElemCount(subObj);
if (subObjElementsCnt > 0 || subObj.__text != null || subObj.__cdata != null) {
result += startTag(subObj, it, attrList, false);
result += parseJSONObject(subObj, getJsonPropertyPath(jsonObjPath, it));
result += endTag(subObj, it);
} else {
result += startTag(subObj, it, attrList, true);
}
}
} else {
result += startTag(subObj, it, attrList, false);
result += parseJSONTextObject(subObj);
result += endTag(subObj, it);
}
}
}
result += parseJSONTextObject(jsonObj);
return result;
}
this.parseXmlString = function (xmlDocStr) {
var isIEParser = window.ActiveXObject || "ActiveXObject" in window;
if (xmlDocStr === undefined) {
return null;
}
var xmlDoc;
if (window.DOMParser) {
var parser = new window.DOMParser();
var parsererrorNS = null;
try {
xmlDoc = parser.parseFromString(xmlDocStr, "text/xml");
if (xmlDoc.getElementsByTagNameNS("*", "parsererror").length > 0) {
xmlDoc = null;
}
} catch (err) {
xmlDoc = null;
}
} else {
// IE :(
if (xmlDocStr.indexOf("<?") == 0) {
xmlDocStr = xmlDocStr.substr(xmlDocStr.indexOf("?>") + 2);
}
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = "false";
xmlDoc.loadXML(xmlDocStr);
}
return xmlDoc;
};
this.asArray = function (prop) {
if (prop === undefined || prop == null) return [];else if (prop instanceof Array) return prop;else return [prop];
};
this.toXmlDateTime = function (dt) {
if (dt instanceof Date) return dt.toISOString();else if (typeof dt === 'number') return new Date(dt).toISOString();else return null;
};
this.asDateTime = function (prop) {
if (typeof prop == "string") {
return fromXmlDateTime(prop);
} else return prop;
};
this.xml2json = function (xmlDoc) {
return parseDOMChildren(xmlDoc);
};
this.xml_str2json = function (xmlDocStr) {
var xmlDoc = this.parseXmlString(xmlDocStr);
if (xmlDoc != null) return this.xml2json(xmlDoc);else return null;
};
this.json2xml_str = function (jsonObj) {
return parseJSONObject(jsonObj, "");
};
this.json2xml = function (jsonObj) {
var xmlDocStr = this.json2xml_str(jsonObj);
return this.parseXmlString(xmlDocStr);
};
this.getVersion = function () {
return VERSION;
};
}
/* harmony default export */ __webpack_exports__["default"] = (X2JS);
/***/ }),
/***/ "./src/core/Debug.js":
/*!***************************!*\
!*** ./src/core/Debug.js ***!
\***************************/
/***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _EventBus__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./EventBus */ "./src/core/EventBus.js");
/* harmony import */ var _events_Events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./events/Events */ "./src/core/events/Events.js");
/* harmony import */ var _FactoryMaker__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./FactoryMaker */ "./src/core/FactoryMaker.js");
/**
* The copyright in this software is being made available under the BSD License,
* included below. This software may be subject to other third party and contributor
* rights, including patent rights, and no such rights are granted under this license.
*
* Copyright (c) 2013, Dash Industry Forum.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
* * Neither the name of Dash Industry Forum nor the names of its
* contributors may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
var LOG_LEVEL_NONE = 0;
var LOG_LEVEL_FATAL = 1;
var LOG_LEVEL_ERROR = 2;
var LOG_LEVEL_WARNING = 3;
var LOG_LEVEL_INFO = 4;
var LOG_LEVEL_DEBUG = 5;
/**
* @module Debug
* @param {object} config
* @ignore
*/
function Debug(config) {
config = config || {};
var context = this.context;
var eventBus = (0,_EventBus__WEBPACK_IMPORTED_MODULE_0__["default"])(context).getInstance();
var settings = config.settings;
var logFn = [];
var instance, showLogTimestamp, showCalleeName, startTime;
function setup() {
showLogTimestamp = true;
showCalleeName = true;
startTime = new Date().getTime();
if (typeof window !== 'undefined' && window.console) {
logFn[LOG_LEVEL_FATAL] = getLogFn(window.console.error);
logFn[LOG_LEVEL_ERROR] = getLogFn(window.console.error);
logFn[LOG_LEVEL_WARNING] = getLogFn(window.console.warn);
logFn[LOG_LEVEL_INFO] = getLogFn(window.console.info);
logFn[LOG_LEVEL_DEBUG] = getLogFn(window.console.debug);
}
}
function getLogFn(fn) {
if (fn && fn.bind) {
return fn.bind(window.console);
} // if not define, return the default function for reporting logs
return window.console.log.bind(window.console);
}
/**
* Retrieves a logger which can be used to write logging information in browser console.
* @param {object} instance Object for which the logger is created. It is used
* to include calle object information in log messages.
* @memberof module:Debug
* @returns {Logger}
* @instance
*/
function getLogger(instance) {
return {
fatal: fatal.bind(instance),
error: error.bind(instance),
warn: warn.bind(instance),
info: info.bind(instance),
debug: debug.bind(instance)
};
}
/**
* Prepends a timestamp in milliseconds to each log message.
* @param {boolean} value Set to true if you want to see a timestamp in each log message.
* @default LOG_LEVEL_WARNING
* @memberof module:Debug
* @instance
*/
function setLogTimestampVisible(value) {
showLogTimestamp = value;
}
/**
* Prepends the callee object name, and media type if available, to each log message.
* @param {boolean} value Set to true if you want to see the callee object name and media type in each log message.
* @default true
* @memberof module:Debug
* @instance
*/
function setCalleeNameVisible(value) {
showCalleeName = value;
}
function fatal() {
for (var _len = arguments.length, params = new Array(_len), _key = 0; _key < _len; _key++) {
params[_key] = arguments[_key];
}
doLog.apply(void 0, [LOG_LEVEL_FATAL, this].concat(params));
}
function error() {
for (var _len2 = arguments.length, params = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
params[_key2] = arguments[_key2];
}
doLog.apply(void 0, [LOG_LEVEL_ERROR, this].concat(params));
}
function warn() {
for (var _len3 = arguments.length, params = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
params[_key3] = arguments[_key3];
}
doLog.apply(void 0, [LOG_LEVEL_WARNING, this].concat(params));
}
function info() {
for (var _len4 = arguments.length, params = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
params[_key4] = arguments[_key4];
}
doLog.apply(void 0, [LOG_LEVEL_INFO, this].concat(params));
}
function debug() {
for (var _len5 = arguments.length, params = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
params[_key5] = arguments[_key5];
}
doLog.apply(void 0, [LOG_LEVEL_DEBUG, this].concat(params));
}
function doLog(level, _this) {
var message = '';
var logTime = null;
if (showLogTimestamp) {
logTime = new Date().getTime();
message += '[' + (logTime - startTime) + ']';
}
if (showCalleeName && _this && _this.getClassName) {
message += '[' + _this.getClassName() + ']';
if (_this.getType) {
message += '[' + _this.getType() + ']';
}
}
if (message.length > 0) {
message += ' ';
}
for (var _len6 = arguments.length, params = new Array(_len6 > 2 ? _len6 - 2 : 0), _key6 = 2; _key6 < _len6; _key6++) {
params[_key6 - 2] = arguments[_key6];
}
Array.apply(null, params).forEach(function (item) {
message += item + ' ';
}); // log to console if the log level is high enough
if (logFn[level] && settings && settings.get().debug.logLevel >= level) {
logFn[level](message);
} // send log event regardless of log level
if (settings && settings.get().debug.dispatchEvent) {
eventBus.trigger(_events_Events__WEBPACK_IMPORTED_MODULE_1__["default"].LOG, {
message: message,
level: level
});
}
}
instance = {
getLogger: getLogger,
setLogTimestampVisible: setLogTimestampVisible,
setCalleeNameVisible: setCalleeNameVisible
};
setup();
return instance;
}
Debug.__dashjs_factory_name = 'Debug';
var factory = _FactoryMaker__WEBPACK_IMPORTED_MODULE_2__["default"].getSingletonFactory(Debug);
factory.LOG_LEVEL_NONE = LOG_LEVEL_NONE;
factory.LOG_LEVEL_FATAL = LOG_LEVEL_FATAL;
factory.LOG_LEVEL_ERROR = LOG_LEVEL_ERROR;
factory.LOG_LEVEL_WARNING = LOG_LEVEL_WARNING;
factory.LOG_LEVEL_INFO = LOG_LEVEL_INFO;
factory.LOG_LEVEL_DEBUG = LOG_LEVEL_DEBUG;
_FactoryMaker__WEBPACK_IMPORTED_MODULE_2__["default"].updateSingletonFactory(Debug.__dashjs_factory_name, factory);
/* harmony default export */ __webpack_exports__["default"] = (factory);
/***/ }),
/***/ "./src/core/EventBus.js":
/*!******************************!*\
!*** ./src/core/EventBus.js ***!
\******************************/
/***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _FactoryMaker__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./FactoryMaker */ "./src/core/FactoryMaker.js");
/* harmony import */ var _streaming_MediaPlayerEvents__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../streaming/MediaPlayerEvents */ "./src/streaming/MediaPlayerEvents.js");
/**
* The copyright in this software is being made available under the BSD License,
* included below. This software may be subject to other third party and contributor
* rights, including patent rights, and no such rights are granted under this license.
*
* Copyright (c) 2013, Dash Industry Forum.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
* * Neither the name of Dash Industry Forum nor the names of its
* contributors may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
var EVENT_PRIORITY_LOW = 0;
var EVENT_PRIORITY_HIGH = 5000;
function EventBus() {
var handlers = {};
function on(type, listener, scope) {
var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
if (!type) {
throw new Error('event type cannot be null or undefined');
}
if (!listener || typeof listener !== 'function') {
throw new Error('listener must be a function: ' + listener);
}
var priority = options.priority || EVENT_PRIORITY_LOW;
if (getHandlerIdx(type, listener, scope) >= 0) return;
handlers[type] = handlers[type] || [];
var handler = {
callback: listener,
scope: scope,
priority: priority
};
if (scope && scope.getStreamId) {
handler.streamId = scope.getStreamId();
}
if (scope && scope.getType) {
handler.mediaType = scope.getType();
}
if (options && options.mode) {
handler.mode = options.mode;
}
var inserted = handlers[type].some(function (item, idx) {
if (item && priority > item.priority) {
handlers[type].splice(idx, 0, handler);
return true;
}
});
if (!inserted) {
handlers[type].push(handler);
}
}
function off(type, listener, scope) {
if (!type || !listener || !handlers[type]) return;
var idx = getHandlerIdx(type, listener, scope);
if (idx < 0) return;
handlers[type][idx] = null;
}
function trigger(type) {
var payload = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var filters = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
if (!type || !handlers[type]) return;
payload = payload || {};
if (payload.hasOwnProperty('type')) throw new Error('\'type\' is a reserved word for event dispatching');
payload.type = type;
if (filters.streamId) {
payload.streamId = filters.streamId;
}
if (filters.mediaType) {
payload.mediaType = filters.mediaType;
}
handlers[type].filter(function (handler) {
if (!handler) {
return false;
}
if (filters.streamId && handler.streamId && handler.streamId !== filters.streamId) {
return false;
}
if (filters.mediaType && handler.mediaType && handler.mediaType !== filters.mediaType) {
return false;
} // This is used for dispatching DASH events. By default we use the onStart mode. Consequently we filter everything that has a non matching mode and the onReceive events for handlers that did not specify a mode.
if (filters.mode && handler.mode && handler.mode !== filters.mode || !handler.mode && filters.mode && filters.mode === _streaming_MediaPlayerEvents__WEBPACK_IMPORTED_MODULE_1__["default"].EVENT_MODE_ON_RECEIVE) {
return false;
}
return true;
}).forEach(function (handler) {
return handler && handler.callback.call(handler.scope, payload);
});
}
function getHandlerIdx(type, listener, scope) {
var idx = -1;
if (!handlers[type]) return idx;
handlers[type].some(function (item, index) {
if (item && item.callback === listener && (!scope || scope === item.scope)) {
idx = index;
return true;
}
});
return idx;
}
function reset() {
handlers = {};
}
var instance = {
on: on,
off: off,
trigger: trigger,
reset: reset
};
return instance;
}
EventBus.__dashjs_factory_name = 'EventBus';
var factory = _FactoryMaker__WEBPACK_IMPORTED_MODULE_0__["default"].getSingletonFactory(EventBus);
factory.EVENT_PRIORITY_LOW = EVENT_PRIORITY_LOW;
factory.EVENT_PRIORITY_HIGH = EVENT_PRIORITY_HIGH;
_FactoryMaker__WEBPACK_IMPORTED_MODULE_0__["default"].updateSingletonFactory(EventBus.__dashjs_factory_name, factory);
/* harmony default export */ __webpack_exports__["default"] = (factory);
/***/ }),
/***/ "./src/core/FactoryMaker.js":
/*!**********************************!*\
!*** ./src/core/FactoryMaker.js ***!
\**********************************/
/***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/**
* The copyright in this software is being made available under the BSD License,
* included below. This software may be subject to other third party and contributor
* rights, including patent rights, and no such rights are granted under this license.
*
* Copyright (c) 2013, Dash Industry Forum.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
* * Neither the name of Dash Industry Forum nor the names of its
* contributors may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @module FactoryMaker
* @ignore
*/
var FactoryMaker = function () {
var instance;
var singletonContexts = [];
var singletonFactories = {};
var classFactories = {};
function extend(name, childInstance, override, context) {
if (!context[name] && childInstance) {
context[name] = {
instance: childInstance,
override: override
};
}
}
/**
* Use this method from your extended object. this.factory is injected into your object.
* this.factory.getSingletonInstance(this.context, 'VideoModel')
* will return the video model for use in the extended object.
*
* @param {Object} context - injected into extended object as this.context
* @param {string} className - string name found in all dash.js objects
* with name __dashjs_factory_name Will be at the bottom. Will be the same as the object's name.
* @returns {*} Context aware instance of specified singleton name.
* @memberof module:FactoryMaker
* @instance
*/
function getSingletonInstance(context, className) {
for (var i in singletonContexts) {
var obj = singletonContexts[i];
if (obj.context === context && obj.name === className) {
return obj.instance;
}
}
return null;
}
/**
* Use this method to add an singleton instance to the system. Useful for unit testing to mock objects etc.
*
* @param {Object} context
* @param {string} className
* @param {Object} instance
* @memberof module:FactoryMaker
* @instance
*/
function setSingletonInstance(context, className, instance) {
for (var i in singletonContexts) {
var obj = singletonContexts[i];
if (obj.context === context && obj.name === className) {
singletonContexts[i].instance = instance;
return;
}
}
singletonContexts.push({
name: className,
context: context,
instance: instance
});
}
/**
* Use this method to remove all singleton instances associated with a particular context.
*
* @param {Object} context
* @memberof module:FactoryMaker
* @instance
*/
function deleteSingletonInstances(context) {
singletonContexts = singletonContexts.filter(function (x) {
return x.context !== context;
});
}
/*------------------------------------------------------------------------------------------*/
// Factories storage Management
/*------------------------------------------------------------------------------------------*/
function getFactoryByName(name, factoriesArray) {
return factoriesArray[name];
}
function updateFactory(name, factory, factoriesArray) {
if (name in factoriesArray) {
factoriesArray[name] = factory;
}
}
/*------------------------------------------------------------------------------------------*/
// Class Factories Management
/*------------------------------------------------------------------------------------------*/
function updateClassFactory(name, factory) {
updateFactory(name, factory, classFactories);
}
function getClassFactoryByName(name) {
return getFactoryByName(name, classFactories);
}
function getClassFactory(classConstructor) {
var factory = getFactoryByName(classConstructor.__dashjs_factory_name, classFactories);
if (!factory) {
factory = function factory(context) {
if (context === undefined) {
context = {};
}
return {
create: function create() {
return merge(classConstructor, context, arguments);
}
};
};
classFactories[classConstructor.__dashjs_factory_name] = factory; // store factory
}
return factory;
}
/*------------------------------------------------------------------------------------------*/
// Singleton Factory MAangement
/*------------------------------------------------------------------------------------------*/
function updateSingletonFactory(name, factory) {
updateFactory(name, factory, singletonFactories);
}
function getSingletonFactoryByName(name) {
return getFactoryByName(name, singletonFactories);
}
function getSingletonFactory(classConstructor) {
var factory = getFactoryByName(classConstructor.__dashjs_factory_name, singletonFactories);
if (!factory) {
factory = function factory(context) {
var instance;
if (context === undefined) {
context = {};
}
return {
getInstance: function getInstance() {
// If we don't have an instance yet check for one on the context
if (!instance) {
instance = getSingletonInstance(context, classConstructor.__dashjs_factory_name);
} // If there's no instance on the context then create one
if (!instance) {
instance = merge(classConstructor, context, arguments);
singletonContexts.push({
name: classConstructor.__dashjs_factory_name,
context: context,
instance: instance
});
}
return instance;
}
};
};
singletonFactories[classConstructor.__dashjs_factory_name] = factory; // store factory
}
return factory;
}
function merge(classConstructor, context, args) {
var classInstance;
var className = classConstructor.__dashjs_factory_name;
var extensionObject = context[className];
if (extensionObject) {
var extension = extensionObject.instance;
if (extensionObject.override) {
//Override public methods in parent but keep parent.
classInstance = classConstructor.apply({
context: context
}, args);
extension = extension.apply({
context: context,
factory: instance,
parent: classInstance
}, args);
for (var prop in extension) {
if (classInstance.hasOwnProperty(prop)) {
classInstance[prop] = extension[prop];
}
}
} else {
//replace parent object completely with new object. Same as dijon.
return extension.apply({
context: context,
factory: instance
}, args);
}
} else {
// Create new instance of the class
classInstance = classConstructor.apply({
context: context
}, args);
} // Add getClassName function to class instance prototype (used by Debug)
classInstance.getClassName = function () {
return className;
};
return classInstance;
}
instance = {
extend: extend,
getSingletonInstance: getSingletonInstance,
setSingletonInstance: setSingletonInstance,
deleteSingletonInstances: deleteSingletonInstances,
getSingletonFactory: getSingletonFactory,
getSingletonFactoryByName: getSingletonFactoryByName,
updateSingletonFactory: updateSingletonFactory,
getClassFactory: getClassFactory,
getClassFactoryByName: getClassFactoryByName,
updateClassFactory: updateClassFactory
};
return instance;
}();
/* harmony default export */ __webpack_exports__["default"] = (FactoryMaker);
/***/ }),
/***/ "./src/core/Settings.js":
/*!******************************!*\
!*** ./src/core/Settings.js ***!
\******************************/
/***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _FactoryMaker__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./FactoryMaker */ "./src/core/FactoryMaker.js");
/* harmony import */ var _Utils_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Utils.js */ "./src/core/Utils.js");
/* harmony import */ var _core_Debug__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../core/Debug */ "./src/core/Debug.js");
/* harmony import */ var _streaming_constants_Constants__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../streaming/constants/Constants */ "./src/streaming/constants/Constants.js");
/* harmony import */ var _streaming_vo_metrics_HTTPRequest__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../streaming/vo/metrics/HTTPRequest */ "./src/streaming/vo/metrics/HTTPRequest.js");
/* harmony import */ var _EventBus__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./EventBus */ "./src/core/EventBus.js");
/* harmony import */ var _events_Events__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./events/Events */ "./src/core/events/Events.js");
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
/**
* The copyright in this software is being made available under the BSD License,
* included below. This software may be subject to other third party and contributor
* rights, including patent rights, and no such rights are granted under this license.
*
* Copyright (c) 2013, Dash Industry Forum.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
* * Neither the name of Dash Industry Forum nor the names of its
* contributors may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/** @module Settings
* @description Define the configuration parameters of Dash.js MediaPlayer.
* @see {@link module:Settings~PlayerSettings PlayerSettings} for further information about the supported configuration properties.
*/
/**
* @typedef {Object} PlayerSettings
* @property {module:Settings~DebugSettings} [debug]
* Debug related settings.
* @property {module:Settings~ErrorSettings} [errors]
* Error related settings
* @property {module:Settings~StreamingSettings} [streaming]
* Streaming related settings.
* @example
*
* // Full settings object
* settings = {
* debug: {
* logLevel: Debug.LOG_LEVEL_WARNING,
* dispatchEvent: false
* },
* streaming: {
* abandonLoadTimeout: 10000,
* wallclockTimeUpdateInterval: 100,
* manifestUpdateRetryInterval: 100,
* liveUpdateTimeThresholdInMilliseconds: 0,
* cacheInitSegments: false,
* applyServiceDescription: true,
* applyProducerReferenceTime: true,
* applyContentSteering: true,
* eventControllerRefreshDelay: 100,
* enableManifestDurationMismatchFix: true,
* enableManifestTimescaleMismatchFix: false,
* parseInbandPrft: false,
* capabilities: {
* filterUnsupportedEssentialProperties: true,
* useMediaCapabilitiesApi: false
* },
* timeShiftBuffer: {
* calcFromSegmentTimeline: false,
* fallbackToSegmentTimeline: true
* },
* metrics: {
* maxListDepth: 100
* },
* delay: {
* liveDelayFragmentCount: NaN,
* liveDelay: NaN,
* useSuggestedPresentationDelay: true
* },
* protection: {
* keepProtectionMediaKeys: false,
* ignoreEmeEncryptedEvent: false,
* detectPlayreadyMessageFormat: true,
* },
* buffer: {
* enableSeekDecorrelationFix: false,
* fastSwitchEnabled: true,
* flushBufferAtTrackSwitch: false,
* reuseExistingSourceBuffers: true,
* bufferPruningInterval: 10,
* bufferToKeep: 20,
* bufferTimeAtTopQuality: 30,
* bufferTimeAtTopQualityLongForm: 60,
* initialBufferLevel: NaN,
* stableBufferTime: 12,
* longFormContentDurationThreshold: 600,
* stallThreshold: 0.3,
* useAppendWindow: true,
* setStallState: true,
* avoidCurrentTimeRangePruning: false,
* useChangeTypeForTrackSwitch: true,
* mediaSourceDurationInfinity: true,
* resetSourceBuffersForTrackSwitch: false
* },
* gaps: {
* jumpGaps: true,
* jumpLargeGaps: true,
* smallGapLimit: 1.5,
* threshold: 0.3,
* enableSeekFix: true,
* enableStallFix: false,
* stallSeek: 0.1
* },
* utcSynchronization: {
* enabled: true,
* useManifestDateHeaderTimeSource: true,
* backgroundAttempts: 2,
* timeBetweenSyncAttempts: 30,
* maximumTimeBetweenSyncAttempts: 600,
* minimumTimeBetweenSyncAttempts: 2,
* timeBetweenSyncAttemptsAdjustmentFactor: 2,
* maximumAllowedDrift: 100,
* enableBackg