forked from video-dev/hls.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hls.js.map
107 lines (107 loc) · 673 KB
/
hls.js.map
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
{
"version": 3,
"sources": [
"node_modules/browser-pack/_prelude.js",
"node_modules/events/events.js",
"node_modules/url-toolkit/src/url-toolkit.js",
"node_modules/webworkify/index.js",
"src/controller/abr-controller.js",
"src/controller/audio-stream-controller.js",
"src/controller/audio-track-controller.js",
"src/controller/buffer-controller.js",
"src/controller/cap-level-controller.js",
"src/controller/ewma-bandwidth-estimator.js",
"src/controller/fps-controller.js",
"src/controller/level-controller.js",
"src/controller/stream-controller.js",
"src/controller/timeline-controller.js",
"src/crypt/aes-crypto.js",
"src/crypt/aes-decryptor.js",
"src/crypt/decrypter.js",
"src/crypt/fast-aes-key.js",
"src/demux/aacdemuxer.js",
"src/demux/adts.js",
"src/demux/demuxer-inline.js",
"src/demux/demuxer-worker.js",
"src/demux/demuxer.js",
"src/demux/exp-golomb.js",
"src/demux/id3.js",
"src/demux/tsdemuxer.js",
"src/errors.js",
"src/event-handler.js",
"src/events.js",
"src/helper/aac.js",
"src/helper/buffer-helper.js",
"src/helper/level-helper.js",
"src/hls.js",
"src/index.js",
"src/loader/fragment-loader.js",
"src/loader/key-loader.js",
"src/loader/playlist-loader.js",
"src/remux/mp4-generator.js",
"src/remux/mp4-remuxer.js",
"src/remux/passthrough-remuxer.js",
"src/utils/attr-list.js",
"src/utils/binary-search.js",
"src/utils/cea-608-parser.js",
"src/utils/cues.js",
"src/utils/ewma.js",
"src/utils/logger.js",
"src/utils/timeRanges.js",
"src/utils/xhr-loader.js"
],
"names": [],
"mappings": "AAAA;ACAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC9SA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;;AC3EA;;;;AACA;;;;AACA;;;;AACA;;AACA;;AACA;;;;;;;;;;+eAXA;;;;;;IAaM,a;;;AAEJ,y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M,gBAAV,EAA4B;AAC1B,cAAM,KAAN,GAAc,MAAM,KAApB;AACD;AACD,UAAI,aAAa,KAAK,SAAL,CAAe,UAAhC;AACA,UAAI,UAAJ,EAAgB;AACd;AACA,mBAAW,KAAX,EAAkB,KAAK,OAAvB,EAAgC,IAAhC;AACD;AACF;;;;;;kBAGY,S",
"file": "generated.js",
"sourceRoot": "",
"sourcesContent": [
"(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require==\"function\"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error(\"Cannot find module '\"+o+\"'\");throw f.code=\"MODULE_NOT_FOUND\",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require==\"function\"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})",
"// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nfunction EventEmitter() {\n this._events = this._events || {};\n this._maxListeners = this._maxListeners || undefined;\n}\nmodule.exports = EventEmitter;\n\n// Backwards-compat with node 0.10.x\nEventEmitter.EventEmitter = EventEmitter;\n\nEventEmitter.prototype._events = undefined;\nEventEmitter.prototype._maxListeners = undefined;\n\n// By default EventEmitters will print a warning if more than 10 listeners are\n// added to it. This is a useful default which helps finding memory leaks.\nEventEmitter.defaultMaxListeners = 10;\n\n// Obviously not all Emitters should be limited to 10. This function allows\n// that to be increased. Set to zero for unlimited.\nEventEmitter.prototype.setMaxListeners = function(n) {\n if (!isNumber(n) || n < 0 || isNaN(n))\n throw TypeError('n must be a positive number');\n this._maxListeners = n;\n return this;\n};\n\nEventEmitter.prototype.emit = function(type) {\n var er, handler, len, args, i, listeners;\n\n if (!this._events)\n this._events = {};\n\n // If there is no 'error' event listener then throw.\n if (type === 'error') {\n if (!this._events.error ||\n (isObject(this._events.error) && !this._events.error.length)) {\n er = arguments[1];\n if (er instanceof Error) {\n throw er; // Unhandled 'error' event\n } else {\n // At least give some kind of context to the user\n var err = new Error('Uncaught, unspecified \"error\" event. (' + er + ')');\n err.context = er;\n throw err;\n }\n }\n }\n\n handler = this._events[type];\n\n if (isUndefined(handler))\n return false;\n\n if (isFunction(handler)) {\n switch (arguments.length) {\n // fast cases\n case 1:\n handler.call(this);\n break;\n case 2:\n handler.call(this, arguments[1]);\n break;\n case 3:\n handler.call(this, arguments[1], arguments[2]);\n break;\n // slower\n default:\n args = Array.prototype.slice.call(arguments, 1);\n handler.apply(this, args);\n }\n } else if (isObject(handler)) {\n args = Array.prototype.slice.call(arguments, 1);\n listeners = handler.slice();\n len = listeners.length;\n for (i = 0; i < len; i++)\n listeners[i].apply(this, args);\n }\n\n return true;\n};\n\nEventEmitter.prototype.addListener = function(type, listener) {\n var m;\n\n if (!isFunction(listener))\n throw TypeError('listener must be a function');\n\n if (!this._events)\n this._events = {};\n\n // To avoid recursion in the case that type === \"newListener\"! Before\n // adding it to the listeners, first emit \"newListener\".\n if (this._events.newListener)\n this.emit('newListener', type,\n isFunction(listener.listener) ?\n listener.listener : listener);\n\n if (!this._events[type])\n // Optimize the case of one listener. Don't need the extra array object.\n this._events[type] = listener;\n else if (isObject(this._events[type]))\n // If we've already got an array, just append.\n this._events[type].push(listener);\n else\n // Adding the second element, need to change to array.\n this._events[type] = [this._events[type], listener];\n\n // Check for listener leak\n if (isObject(this._events[type]) && !this._events[type].warned) {\n if (!isUndefined(this._maxListeners)) {\n m = this._maxListeners;\n } else {\n m = EventEmitter.defaultMaxListeners;\n }\n\n if (m && m > 0 && this._events[type].length > m) {\n this._events[type].warned = true;\n console.error('(node) warning: possible EventEmitter memory ' +\n 'leak detected. %d listeners added. ' +\n 'Use emitter.setMaxListeners() to increase limit.',\n this._events[type].length);\n if (typeof console.trace === 'function') {\n // not supported in IE 10\n console.trace();\n }\n }\n }\n\n return this;\n};\n\nEventEmitter.prototype.on = EventEmitter.prototype.addListener;\n\nEventEmitter.prototype.once = function(type, listener) {\n if (!isFunction(listener))\n throw TypeError('listener must be a function');\n\n var fired = false;\n\n function g() {\n this.removeListener(type, g);\n\n if (!fired) {\n fired = true;\n listener.apply(this, arguments);\n }\n }\n\n g.listener = listener;\n this.on(type, g);\n\n return this;\n};\n\n// emits a 'removeListener' event iff the listener was removed\nEventEmitter.prototype.removeListener = function(type, listener) {\n var list, position, length, i;\n\n if (!isFunction(listener))\n throw TypeError('listener must be a function');\n\n if (!this._events || !this._events[type])\n return this;\n\n list = this._events[type];\n length = list.length;\n position = -1;\n\n if (list === listener ||\n (isFunction(list.listener) && list.listener === listener)) {\n delete this._events[type];\n if (this._events.removeListener)\n this.emit('removeListener', type, listener);\n\n } else if (isObject(list)) {\n for (i = length; i-- > 0;) {\n if (list[i] === listener ||\n (list[i].listener && list[i].listener === listener)) {\n position = i;\n break;\n }\n }\n\n if (position < 0)\n return this;\n\n if (list.length === 1) {\n list.length = 0;\n delete this._events[type];\n } else {\n list.splice(position, 1);\n }\n\n if (this._events.removeListener)\n this.emit('removeListener', type, listener);\n }\n\n return this;\n};\n\nEventEmitter.prototype.removeAllListeners = function(type) {\n var key, listeners;\n\n if (!this._events)\n return this;\n\n // not listening for removeListener, no need to emit\n if (!this._events.removeListener) {\n if (arguments.length === 0)\n this._events = {};\n else if (this._events[type])\n delete this._events[type];\n return this;\n }\n\n // emit removeListener for all listeners on all events\n if (arguments.length === 0) {\n for (key in this._events) {\n if (key === 'removeListener') continue;\n this.removeAllListeners(key);\n }\n this.removeAllListeners('removeListener');\n this._events = {};\n return this;\n }\n\n listeners = this._events[type];\n\n if (isFunction(listeners)) {\n this.removeListener(type, listeners);\n } else if (listeners) {\n // LIFO order\n while (listeners.length)\n this.removeListener(type, listeners[listeners.length - 1]);\n }\n delete this._events[type];\n\n return this;\n};\n\nEventEmitter.prototype.listeners = function(type) {\n var ret;\n if (!this._events || !this._events[type])\n ret = [];\n else if (isFunction(this._events[type]))\n ret = [this._events[type]];\n else\n ret = this._events[type].slice();\n return ret;\n};\n\nEventEmitter.prototype.listenerCount = function(type) {\n if (this._events) {\n var evlistener = this._events[type];\n\n if (isFunction(evlistener))\n return 1;\n else if (evlistener)\n return evlistener.length;\n }\n return 0;\n};\n\nEventEmitter.listenerCount = function(emitter, type) {\n return emitter.listenerCount(type);\n};\n\nfunction isFunction(arg) {\n return typeof arg === 'function';\n}\n\nfunction isNumber(arg) {\n return typeof arg === 'number';\n}\n\nfunction isObject(arg) {\n return typeof arg === 'object' && arg !== null;\n}\n\nfunction isUndefined(arg) {\n return arg === void 0;\n}\n",
"/* jshint ignore:start */\r\n(function(root) { \r\n/* jshint ignore:end */\r\n var URLToolkit = {\r\n // build an absolute URL from a relative one using the provided baseURL\r\n // if relativeURL is an absolute URL it will be returned as is.\r\n buildAbsoluteURL: function(baseURL, relativeURL) {\r\n // remove any remaining space and CRLF\r\n relativeURL = relativeURL.trim();\r\n if (/^[a-z]+:/i.test(relativeURL)) {\r\n // complete url, not relative\r\n return relativeURL;\r\n }\r\n\r\n var relativeURLQuery = null;\r\n var relativeURLHash = null;\r\n\r\n var relativeURLHashSplit = /^([^#]*)(.*)$/.exec(relativeURL);\r\n if (relativeURLHashSplit) {\r\n relativeURLHash = relativeURLHashSplit[2];\r\n relativeURL = relativeURLHashSplit[1];\r\n }\r\n var relativeURLQuerySplit = /^([^\\?]*)(.*)$/.exec(relativeURL);\r\n if (relativeURLQuerySplit) {\r\n relativeURLQuery = relativeURLQuerySplit[2];\r\n relativeURL = relativeURLQuerySplit[1];\r\n }\r\n\r\n var baseURLHashSplit = /^([^#]*)(.*)$/.exec(baseURL);\r\n if (baseURLHashSplit) {\r\n baseURL = baseURLHashSplit[1];\r\n }\r\n var baseURLQuerySplit = /^([^\\?]*)(.*)$/.exec(baseURL);\r\n if (baseURLQuerySplit) {\r\n baseURL = baseURLQuerySplit[1];\r\n }\r\n\r\n var baseURLDomainSplit = /^(([a-z]+:)?\\/\\/[a-z0-9\\.\\-_~]+(:[0-9]+)?)?(\\/.*)$/i.exec(baseURL);\r\n if (!baseURLDomainSplit) {\r\n throw new Error('Error trying to parse base URL.');\r\n }\r\n \r\n // e.g. 'http:', 'https:', ''\r\n var baseURLProtocol = baseURLDomainSplit[2] || '';\r\n // e.g. 'http://example.com', '//example.com', ''\r\n var baseURLProtocolDomain = baseURLDomainSplit[1] || '';\r\n // e.g. '/a/b/c/playlist.m3u8'\r\n var baseURLPath = baseURLDomainSplit[4];\r\n\r\n var builtURL = null;\r\n if (/^\\/\\//.test(relativeURL)) {\r\n // relative url starts wth '//' so copy protocol (which may be '' if baseUrl didn't provide one)\r\n builtURL = baseURLProtocol+'//'+URLToolkit.buildAbsolutePath('', relativeURL.substring(2));\r\n }\r\n else if (/^\\//.test(relativeURL)) {\r\n // relative url starts with '/' so start from root of domain\r\n builtURL = baseURLProtocolDomain+'/'+URLToolkit.buildAbsolutePath('', relativeURL.substring(1));\r\n }\r\n else {\r\n builtURL = URLToolkit.buildAbsolutePath(baseURLProtocolDomain+baseURLPath, relativeURL);\r\n }\r\n\r\n // put the query and hash parts back\r\n if (relativeURLQuery) {\r\n builtURL += relativeURLQuery;\r\n }\r\n if (relativeURLHash) {\r\n builtURL += relativeURLHash;\r\n }\r\n return builtURL;\r\n },\r\n\r\n // build an absolute path using the provided basePath\r\n // adapted from https://developer.mozilla.org/en-US/docs/Web/API/document/cookie#Using_relative_URLs_in_the_path_parameter\r\n // this does not handle the case where relativePath is \"/\" or \"//\". These cases should be handled outside this.\r\n buildAbsolutePath: function(basePath, relativePath) {\r\n var sRelPath = relativePath;\r\n var nUpLn, sDir = '', sPath = basePath.replace(/[^\\/]*$/, sRelPath.replace(/(\\/|^)(?:\\.?\\/+)+/g, '$1'));\r\n for (var nEnd, nStart = 0; nEnd = sPath.indexOf('/../', nStart), nEnd > -1; nStart = nEnd + nUpLn) {\r\n nUpLn = /^\\/(?:\\.\\.\\/)*/.exec(sPath.slice(nEnd))[0].length;\r\n sDir = (sDir + sPath.substring(nStart, nEnd)).replace(new RegExp('(?:\\\\\\/+[^\\\\\\/]*){0,' + ((nUpLn - 1) / 3) + '}$'), '/');\r\n }\r\n return sDir + sPath.substr(nStart);\r\n }\r\n };\r\n\r\n/* jshint ignore:start */\r\n if(typeof exports === 'object' && typeof module === 'object')\r\n module.exports = URLToolkit;\r\n else if(typeof define === 'function' && define.amd)\r\n define([], function() { return URLToolkit; });\r\n else if(typeof exports === 'object')\r\n exports[\"URLToolkit\"] = URLToolkit;\r\n else\r\n root[\"URLToolkit\"] = URLToolkit;\r\n})(this);\r\n/* jshint ignore:end */\r\n",
"var bundleFn = arguments[3];\nvar sources = arguments[4];\nvar cache = arguments[5];\n\nvar stringify = JSON.stringify;\n\nmodule.exports = function (fn, options) {\n var wkey;\n var cacheKeys = Object.keys(cache);\n\n for (var i = 0, l = cacheKeys.length; i < l; i++) {\n var key = cacheKeys[i];\n var exp = cache[key].exports;\n // Using babel as a transpiler to use esmodule, the export will always\n // be an object with the default export as a property of it. To ensure\n // the existing api and babel esmodule exports are both supported we\n // check for both\n if (exp === fn || exp && exp.default === fn) {\n wkey = key;\n break;\n }\n }\n\n if (!wkey) {\n wkey = Math.floor(Math.pow(16, 8) * Math.random()).toString(16);\n var wcache = {};\n for (var i = 0, l = cacheKeys.length; i < l; i++) {\n var key = cacheKeys[i];\n wcache[key] = key;\n }\n sources[wkey] = [\n Function(['require','module','exports'], '(' + fn + ')(self)'),\n wcache\n ];\n }\n var skey = Math.floor(Math.pow(16, 8) * Math.random()).toString(16);\n\n var scache = {}; scache[wkey] = wkey;\n sources[skey] = [\n Function(['require'], (\n // try to call default if defined to also support babel esmodule\n // exports\n 'var f = require(' + stringify(wkey) + ');' +\n '(f.default ? f.default : f)(self);'\n )),\n scache\n ];\n\n var workerSources = {};\n resolveSources(skey);\n\n function resolveSources(key) {\n workerSources[key] = true;\n\n for (var depPath in sources[key][1]) {\n var depKey = sources[key][1][depPath];\n if (!workerSources[depKey]) {\n resolveSources(depKey);\n }\n }\n }\n\n var src = '(' + bundleFn + ')({'\n + Object.keys(workerSources).map(function (key) {\n return stringify(key) + ':['\n + sources[key][0]\n + ',' + stringify(sources[key][1]) + ']'\n ;\n }).join(',')\n + '},{},[' + stringify(skey) + '])'\n ;\n\n var URL = window.URL || window.webkitURL || window.mozURL || window.msURL;\n\n var blob = new Blob([src], { type: 'text/javascript' });\n if (options && options.bare) { return blob; }\n var workerUrl = URL.createObjectURL(blob);\n var worker = new Worker(workerUrl);\n worker.objectURL = workerUrl;\n return worker;\n};\n",
"/*\n * simple ABR Controller\n * - compute next level based on last fragment bw heuristics\n * - implement an abandon rules triggered if we have less than 2 frag buffered and if computed bw shows that we risk buffer stalling\n */\n\nimport Event from '../events';\nimport EventHandler from '../event-handler';\nimport BufferHelper from '../helper/buffer-helper';\nimport {ErrorDetails} from '../errors';\nimport {logger} from '../utils/logger';\nimport EwmaBandWidthEstimator from './ewma-bandwidth-estimator';\n\nclass AbrController extends EventHandler {\n\n constructor(hls) {\n super(hls, Event.FRAG_LOADING,\n Event.FRAG_LOADED,\n Event.FRAG_BUFFERED,\n Event.ERROR);\n this.lastLoadedFragLevel = 0;\n this._autoLevelCapping = -1;\n this._nextAutoLevel = -1;\n this.hls = hls;\n this.onCheck = this.abandonRulesCheck.bind(this);\n }\n\n destroy() {\n this.clearTimer();\n EventHandler.prototype.destroy.call(this);\n }\n\n onFragLoading(data) {\n let frag = data.frag;\n if (frag.type === 'main') {\n if (!this.timer) {\n this.timer = setInterval(this.onCheck, 100);\n }\n // lazy init of bw Estimator, rationale is that we use different params for Live/VoD\n // so we need to wait for stream manifest / playlist type to instantiate it.\n if (!this.bwEstimator) {\n let hls = this.hls,\n level = data.frag.level,\n isLive = hls.levels[level].details.live,\n config = hls.config,\n ewmaFast, ewmaSlow;\n\n if (isLive) {\n ewmaFast = config.abrEwmaFastLive;\n ewmaSlow = config.abrEwmaSlowLive;\n } else {\n ewmaFast = config.abrEwmaFastVoD;\n ewmaSlow = config.abrEwmaSlowVoD;\n }\n this.bwEstimator = new EwmaBandWidthEstimator(hls,ewmaSlow,ewmaFast,config.abrEwmaDefaultEstimate);\n }\n this.fragCurrent = frag;\n }\n }\n\n abandonRulesCheck() {\n /*\n monitor fragment retrieval time...\n we compute expected time of arrival of the complete fragment.\n we compare it to expected time of buffer starvation\n */\n let hls = this.hls, v = hls.media,frag = this.fragCurrent, loader = frag.loader, minAutoLevel = this.minAutoLevel;\n\n // if loader has been destroyed or loading has been aborted, stop timer and return\n if(!loader || ( loader.stats && loader.stats.aborted)) {\n logger.warn('frag loader destroy or aborted, disarm abandonRules');\n this.clearTimer();\n return;\n }\n let stats = loader.stats;\n /* only monitor frag retrieval time if\n (video not paused OR first fragment being loaded(ready state === HAVE_NOTHING = 0)) AND autoswitching enabled AND not lowest level (=> means that we have several levels) */\n if (v && ((!v.paused && (v.playbackRate !== 0)) || !v.readyState) && frag.autoLevel && frag.level) {\n let requestDelay = performance.now() - stats.trequest,\n playbackRate = Math.abs(v.playbackRate);\n // monitor fragment load progress after half of expected fragment duration,to stabilize bitrate\n if (requestDelay > (500 * frag.duration / playbackRate)) {\n let levels = hls.levels,\n loadRate = Math.max(1, stats.bw ? stats.bw / 8 : stats.loaded * 1000 / requestDelay), // byte/s; at least 1 byte/s to avoid division by zero\n // compute expected fragment length using frag duration and level bitrate. also ensure that expected len is gte than already loaded size\n expectedLen = stats.total ? stats.total : Math.max(stats.loaded, Math.round(frag.duration * levels[frag.level].bitrate / 8)),\n pos = v.currentTime,\n fragLoadedDelay = (expectedLen - stats.loaded) / loadRate,\n bufferStarvationDelay = (BufferHelper.bufferInfo(v,pos,hls.config.maxBufferHole).end - pos) / playbackRate;\n // consider emergency switch down only if we have less than 2 frag buffered AND\n // time to finish loading current fragment is bigger than buffer starvation delay\n // ie if we risk buffer starvation if bw does not increase quickly\n if ((bufferStarvationDelay < (2 * frag.duration / playbackRate)) && (fragLoadedDelay > bufferStarvationDelay)) {\n let fragLevelNextLoadedDelay, nextLoadLevel;\n // lets iterate through lower level and try to find the biggest one that could avoid rebuffering\n // we start from current level - 1 and we step down , until we find a matching level\n for (nextLoadLevel = frag.level - 1 ; nextLoadLevel > minAutoLevel ; nextLoadLevel--) {\n // compute time to load next fragment at lower level\n // 0.8 : consider only 80% of current bw to be conservative\n // 8 = bits per byte (bps/Bps)\n fragLevelNextLoadedDelay = frag.duration * levels[nextLoadLevel].bitrate / (8 * 0.8 * loadRate);\n if (fragLevelNextLoadedDelay < bufferStarvationDelay) {\n // we found a lower level that be rebuffering free with current estimated bw !\n break;\n }\n }\n // only emergency switch down if it takes less time to load new fragment at lowest level instead\n // of finishing loading current one ...\n if (fragLevelNextLoadedDelay < fragLoadedDelay) {\n logger.warn(`loading too slow, abort fragment loading and switch to level ${nextLoadLevel}:fragLoadedDelay[${nextLoadLevel}]<fragLoadedDelay[${frag.level-1}];bufferStarvationDelay:${fragLevelNextLoadedDelay.toFixed(1)}<${fragLoadedDelay.toFixed(1)}:${bufferStarvationDelay.toFixed(1)}`);\n // force next load level in auto mode\n hls.nextLoadLevel = nextLoadLevel;\n // update bw estimate for this fragment before cancelling load (this will help reducing the bw)\n this.bwEstimator.sample(requestDelay,stats.loaded);\n //abort fragment loading\n loader.abort();\n // stop abandon rules timer\n this.clearTimer();\n hls.trigger(Event.FRAG_LOAD_EMERGENCY_ABORTED, {frag: frag, stats: stats });\n }\n }\n }\n }\n }\n\n onFragLoaded(data) {\n let frag = data.frag;\n if (frag.type === 'main') {\n // stop monitoring bw once frag loaded\n this.clearTimer();\n // store level id after successful fragment load\n this.lastLoadedFragLevel = frag.level;\n // reset forced auto level value so that next level will be selected\n this._nextAutoLevel = -1;\n // if fragment has been loaded to perform a bitrate test,\n if (data.frag.bitrateTest) {\n let stats = data.stats;\n stats.tparsed = stats.tbuffered = stats.tload;\n this.onFragBuffered(data);\n }\n }\n }\n\n onFragBuffered(data) {\n var stats = data.stats, frag = data.frag;\n // only update stats on first frag buffering\n // if same frag is loaded multiple times, it might be in browser cache, and loaded quickly\n // and leading to wrong bw estimation\n // on bitrate test, also only update stats once (if tload = tbuffered == on FRAG_LOADED)\n if (stats.aborted !== true && frag.loadCounter === 1 && frag.type === 'main' && ((!frag.bitrateTest || stats.tload === stats.tbuffered))) {\n // use tparsed-trequest instead of tbuffered-trequest to compute fragLoadingProcessing; rationale is that buffer appending only happens once media is attached\n // in case we use config.startFragPrefetch while media is not attached yet, fragment might be parsed while media not attached yet, but it will only be buffered on media attached\n // as a consequence it could happen really late in the process. meaning that appending duration might appears huge ... leading to underestimated throughput estimation\n let fragLoadingProcessingMs = stats.tparsed - stats.trequest;\n logger.log(`latency/loading/parsing/append/kbps:${Math.round(stats.tfirst-stats.trequest)}/${Math.round(stats.tload-stats.tfirst)}/${Math.round(stats.tparsed-stats.tload)}/${Math.round(stats.tbuffered-stats.tparsed)}/${Math.round(8*stats.loaded/(stats.tbuffered-stats.trequest))}`);\n this.bwEstimator.sample(fragLoadingProcessingMs,stats.loaded);\n // if fragment has been loaded to perform a bitrate test, (hls.startLevel = -1), store bitrate test delay duration\n if (frag.bitrateTest) {\n this.bitrateTestDelay = fragLoadingProcessingMs/1000;\n } else {\n this.bitrateTestDelay = 0;\n }\n }\n }\n\n onError(data) {\n // stop timer in case of frag loading error\n switch(data.details) {\n case ErrorDetails.FRAG_LOAD_ERROR:\n case ErrorDetails.FRAG_LOAD_TIMEOUT:\n this.clearTimer();\n break;\n default:\n break;\n }\n }\n\n clearTimer() {\n if (this.timer) {\n clearInterval(this.timer);\n this.timer = null;\n }\n }\n\n /** Return the capping/max level value that could be used by automatic level selection algorithm **/\n get autoLevelCapping() {\n return this._autoLevelCapping;\n }\n\n /** set the capping/max level value that could be used by automatic level selection algorithm **/\n set autoLevelCapping(newLevel) {\n this._autoLevelCapping = newLevel;\n }\n\n get nextAutoLevel() {\n let nextAutoLevel = this._nextAutoLevel, bwEstimator = this.bwEstimator, hls = this.hls,\n levels = hls.levels, minAutoBitrate = hls.config.minAutoBitrate;\n // in case next auto level has been forced, and bw not available or not reliable\n if (nextAutoLevel !== -1 && (!bwEstimator || !bwEstimator.canEstimate())) {\n // cap next auto level by max auto level\n return Math.min(nextAutoLevel,this.maxAutoLevel);\n }\n // compute next level using ABR logic\n let nextABRAutoLevel = this.nextABRAutoLevel;\n if (nextAutoLevel !== -1) {\n // nextAutoLevel is defined, use it to cap ABR computed quality level\n nextABRAutoLevel = Math.min(nextAutoLevel,nextABRAutoLevel);\n }\n if(minAutoBitrate !== undefined) {\n while (levels[nextABRAutoLevel].bitrate < minAutoBitrate) {\n nextABRAutoLevel++;\n }\n }\n return nextABRAutoLevel;\n }\n\n get minAutoLevel() {\n let hls = this.hls, levels = hls.levels, minAutoBitrate = hls.config.minAutoBitrate, len = levels ? levels.length : 0;\n for (let i = 0; i < len; i++) {\n if (levels[i].bitrate > minAutoBitrate) {\n return i;\n }\n }\n return 0;\n }\n\n get maxAutoLevel() {\n var levels = this.hls.levels,autoLevelCapping = this._autoLevelCapping, maxAutoLevel;\n if (autoLevelCapping=== -1 && levels && levels.length) {\n maxAutoLevel = levels.length - 1;\n } else {\n maxAutoLevel = autoLevelCapping;\n }\n return maxAutoLevel;\n }\n\n get nextABRAutoLevel() {\n var hls = this.hls, maxAutoLevel = this.maxAutoLevel, levels = hls.levels, config = hls.config, minAutoLevel = this.minAutoLevel;\n const v = hls.media,\n currentLevel = this.lastLoadedFragLevel,\n currentFragDuration = this.fragCurrent ? this.fragCurrent.duration : 0,\n pos = (v ? v.currentTime : 0),\n // playbackRate is the absolute value of the playback rate; if v.playbackRate is 0, we use 1 to load as\n // if we're playing back at the normal rate.\n playbackRate = ((v && (v.playbackRate !== 0)) ? Math.abs(v.playbackRate) : 1.0),\n avgbw = this.bwEstimator ? this.bwEstimator.getEstimate() : config.abrEwmaDefaultEstimate,\n // bufferStarvationDelay is the wall-clock time left until the playback buffer is exhausted.\n bufferStarvationDelay = (BufferHelper.bufferInfo(v, pos, config.maxBufferHole).end - pos) / playbackRate;\n\n // First, look to see if we can find a level matching with our avg bandwidth AND that could also guarantee no rebuffering at all\n let bestLevel = this.findBestLevel(currentLevel,currentFragDuration,avgbw,minAutoLevel,maxAutoLevel,bufferStarvationDelay,config.abrBandWidthFactor,config.abrBandWidthUpFactor,levels);\n if (bestLevel >= 0) {\n return bestLevel;\n } else {\n logger.trace('rebuffering expected to happen, lets try to find a quality level minimizing the rebuffering');\n // not possible to get rid of rebuffering ... let's try to find level that will guarantee less than maxStarvationDelay of rebuffering\n // if no matching level found, logic will return 0\n let maxStarvationDelay = config.maxStarvationDelay,\n bwFactor = config.abrBandWidthFactor,\n bwUpFactor = config.abrBandWidthUpFactor;\n if (bufferStarvationDelay === 0) {\n // in case buffer is empty, let's check if previous fragment was loaded to perform a bitrate test\n let bitrateTestDelay = this.bitrateTestDelay;\n if (bitrateTestDelay) {\n // if it is the case, then we need to adjust our max starvation delay using maxLoadingDelay config value\n // max video loading delay used in automatic start level selection :\n // in that mode ABR controller will ensure that video loading time (ie the time to fetch the first fragment at lowest quality level +\n // the time to fetch the fragment at the appropriate quality level is less than ```maxLoadingDelay``` )\n maxStarvationDelay = config.maxLoadingDelay - bitrateTestDelay;\n logger.trace(`bitrate test took ${Math.round(1000*bitrateTestDelay)}ms, set first fragment max fetchDuration to ${Math.round(1000*maxStarvationDelay)} ms`);\n // don't use conservative factor on bitrate test\n bwFactor = bwUpFactor = 1;\n }\n }\n bestLevel = this.findBestLevel(currentLevel,currentFragDuration,avgbw,minAutoLevel,maxAutoLevel,bufferStarvationDelay+maxStarvationDelay,bwFactor,bwUpFactor,levels);\n return Math.max(bestLevel,0);\n }\n }\n\n findBestLevel(currentLevel,currentFragDuration,currentBw,minAutoLevel,maxAutoLevel,maxFetchDuration,bwFactor,bwUpFactor,levels) {\n for (let i = maxAutoLevel; i >= minAutoLevel; i--) {\n let levelInfo = levels[i],\n levelDetails = levelInfo.details,\n avgDuration = levelDetails ? levelDetails.totalduration/levelDetails.fragments.length : currentFragDuration,\n live = levelDetails ? levelDetails.live : false,\n adjustedbw;\n // follow algorithm captured from stagefright :\n // https://android.googlesource.com/platform/frameworks/av/+/master/media/libstagefright/httplive/LiveSession.cpp\n // Pick the highest bandwidth stream below or equal to estimated bandwidth.\n // consider only 80% of the available bandwidth, but if we are switching up,\n // be even more conservative (70%) to avoid overestimating and immediately\n // switching back.\n if (i <= currentLevel) {\n adjustedbw = bwFactor * currentBw;\n } else {\n adjustedbw = bwUpFactor * currentBw;\n }\n const bitrate = levels[i].bitrate,\n fetchDuration = bitrate * avgDuration / adjustedbw;\n\n logger.trace(`level/adjustedbw/bitrate/avgDuration/maxFetchDuration/fetchDuration: ${i}/${Math.round(adjustedbw)}/${bitrate}/${avgDuration}/${maxFetchDuration}/${fetchDuration}`);\n // if adjusted bw is greater than level bitrate AND\n if (adjustedbw > bitrate &&\n // fragment fetchDuration unknown OR live stream OR fragment fetchDuration less than max allowed fetch duration, then this level matches\n // we don't account for max Fetch Duration for live streams, this is to avoid switching down when near the edge of live sliding window ...\n (!fetchDuration || live || fetchDuration < maxFetchDuration) ) {\n // as we are looping from highest to lowest, this will return the best achievable quality level\n\n return i;\n }\n }\n // not enough time budget even with quality level 0 ... rebuffering might happen\n return -1;\n }\n\n set nextAutoLevel(nextLevel) {\n this._nextAutoLevel = nextLevel;\n }\n}\n\nexport default AbrController;\n\n",
"/*\n * Audio Stream Controller\n*/\n\nimport BinarySearch from '../utils/binary-search';\nimport BufferHelper from '../helper/buffer-helper';\nimport Demuxer from '../demux/demuxer';\nimport Event from '../events';\nimport EventHandler from '../event-handler';\nimport LevelHelper from '../helper/level-helper';\nimport TimeRanges from '../utils/timeRanges';\nimport {ErrorTypes, ErrorDetails} from '../errors';\nimport {logger} from '../utils/logger';\n\nconst State = {\n STOPPED : 'STOPPED',\n STARTING : 'STARTING',\n IDLE : 'IDLE',\n PAUSED : 'PAUSED',\n KEY_LOADING : 'KEY_LOADING',\n FRAG_LOADING : 'FRAG_LOADING',\n FRAG_LOADING_WAITING_RETRY : 'FRAG_LOADING_WAITING_RETRY',\n WAITING_TRACK : 'WAITING_TRACK',\n PARSING : 'PARSING',\n PARSED : 'PARSED',\n ENDED : 'ENDED',\n ERROR : 'ERROR',\n WAITING_INIT_PTS : 'WAITING_INIT_PTS'\n};\n\nclass AudioStreamController extends EventHandler {\n\n constructor(hls) {\n super(hls,\n Event.MEDIA_ATTACHED,\n Event.MEDIA_DETACHING,\n Event.AUDIO_TRACKS_UPDATED,\n Event.AUDIO_TRACK_SWITCHING,\n Event.AUDIO_TRACK_LOADED,\n Event.KEY_LOADED,\n Event.FRAG_LOADED,\n Event.FRAG_PARSING_INIT_SEGMENT,\n Event.FRAG_PARSING_DATA,\n Event.FRAG_PARSED,\n Event.ERROR,\n Event.BUFFER_CREATED,\n Event.BUFFER_APPENDED,\n Event.BUFFER_FLUSHED,\n Event.INIT_PTS_FOUND);\n\n this.config = hls.config;\n this.audioCodecSwap = false;\n this.ticks = 0;\n this.ontick = this.tick.bind(this);\n this.initPTS=[];\n this.waitingFragment=null;\n }\n\n destroy() {\n this.stopLoad();\n if (this.timer) {\n clearInterval(this.timer);\n this.timer = null;\n }\n EventHandler.prototype.destroy.call(this);\n this.state = State.STOPPED;\n }\n\n //Signal that video PTS was found\n onInitPtsFound(data) {\n var demuxerId=data.id, cc = data.cc, initPTS = data.initPTS;\n if(demuxerId === 'main') {\n //Always update the new INIT PTS\n //Can change due level switch\n this.initPTS[cc] = initPTS;\n logger.log(`InitPTS for cc:${cc} found from video track:${initPTS}`);\n\n //If we are waiting we need to demux/remux the waiting frag\n //With the new initPTS\n if (this.state === State.WAITING_INIT_PTS) {\n logger.log('sending pending audio frag to demuxer');\n this.state = State.FRAG_LOADING;\n //We have audio frag waiting or video pts\n //Let process it\n this.onFragLoaded(this.waitingFragment);\n //Lets clean the waiting frag\n this.waitingFragment = null;\n }\n }\n }\n\n startLoad(startPosition) {\n if (this.tracks) {\n var lastCurrentTime = this.lastCurrentTime;\n this.stopLoad();\n if (!this.timer) {\n this.timer = setInterval(this.ontick, 100);\n }\n this.fragLoadError = 0;\n if (lastCurrentTime > 0 && startPosition === -1) {\n logger.log(`audio:override startPosition with lastCurrentTime @${lastCurrentTime.toFixed(3)}`);\n this.state = State.IDLE;\n } else {\n this.lastCurrentTime = this.startPosition ? this.startPosition : startPosition;\n this.state = State.STARTING;\n }\n this.nextLoadPosition = this.startPosition = this.lastCurrentTime;\n this.tick();\n } else {\n this.startPosition = startPosition;\n this.state = State.STOPPED;\n }\n }\n\n stopLoad() {\n var frag = this.fragCurrent;\n if (frag) {\n if (frag.loader) {\n frag.loader.abort();\n }\n this.fragCurrent = null;\n }\n this.fragPrevious = null;\n if (this.demuxer) {\n this.demuxer.destroy();\n this.demuxer = null;\n }\n this.state = State.STOPPED;\n }\n\n tick() {\n this.ticks++;\n if (this.ticks === 1) {\n this.doTick();\n if (this.ticks > 1) {\n setTimeout(this.tick, 1);\n }\n this.ticks = 0;\n }\n }\n\n doTick() {\n var pos, track, trackDetails, hls = this.hls, config = hls.config;\n //logger.log('audioStream:' + this.state);\n switch(this.state) {\n case State.ERROR:\n //don't do anything in error state to avoid breaking further ...\n case State.PAUSED:\n //don't do anything in paused state either ...\n break;\n case State.STARTING:\n this.state = State.WAITING_TRACK;\n this.loadedmetadata = false;\n break;\n case State.IDLE:\n // if video not attached AND\n // start fragment already requested OR start frag prefetch disable\n // exit loop\n // => if media not attached but start frag prefetch is enabled and start frag not requested yet, we will not exit loop\n if (!this.media &&\n (this.startFragRequested || !config.startFragPrefetch)) {\n break;\n }\n // determine next candidate fragment to be loaded, based on current position and\n // end of buffer position\n // if we have not yet loaded any fragment, start loading from start position\n if (this.loadedmetadata) {\n pos = this.media.currentTime;\n } else {\n pos = this.nextLoadPosition;\n }\n let media = this.mediaBuffer ? this.mediaBuffer : this.media,\n bufferInfo = BufferHelper.bufferInfo(media,pos,config.maxBufferHole),\n bufferLen = bufferInfo.len,\n bufferEnd = bufferInfo.end,\n fragPrevious = this.fragPrevious,\n maxBufLen = config.maxMaxBufferLength,\n audioSwitch = this.audioSwitch;\n\n // if buffer length is less than maxBufLen try to load a new fragment\n if (bufferLen < maxBufLen && this.trackId < this.tracks.length) {\n trackDetails = this.tracks[this.trackId].details;\n // if track info not retrieved yet, switch state and wait for track retrieval\n if (typeof trackDetails === 'undefined') {\n this.state = State.WAITING_TRACK;\n break;\n }\n\n // we just got done loading the final fragment, check if we need to finalize media stream\n if (!audioSwitch && !trackDetails.live && fragPrevious && fragPrevious.sn === trackDetails.endSN) {\n // if we are not seeking or if we are seeking but everything (almost) til the end is buffered, let's signal eos\n // we don't compare exactly media.duration === bufferInfo.end as there could be some subtle media duration difference when switching\n // between different renditions. using half frag duration should help cope with these cases.\n if (!this.media.seeking || (this.media.duration-bufferEnd) < fragPrevious.duration/2) {\n // Finalize the media stream\n this.hls.trigger(Event.BUFFER_EOS,{ type : 'audio'});\n this.state = State.ENDED;\n break;\n }\n }\n\n // find fragment index, contiguous with end of buffer position\n let fragments = trackDetails.fragments,\n fragLen = fragments.length,\n start = fragments[0].start,\n end = fragments[fragLen-1].start + fragments[fragLen-1].duration,\n frag;\n\n // When switching audio track, reload audio as close as possible to currentTime\n if(audioSwitch){\n if (trackDetails.live && !trackDetails.PTSKnown) {\n logger.log(`switching audiotrack, live stream, unknown PTS,load first fragment`);\n bufferEnd = 0;\n } else {\n bufferEnd = pos;\n // if currentTime (pos) is less than alt audio playlist start time, it means that alt audio is ahead of currentTime\n if (trackDetails.PTSKnown && pos < start) {\n // if everything is buffered from pos to start, let's seek to start\n if (bufferInfo.end > start) {\n logger.log('alt audio track ahead of main track, seek to start of alt audio track');\n this.media.currentTime = start + 0.05;\n } else {\n return;\n }\n }\n }\n }\n\n // if bufferEnd before start of playlist, load first fragment\n if (bufferEnd < start) {\n frag = fragments[0];\n } else {\n let foundFrag;\n let maxFragLookUpTolerance = config.maxFragLookUpTolerance;\n if (bufferEnd < end) {\n if (bufferEnd > end - maxFragLookUpTolerance) {\n maxFragLookUpTolerance = 0;\n }\n foundFrag = BinarySearch.search(fragments, (candidate) => {\n // offset should be within fragment boundary - config.maxFragLookUpTolerance\n // this is to cope with situations like\n // bufferEnd = 9.991\n // frag[Ø] : [0,10]\n // frag[1] : [10,20]\n // bufferEnd is within frag[0] range ... although what we are expecting is to return frag[1] here\n // frag start frag start+duration\n // |-----------------------------|\n // <---> <--->\n // ...--------><-----------------------------><---------....\n // previous frag matching fragment next frag\n // return -1 return 0 return 1\n //logger.log(`level/sn/start/end/bufEnd:${level}/${candidate.sn}/${candidate.start}/${(candidate.start+candidate.duration)}/${bufferEnd}`);\n if ((candidate.start + candidate.duration - maxFragLookUpTolerance) <= bufferEnd) {\n return 1;\n }\n else if (candidate.start - maxFragLookUpTolerance > bufferEnd) {\n return -1;\n }\n return 0;\n });\n } else {\n // reach end of playlist\n foundFrag = fragments[fragLen-1];\n }\n if (foundFrag) {\n frag = foundFrag;\n start = foundFrag.start;\n //logger.log('find SN matching with pos:' + bufferEnd + ':' + frag.sn);\n if (fragPrevious && frag.level === fragPrevious.level && frag.sn === fragPrevious.sn) {\n if (frag.sn < trackDetails.endSN) {\n frag = fragments[frag.sn + 1 - trackDetails.startSN];\n logger.log(`SN just loaded, load next one: ${frag.sn}`);\n } else {\n frag = null;\n }\n }\n }\n }\n if(frag) {\n //logger.log(' loading frag ' + i +',pos/bufEnd:' + pos.toFixed(3) + '/' + bufferEnd.toFixed(3));\n if ((frag.decryptdata.uri != null) && (frag.decryptdata.key == null)) {\n logger.log(`Loading key for ${frag.sn} of [${trackDetails.startSN} ,${trackDetails.endSN}],track ${this.trackId}`);\n this.state = State.KEY_LOADING;\n hls.trigger(Event.KEY_LOADING, {frag: frag});\n } else {\n logger.log(`Loading ${frag.sn} of [${trackDetails.startSN} ,${trackDetails.endSN}],track ${this.trackId}, currentTime:${pos},bufferEnd:${bufferEnd.toFixed(3)}`);\n // ensure that we are not reloading the same fragments in loop ...\n if (this.fragLoadIdx !== undefined) {\n this.fragLoadIdx++;\n } else {\n this.fragLoadIdx = 0;\n }\n if (frag.loadCounter) {\n frag.loadCounter++;\n let maxThreshold = config.fragLoadingLoopThreshold;\n // if this frag has already been loaded 3 times, and if it has been reloaded recently\n if (frag.loadCounter > maxThreshold && (Math.abs(this.fragLoadIdx - frag.loadIdx) < maxThreshold)) {\n hls.trigger(Event.ERROR, {type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.FRAG_LOOP_LOADING_ERROR, fatal: false, frag: frag});\n return;\n }\n } else {\n frag.loadCounter = 1;\n }\n frag.loadIdx = this.fragLoadIdx;\n this.fragCurrent = frag;\n this.startFragRequested = true;\n this.nextLoadPosition = frag.start + frag.duration;\n hls.trigger(Event.FRAG_LOADING, {frag: frag});\n this.state = State.FRAG_LOADING;\n }\n }\n }\n break;\n case State.WAITING_TRACK:\n track = this.tracks[this.trackId];\n // check if playlist is already loaded\n if (track && track.details) {\n this.state = State.IDLE;\n }\n break;\n case State.FRAG_LOADING_WAITING_RETRY:\n var now = performance.now();\n var retryDate = this.retryDate;\n media = this.media;\n var isSeeking = media && media.seeking;\n // if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading\n if(!retryDate || (now >= retryDate) || isSeeking) {\n logger.log(`audioStreamController: retryDate reached, switch back to IDLE state`);\n this.state = State.IDLE;\n }\n break;\n case State.WAITING_INIT_PTS:\n case State.STOPPED:\n case State.FRAG_LOADING:\n case State.PARSING:\n case State.PARSED:\n case State.ENDED:\n break;\n default:\n break;\n }\n }\n\n onMediaAttached(data) {\n var media = this.media = this.mediaBuffer = data.media;\n this.onvseeking = this.onMediaSeeking.bind(this);\n this.onvended = this.onMediaEnded.bind(this);\n media.addEventListener('seeking', this.onvseeking);\n media.addEventListener('ended', this.onvended);\n let config = this.config;\n if(this.tracks && config.autoStartLoad) {\n this.startLoad(config.startPosition);\n }\n }\n\n onMediaDetaching() {\n var media = this.media;\n if (media && media.ended) {\n logger.log('MSE detaching and video ended, reset startPosition');\n this.startPosition = this.lastCurrentTime = 0;\n }\n\n // reset fragment loading counter on MSE detaching to avoid reporting FRAG_LOOP_LOADING_ERROR after error recovery\n var tracks = this.tracks;\n if (tracks) {\n // reset fragment load counter\n tracks.forEach(track => {\n if(track.details) {\n track.details.fragments.forEach(fragment => {\n fragment.loadCounter = undefined;\n });\n }\n });\n }\n // remove video listeners\n if (media) {\n media.removeEventListener('seeking', this.onvseeking);\n media.removeEventListener('ended', this.onvended);\n this.onvseeking = this.onvseeked = this.onvended = null;\n }\n this.media = this.mediaBuffer = null;\n this.loadedmetadata = false;\n this.stopLoad();\n }\n\n onMediaSeeking() {\n if (this.state === State.ENDED) {\n // switch to IDLE state to check for potential new fragment\n this.state = State.IDLE;\n }\n if (this.media) {\n this.lastCurrentTime = this.media.currentTime;\n }\n // avoid reporting fragment loop loading error in case user is seeking several times on same position\n if (this.fragLoadIdx !== undefined) {\n this.fragLoadIdx += 2 * this.config.fragLoadingLoopThreshold;\n }\n // tick to speed up processing\n this.tick();\n }\n\n onMediaEnded() {\n // reset startPosition and lastCurrentTime to restart playback @ stream beginning\n this.startPosition = this.lastCurrentTime = 0;\n }\n\n\n onAudioTracksUpdated(data) {\n logger.log('audio tracks updated');\n this.tracks = data.audioTracks;\n }\n\n onAudioTrackSwitching(data) {\n // if any URL found on new audio track, it is an alternate audio track\n var altAudio = !!data.url;\n this.trackId = data.id;\n this.state = State.IDLE;\n\n this.fragCurrent = null;\n this.state = State.PAUSED;\n this.waitingFragment=null;\n // destroy useless demuxer when switching audio to main\n if (!altAudio) {\n if (this.demuxer) {\n this.demuxer.destroy();\n this.demuxer = null;\n }\n } else {\n // switching to audio track, start timer if not already started\n if (!this.timer) {\n this.timer = setInterval(this.ontick, 100);\n }\n }\n\n //should we switch tracks ?\n if(altAudio){\n this.audioSwitch = true;\n //main audio track are handled by stream-controller, just do something if switching to alt audio track\n this.state=State.IDLE;\n // increase fragment load Index to avoid frag loop loading error after buffer flush\n this.fragLoadIdx += 2 * this.config.fragLoadingLoopThreshold;\n }\n this.tick();\n }\n\n onAudioTrackLoaded(data) {\n var newDetails = data.details,\n trackId = data.id,\n track = this.tracks[trackId],\n duration = newDetails.totalduration,\n sliding = 0;\n\n logger.log(`track ${trackId} loaded [${newDetails.startSN},${newDetails.endSN}],duration:${duration}`);\n\n if (newDetails.live) {\n var curDetails = track.details;\n if (curDetails && newDetails.fragments.length > 0) {\n // we already have details for that level, merge them\n LevelHelper.mergeDetails(curDetails,newDetails);\n sliding = newDetails.fragments[0].start;\n // TODO\n //this.liveSyncPosition = this.computeLivePosition(sliding, curDetails);\n if (newDetails.PTSKnown) {\n logger.log(`live audio playlist sliding:${sliding.toFixed(3)}`);\n } else {\n logger.log('live audio playlist - outdated PTS, unknown sliding');\n }\n } else {\n newDetails.PTSKnown = false;\n logger.log('live audio playlist - first load, unknown sliding');\n }\n } else {\n newDetails.PTSKnown = false;\n }\n track.details = newDetails;\n\n // compute start position\n if (!this.startFragRequested) {\n // compute start position if set to -1. use it straight away if value is defined\n if (this.startPosition === -1) {\n // first, check if start time offset has been set in playlist, if yes, use this value\n let startTimeOffset = newDetails.startTimeOffset;\n if(!isNaN(startTimeOffset)) {\n logger.log(`start time offset found in playlist, adjust startPosition to ${startTimeOffset}`);\n this.startPosition = startTimeOffset;\n } else {\n this.startPosition = 0;\n }\n }\n this.nextLoadPosition = this.startPosition;\n }\n // only switch batck to IDLE state if we were waiting for track to start downloading a new fragment\n if (this.state === State.WAITING_TRACK) {\n this.state = State.IDLE;\n }\n //trigger handler right now\n this.tick();\n }\n\n onKeyLoaded() {\n if (this.state === State.KEY_LOADING) {\n this.state = State.IDLE;\n this.tick();\n }\n }\n\n onFragLoaded(data) {\n var fragCurrent = this.fragCurrent;\n if (this.state === State.FRAG_LOADING &&\n fragCurrent &&\n data.frag.type === 'audio' &&\n data.frag.level === fragCurrent.level &&\n data.frag.sn === fragCurrent.sn) {\n this.state = State.PARSING;\n // transmux the MPEG-TS data to ISO-BMFF segments\n this.stats = data.stats;\n var track = this.tracks[this.trackId],\n details = track.details,\n duration = details.totalduration,\n start = fragCurrent.start,\n trackId = fragCurrent.level,\n sn = fragCurrent.sn,\n cc = fragCurrent.cc,\n audioCodec = this.config.defaultAudioCodec || track.audioCodec;\n this.appended = false;\n if(!this.demuxer) {\n this.demuxer = new Demuxer(this.hls,'audio');\n }\n //Check if we have video initPTS\n // If not we need to wait for it\n let initPTS = this.initPTS[cc];\n if (initPTS !== undefined){\n this.pendingBuffering = true;\n logger.log(`Demuxing ${sn} of [${details.startSN} ,${details.endSN}],track ${trackId}`);\n // time Offset is accurate if level PTS is known, or if playlist is not sliding (not live)\n let accurateTimeOffset = false; //details.PTSKnown || !details.live;\n this.demuxer.push(data.payload, audioCodec, null, start, cc, trackId, sn, duration, fragCurrent.decryptdata, accurateTimeOffset, initPTS);\n } else {\n logger.log(`unknown video PTS for continuity counter ${cc}, waiting for video PTS before demuxing audio frag ${sn} of [${details.startSN} ,${details.endSN}],track ${trackId}`);\n this.waitingFragment=data;\n this.state=State.WAITING_INIT_PTS;\n }\n }\n this.fragLoadError = 0;\n }\n\n onFragParsingInitSegment(data) {\n let fragCurrent = this.fragCurrent;\n if (fragCurrent &&\n data.id === 'audio' &&\n data.sn === fragCurrent.sn &&\n data.level === fragCurrent.level &&\n this.state === State.PARSING) {\n let tracks = data.tracks, track;\n\n // delete any video track found on audio demuxer\n if (tracks.video) {\n delete tracks.video;\n }\n\n // include levelCodec in audio and video tracks\n track = tracks.audio;\n if(track) {\n track.levelCodec = 'mp4a.40.2';\n track.id = data.id;\n this.hls.trigger(Event.BUFFER_CODECS,tracks);\n logger.log(`audio track:audio,container:${track.container},codecs[level/parsed]=[${track.levelCodec}/${track.codec}]`);\n let initSegment = track.initSegment;\n if (initSegment) {\n let appendObj = {type: 'audio', data: initSegment, parent : 'audio',content : 'initSegment'};\n if (this.audioSwitch) {\n this.pendingData = [appendObj];\n } else {\n this.appended = true;\n // arm pending Buffering flag before appending a segment\n this.pendingBuffering = true;\n this.hls.trigger(Event.BUFFER_APPENDING, appendObj);\n }\n }\n //trigger handler right now\n this.tick();\n }\n }\n }\n\n onFragParsingData(data) {\n let fragCurrent = this.fragCurrent;\n if (fragCurrent &&\n data.id === 'audio' &&\n data.type === 'audio' &&\n data.sn === fragCurrent.sn &&\n data.level === fragCurrent.level &&\n this.state === State.PARSING) {\n let trackId= this.trackId,\n track = this.tracks[trackId],\n frag = this.fragCurrent,\n hls = this.hls;\n\n logger.log(`parsed ${data.type},PTS:[${data.startPTS.toFixed(3)},${data.endPTS.toFixed(3)}],DTS:[${data.startDTS.toFixed(3)}/${data.endDTS.toFixed(3)}],nb:${data.nb}`);\n LevelHelper.updateFragPTSDTS(track.details,frag.sn,data.startPTS,data.endPTS);\n\n let audioSwitch = this.audioSwitch, media = this.media, appendOnBufferFlush = false;\n //Only flush audio from old audio tracks when PTS is known on new audio track\n if(audioSwitch && media) {\n if (media.readyState) {\n let currentTime = media.currentTime;\n logger.log('switching audio track : currentTime:'+ currentTime);\n if (currentTime >= data.startPTS) {\n logger.log('switching audio track : flushing all audio');\n hls.trigger(Event.BUFFER_FLUSHING, {startOffset: 0 , endOffset: Number.POSITIVE_INFINITY, type : 'audio'});\n appendOnBufferFlush = true;\n //Lets announce that the initial audio track switch flush occur\n this.audioSwitch = false;\n hls.trigger(Event.AUDIO_TRACK_SWITCHED, {id : trackId});\n }\n } else {\n //Lets announce that the initial audio track switch flush occur\n this.audioSwitch=false;\n hls.trigger(Event.AUDIO_TRACK_SWITCHED, {id : trackId});\n }\n }\n\n\n let pendingData = this.pendingData;\n if(!this.audioSwitch) {\n [data.data1, data.data2].forEach(buffer => {\n if (buffer) {\n pendingData.push({type: data.type, data: buffer, parent : 'audio',content : 'data'});\n }\n });\n if (!appendOnBufferFlush && pendingData.length) {\n pendingData.forEach(appendObj => {\n // arm pending Buffering flag before appending a segment\n this.pendingBuffering = true;\n this.hls.trigger(Event.BUFFER_APPENDING, appendObj);\n });\n this.pendingData = [];\n this.appended = true;\n }\n }\n //trigger handler right now\n this.tick();\n }\n }\n\n onFragParsed(data) {\n let fragCurrent = this.fragCurrent;\n if (fragCurrent &&\n data.id === 'audio' &&\n data.sn === fragCurrent.sn &&\n data.level === fragCurrent.level &&\n this.state === State.PARSING) {\n this.stats.tparsed = performance.now();\n this.state = State.PARSED;\n this._checkAppendedParsed();\n }\n }\n\n\n onBufferCreated(data) {\n let audioTrack = data.tracks.audio;\n if (audioTrack) {\n this.mediaBuffer = audioTrack.buffer;\n this.loadedmetadata = true;\n }\n }\n\n onBufferAppended(data) {\n if (data.parent === 'audio') {\n const state = this.state;\n if (state === State.PARSING || state === State.PARSED) {\n // check if all buffers have been appended\n this.pendingBuffering = (data.pending > 0);\n this._checkAppendedParsed();\n }\n }\n }\n\n _checkAppendedParsed() {\n //trigger handler right now\n if (this.state === State.PARSED && (!this.appended || !this.pendingBuffering)) {\n let frag = this.fragCurrent, stats = this.stats, hls = this.hls;\n if (frag) {\n this.fragPrevious = frag;\n stats.tbuffered = performance.now();\n hls.trigger(Event.FRAG_BUFFERED, {stats: stats, frag: frag, id : 'audio'});\n let media = this.mediaBuffer ? this.mediaBuffer : this.media;\n logger.log(`audio buffered : ${TimeRanges.toString(media.buffered)}`);\n if (this.audioSwitch && this.appended) {\n this.audioSwitch = false;\n hls.trigger(Event.AUDIO_TRACK_SWITCHED, {id : this.trackId});\n }\n this.state = State.IDLE;\n }\n this.tick();\n }\n }\n\n onError(data) {\n let frag = data.frag;\n // don't handle frag error not related to audio fragment\n if (frag && frag.type !== 'audio') {\n return;\n }\n switch(data.details) {\n case ErrorDetails.FRAG_LOAD_ERROR:\n case ErrorDetails.FRAG_LOAD_TIMEOUT:\n if(!data.fatal) {\n var loadError = this.fragLoadError;\n if(loadError) {\n loadError++;\n } else {\n loadError=1;\n }\n let config = this.config;\n if (loadError <= config.fragLoadingMaxRetry) {\n this.fragLoadError = loadError;\n // reset load counter to avoid frag loop loading error\n frag.loadCounter = 0;\n // exponential backoff capped to config.fragLoadingMaxRetryTimeout\n var delay = Math.min(Math.pow(2,loadError-1)*config.fragLoadingRetryDelay,config.fragLoadingMaxRetryTimeout);\n logger.warn(`audioStreamController: frag loading failed, retry in ${delay} ms`);\n this.retryDate = performance.now() + delay;\n // retry loading state\n this.state = State.FRAG_LOADING_WAITING_RETRY;\n } else {\n logger.error(`audioStreamController: ${data.details} reaches max retry, redispatch as fatal ...`);\n // redispatch same error but with fatal set to true\n data.fatal = true;\n this.hls.trigger(Event.ERROR, data);\n this.state = State.ERROR;\n }\n }\n break;\n case ErrorDetails.FRAG_LOOP_LOADING_ERROR:\n case ErrorDetails.AUDIO_TRACK_LOAD_ERROR:\n case ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:\n case ErrorDetails.KEY_LOAD_ERROR:\n case ErrorDetails.KEY_LOAD_TIMEOUT:\n // when in ERROR state, don't switch back to IDLE state in case a non-fatal error is received\n if(this.state !== State.ERROR) {\n // if fatal error, stop processing, otherwise move to IDLE to retry loading\n this.state = data.fatal ? State.ERROR : State.IDLE;\n logger.warn(`audioStreamController: ${data.details} while loading frag,switch to ${this.state} state ...`);\n }\n break;\n default:\n break;\n }\n }\n\n onBufferFlushed() {\n let pendingData = this.pendingData;\n if (pendingData && pendingData.length) {\n logger.log('appending pending audio data on Buffer Flushed');\n pendingData.forEach(appendObj => {\n this.hls.trigger(Event.BUFFER_APPENDING, appendObj);\n });\n this.appended = true;\n this.pendingData = [];\n this.state = State.PARSED;\n } else {\n // move to IDLE once flush complete. this should trigger new fragment loading\n this.state = State.IDLE;\n // reset reference to frag\n this.fragPrevious = null;\n this.tick();\n }\n }\n}\nexport default AudioStreamController;\n\n",
"/*\n * audio track controller\n*/\n\nimport Event from '../events';\nimport EventHandler from '../event-handler';\nimport {logger} from '../utils/logger';\n\nclass AudioTrackController extends EventHandler {\n\n constructor(hls) {\n super(hls, Event.MANIFEST_LOADING,\n Event.MANIFEST_LOADED,\n Event.AUDIO_TRACK_LOADED);\n this.ticks = 0;\n this.ontick = this.tick.bind(this);\n }\n\n destroy() {\n EventHandler.prototype.destroy.call(this);\n }\n tick() {\n this.ticks++;\n if (this.ticks === 1) {\n this.doTick();\n if (this.ticks > 1) {\n setTimeout(this.tick, 1);\n }\n this.ticks = 0;\n }\n }\n doTick() {\n this.updateTrack(this.trackId);\n }\n onManifestLoading() {\n // reset audio tracks on manifest loading\n this.tracks = [];\n this.trackId = -1;\n }\n\n onManifestLoaded(data) {\n let tracks = data.audioTracks || [];\n let defaultFound = false;\n this.tracks = tracks;\n this.hls.trigger(Event.AUDIO_TRACKS_UPDATED, {audioTracks : tracks});\n // loop through available audio tracks and autoselect default if needed\n let id = 0;\n tracks.forEach(track => {\n if(track.default) {\n this.audioTrack = id;\n defaultFound = true;\n return;\n }\n id++;\n });\n if (defaultFound === false && tracks.length) {\n logger.log('no default audio track defined, use first audio track as default');\n this.audioTrack = 0;\n }\n }\n\n onAudioTrackLoaded(data) {\n if (data.id < this.tracks.length) {\n logger.log(`audioTrack ${data.id} loaded`);\n this.tracks[data.id].details = data.details;\n // check if current playlist is a live playlist\n if (data.details.live && !this.timer) {\n // if live playlist we will have to reload it periodically\n // set reload period to playlist target duration\n this.timer = setInterval(this.ontick, 1000 * data.details.targetduration);\n }\n if (!data.details.live && this.timer) {\n // playlist is not live and timer is armed : stopping it\n clearInterval(this.timer);\n this.timer = null;\n }\n }\n }\n\n /** get alternate audio tracks list from playlist **/\n get audioTracks() {\n return this.tracks;\n }\n\n /** get index of the selected audio track (index in audio track lists) **/\n get audioTrack() {\n return this.trackId;\n }\n\n /** select an audio track, based on its index in audio track lists**/\n set audioTrack(audioTrackId) {\n if (this.trackId !== audioTrackId || this.tracks[audioTrackId].details === undefined) {\n this.setAudioTrackInternal(audioTrackId);\n }\n }\n\n setAudioTrackInternal(newId) {\n // check if level idx is valid\n if (newId >= 0 && newId < this.tracks.length) {\n // stopping live reloading timer if any\n if (this.timer) {\n clearInterval(this.timer);\n this.timer = null;\n }\n this.trackId = newId;\n logger.log(`switching to audioTrack ${newId}`);\n let audioTrack = this.tracks[newId],\n hls = this.hls,\n type = audioTrack.type,\n url = audioTrack.url,\n eventObj = {id: newId, type : type, url : url};\n // keep AUDIO_TRACK_SWITCH for legacy reason\n hls.trigger(Event.AUDIO_TRACK_SWITCH, eventObj);\n hls.trigger(Event.AUDIO_TRACK_SWITCHING, eventObj);\n // check if we need to load playlist for this audio Track\n let details = audioTrack.details;\n if (url && (details === undefined || details.live === true)) {\n // track not retrieved yet, or live playlist we need to (re)load it\n logger.log(`(re)loading playlist for audioTrack ${newId}`);\n hls.trigger(Event.AUDIO_TRACK_LOADING, {url: url, id: newId});\n }\n }\n }\n\n updateTrack(newId) {\n // check if level idx is valid\n if (newId >= 0 && newId < this.tracks.length) {\n // stopping live reloading timer if any\n if (this.timer) {\n clearInterval(this.timer);\n this.timer = null;\n }\n this.trackId = newId;\n logger.log(`updating audioTrack ${newId}`);\n let audioTrack = this.tracks[newId], url = audioTrack.url;\n // check if we need to load playlist for this audio Track\n let details = audioTrack.details;\n if (url && (details === undefined || details.live === true)) {\n // track not retrieved yet, or live playlist we need to (re)load it\n logger.log(`(re)loading playlist for audioTrack ${newId}`);\n this.hls.trigger(Event.AUDIO_TRACK_LOADING, {url: url, id: newId});\n }\n }\n }\n}\n\nexport default AudioTrackController;\n",
"/*\n * Buffer Controller\n*/\n\nimport Event from '../events';\nimport EventHandler from '../event-handler';\nimport {logger} from '../utils/logger';\nimport {ErrorTypes, ErrorDetails} from '../errors';\n\n\nclass BufferController extends EventHandler {\n\n constructor(hls) {\n super(hls,\n Event.MEDIA_ATTACHING,\n Event.MEDIA_DETACHING,\n Event.MANIFEST_PARSED,\n Event.BUFFER_RESET,\n Event.BUFFER_APPENDING,\n Event.BUFFER_CODECS,\n Event.BUFFER_EOS,\n Event.BUFFER_FLUSHING,\n Event.LEVEL_PTS_UPDATED,\n Event.LEVEL_UPDATED);\n\n // the value that we have set mediasource.duration to\n // (the actual duration may be tweaked slighly by the browser)\n this._msDuration = null;\n // the value that we want to set mediaSource.duration to\n this._levelDuration = null;\n\n // Source Buffer listeners\n this.onsbue = this.onSBUpdateEnd.bind(this);\n this.onsbe = this.onSBUpdateError.bind(this);\n this.pendingTracks = {};\n this.tracks = {};\n }\n\n destroy() {\n EventHandler.prototype.destroy.call(this);\n }\n\n onLevelPtsUpdated(data) {\n let type = data.type;\n let audioTrack = this.tracks.audio;\n\n // Adjusting `SourceBuffer.timestampOffset` (desired point in the timeline where the next frames should be appended)\n // in Chrome browser when we detect MPEG audio container and time delta between level PTS and `SourceBuffer.timestampOffset`\n // is greater than 100ms (this is enough to handle seek for VOD or level change for LIVE videos). At the time of change we issue\n // `SourceBuffer.abort()` and adjusting `SourceBuffer.timestampOffset` if `SourceBuffer.updating` is false or awaiting `updateend`\n // event if SB is in updating state.\n // More info here: https://github.com/dailymotion/hls.js/issues/332#issuecomment-257986486\n\n if (type === 'audio' && audioTrack && audioTrack.container === 'audio/mpeg') { // Chrome audio mp3 track\n let audioBuffer = this.sourceBuffer.audio;\n let delta = Math.abs(audioBuffer.timestampOffset - data.start);\n\n // adjust timestamp offset if time delta is greater than 100ms\n if (delta > 0.1) {\n let updating = audioBuffer.updating;\n\n try {\n audioBuffer.abort();\n } catch (err) {\n updating = true;\n logger.warn('can not abort audio buffer: ' + err);\n }\n\n if (!updating) {\n logger.warn('change mpeg audio timestamp offset from ' + audioBuffer.timestampOffset + ' to ' + data.start);\n audioBuffer.timestampOffset = data.start;\n } else {\n this.audioTimestampOffset = data.start;\n }\n }\n }\n }\n\n onManifestParsed(data) {\n let audioExpected = data.audio,\n videoExpected = data.video,\n sourceBufferNb = 0;\n // in case of alt audio 2 BUFFER_CODECS events will be triggered, one per stream controller\n // sourcebuffers will be created all at once when the expected nb of tracks will be reached\n // in case alt audio is not used, only one BUFFER_CODEC event will be fired from main stream controller\n // it will contain the expected nb of source buffers, no need to compute it\n if (data.altAudio && (audioExpected || videoExpected)) {\n sourceBufferNb = (audioExpected ? 1 : 0) + (videoExpected ? 1 : 0);\n logger.log(`${sourceBufferNb} sourceBuffer(s) expected`);\n }\n this.sourceBufferNb = sourceBufferNb;\n }\n\n onMediaAttaching(data) {\n let media = this.media = data.media;\n if (media) {\n // setup the media source\n var ms = this.mediaSource = new MediaSource();\n //Media Source listeners\n this.onmso = this.onMediaSourceOpen.bind(this);\n this.onmse = this.onMediaSourceEnded.bind(this);\n this.onmsc = this.onMediaSourceClose.bind(this);\n ms.addEventListener('sourceopen', this.onmso);\n ms.addEventListener('sourceended', this.onmse);\n ms.addEventListener('sourceclose', this.onmsc);\n // link video and media Source\n media.src = URL.createObjectURL(ms);\n }\n }\n\n onMediaDetaching() {\n logger.log('media source detaching');\n var ms = this.mediaSource;\n if (ms) {\n if (ms.readyState === 'open') {\n try {\n // endOfStream could trigger exception if any sourcebuffer is in updating state\n // we don't really care about checking sourcebuffer state here,\n // as we are anyway detaching the MediaSource\n // let's just avoid this exception to propagate\n ms.endOfStream();\n } catch(err) {\n logger.warn(`onMediaDetaching:${err.message} while calling endOfStream`);\n }\n }\n ms.removeEventListener('sourceopen', this.onmso);\n ms.removeEventListener('sourceended', this.onmse);\n ms.removeEventListener('sourceclose', this.onmsc);\n\n // Detach properly the MediaSource from the HTMLMediaElement as\n // suggested in https://github.com/w3c/media-source/issues/53.\n if (this.media) {\n URL.revokeObjectURL(this.media.src);\n this.media.removeAttribute('src');\n this.media.load();\n }\n\n this.mediaSource = null;\n this.media = null;\n this.pendingTracks = {};\n this.tracks = {};\n this.sourceBuffer = {};\n this.flushRange = [];\n this.segments = [];\n this.appended = 0;\n }\n this.onmso = this.onmse = this.onmsc = null;\n this.hls.trigger(Event.MEDIA_DETACHED);\n }\n\n onMediaSourceOpen() {\n logger.log('media source opened');\n this.hls.trigger(Event.MEDIA_ATTACHED, { media : this.media });\n let mediaSource = this.mediaSource;\n if (mediaSource) {\n // once received, don't listen anymore to sourceopen event\n mediaSource.removeEventListener('sourceopen', this.onmso);\n }\n this.checkPendingTracks();\n }\n\n checkPendingTracks() {\n // if any buffer codecs pending, check if we have enough to create sourceBuffers\n let pendingTracks = this.pendingTracks,\n pendingTracksNb = Object.keys(pendingTracks).length;\n // if any pending tracks and (if nb of pending tracks gt or equal than expected nb or if unknown expected nb)\n if (pendingTracksNb && (\n this.sourceBufferNb <= pendingTracksNb ||\n this.sourceBufferNb === 0)) {\n // ok, let's create them now !\n this.createSourceBuffers(pendingTracks);\n this.pendingTracks = {};\n // append any pending segments now !\n this.doAppending();\n }\n }\n\n onMediaSourceClose() {\n logger.log('media source closed');\n }\n\n onMediaSourceEnded() {\n logger.log('media source ended');\n }\n\n\n onSBUpdateEnd() {\n // update timestampOffset\n if (this.audioTimestampOffset) {\n let audioBuffer = this.sourceBuffer.audio;\n logger.warn('change mpeg audio timestamp offset from ' + audioBuffer.timestampOffset + ' to ' + this.audioTimestampOffset);\n audioBuffer.timestampOffset = this.audioTimestampOffset;\n delete this.audioTimestampOffset;\n }\n\n if (this._needsFlush) {\n this.doFlush();\n }\n\n if (this._needsEos) {\n this.checkEos();\n }\n this.appending = false;\n let parent = this.parent;\n // count nb of pending segments waiting for appending on this sourcebuffer\n let pending = this.segments.reduce( (counter, segment) => (segment.parent === parent) ? counter + 1 : counter , 0);\n this.hls.trigger(Event.BUFFER_APPENDED, { parent : parent, pending : pending });\n\n // don't append in flushing mode\n if (!this._needsFlush) {\n this.doAppending();\n }\n\n this.updateMediaElementDuration();\n }\n\n onSBUpdateError(event) {\n logger.error(`sourceBuffer error:${event}`);\n // according to http://www.w3.org/TR/media-source/#sourcebuffer-append-error\n // this error might not always be fatal (it is fatal if decode error is set, in that case\n // it will be followed by a mediaElement error ...)\n this.hls.trigger(Event.ERROR, {type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.BUFFER_APPENDING_ERROR, fatal: false});\n // we don't need to do more than that, as accordin to the spec, updateend will be fired just after\n }\n\n onBufferReset() {\n var sourceBuffer = this.sourceBuffer;\n for(var type in sourceBuffer) {\n var sb = sourceBuffer[type];\n try {\n this.mediaSource.removeSourceBuffer(sb);\n sb.removeEventListener('updateend', this.onsbue);\n sb.removeEventListener('error', this.onsbe);\n } catch(err) {\n }\n }\n this.sourceBuffer = {};\n this.flushRange = [];\n this.segments = [];\n this.appended = 0;\n }\n\n onBufferCodecs(tracks) {\n // if source buffer(s) not created yet, appended buffer tracks in this.pendingTracks\n // if sourcebuffers already created, do nothing ...\n if (Object.keys(this.sourceBuffer).length === 0) {\n for (var trackName in tracks) { this.pendingTracks[trackName] = tracks[trackName]; }\n let mediaSource = this.mediaSource;\n if (mediaSource && mediaSource.readyState === 'open') {\n // try to create sourcebuffers if mediasource opened\n this.checkPendingTracks();\n }\n }\n }\n\n\n createSourceBuffers(tracks) {\n var sourceBuffer = this.sourceBuffer,mediaSource = this.mediaSource;\n\n for (let trackName in tracks) {\n if(!sourceBuffer[trackName]) {\n let track = tracks[trackName];\n // use levelCodec as first priority\n let codec = track.levelCodec || track.codec;\n let mimeType = `${track.container};codecs=${codec}`;\n logger.log(`creating sourceBuffer(${mimeType})`);\n try {\n let sb = sourceBuffer[trackName] = mediaSource.addSourceBuffer(mimeType);\n sb.addEventListener('updateend', this.onsbue);\n sb.addEventListener('error', this.onsbe);\n this.tracks[trackName] = {codec: codec, container: track.container};\n track.buffer = sb;\n } catch(err) {\n logger.error(`error while trying to add sourceBuffer:${err.message}`);\n this.hls.trigger(Event.ERROR, {type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.BUFFER_ADD_CODEC_ERROR, fatal: false, err: err, mimeType : mimeType});\n }\n }\n }\n this.hls.trigger(Event.BUFFER_CREATED, { tracks : tracks } );\n }\n\n onBufferAppending(data) {\n if (!this._needsFlush) {\n if (!this.segments) {\n this.segments = [ data ];\n } else {\n this.segments.push(data);\n }\n this.doAppending();\n }\n }\n\n onBufferAppendFail(data) {\n logger.error(`sourceBuffer error:${data.event}`);\n // according to http://www.w3.org/TR/media-source/#sourcebuffer-append-error\n // this error might not always be fatal (it is fatal if decode error is set, in that case\n // it will be followed by a mediaElement error ...)\n this.hls.trigger(Event.ERROR, {type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.BUFFER_APPENDING_ERROR, fatal: false, frag: this.fragCurrent});\n }\n\n // on BUFFER_EOS mark matching sourcebuffer(s) as ended and trigger checkEos()\n onBufferEos(data) {\n var sb = this.sourceBuffer;\n let dataType = data.type;\n for(let type in sb) {\n if (!dataType || type === dataType) {\n if (!sb[type].ended) {\n sb[type].ended = true;\n logger.log(`${type} sourceBuffer now EOS`);\n }\n }\n }\n this.checkEos();\n }\n\n // if all source buffers are marked as ended, signal endOfStream() to MediaSource.\n checkEos() {\n var sb = this.sourceBuffer, mediaSource = this.mediaSource;\n if (!mediaSource || mediaSource.readyState !== 'open') {\n this._needsEos = false;\n return;\n }\n for(let type in sb) {\n let sbobj = sb[type];\n if (!sbobj.ended) {\n return;\n }\n if(sbobj.updating) {\n this._needsEos = true;\n return;\n }\n }\n logger.log('all media data available, signal endOfStream() to MediaSource and stop loading fragment');\n //Notify the media element that it now has all of the media data\n try {\n mediaSource.endOfStream();\n } catch(e) {\n logger.warn('exception while calling mediaSource.endOfStream()');\n }\n this._needsEos = false;\n }\n\n\n onBufferFlushing(data) {\n this.flushRange.push({start: data.startOffset, end: data.endOffset, type : data.type});\n // attempt flush immediatly\n this.flushBufferCounter = 0;\n this.doFlush();\n }\n\n onLevelUpdated(event) {\n let details = event.details;\n if (details.fragments.length === 0) {\n return;\n }\n this._levelDuration = details.totalduration + details.fragments[0].start;\n this.updateMediaElementDuration();\n }\n\n // https://github.com/dailymotion/hls.js/issues/355\n updateMediaElementDuration() {\n let media = this.media,\n mediaSource = this.mediaSource,\n sourceBuffer = this.sourceBuffer,\n levelDuration = this._levelDuration;\n if (levelDuration === null || !media || !mediaSource || !sourceBuffer || media.readyState === 0 || mediaSource.readyState !== 'open') {\n return;\n }\n for (let type in sourceBuffer) {\n if (sourceBuffer[type].updating) {\n // can't set duration whilst a buffer is updating\n return;\n }\n }\n if (this._msDuration === null) {\n // initialise to the value that the media source is reporting\n this._msDuration = mediaSource.duration;\n }\n let duration = media.duration;\n // levelDuration was the last value we set.\n // not using mediaSource.duration as the browser may tweak this value\n // only update mediasource duration if its value increase, this is to avoid\n // flushing already buffered portion when switching between quality level\n if ((levelDuration > this._msDuration && levelDuration > duration) || (duration === Infinity || isNaN(duration) )) {\n logger.log(`Updating mediasource duration to ${levelDuration.toFixed(3)}`);\n this._msDuration = mediaSource.duration = levelDuration;\n }\n }\n\n doFlush() {\n // loop through all buffer ranges to flush\n while(this.flushRange.length) {\n var range = this.flushRange[0];\n // flushBuffer will abort any buffer append in progress and flush Audio/Video Buffer\n if (this.flushBuffer(range.start, range.end, range.type)) {\n // range flushed, remove from flush array\n this.flushRange.shift();\n this.flushBufferCounter = 0;\n } else {\n this._needsFlush = true;\n // avoid looping, wait for SB update end to retrigger a flush\n return;\n }\n }\n if (this.flushRange.length === 0) {\n // everything flushed\n this._needsFlush = false;\n\n // let's recompute this.appended, which is used to avoid flush looping\n var appended = 0;\n var sourceBuffer = this.sourceBuffer;\n try {\n for (var type in sourceBuffer) {\n appended += sourceBuffer[type].buffered.length;\n }\n } catch(error) {\n // error could be thrown while accessing buffered, in case sourcebuffer has already been removed from MediaSource\n // this is harmess at this stage, catch this to avoid reporting an internal exception\n logger.error('error while accessing sourceBuffer.buffered');\n }\n this.appended = appended;\n this.hls.trigger(Event.BUFFER_FLUSHED);\n }\n }\n\n doAppending() {\n var hls = this.hls, sourceBuffer = this.sourceBuffer, segments = this.segments;\n if (Object.keys(sourceBuffer).length) {\n if (this.media.error) {\n this.segments = [];\n logger.error('trying to append although a media error occured, flush segment and abort');\n return;\n }\n if (this.appending) {\n //logger.log(`sb appending in progress`);\n return;\n }\n if (segments && segments.length) {\n let segment = segments.shift();\n try {\n let type = segment.type, sb = sourceBuffer[type];\n if(sb) {\n if(!sb.updating) {\n // reset sourceBuffer ended flag before appending segment\n sb.ended = false;\n //logger.log(`appending ${segment.content} ${type} SB, size:${segment.data.length}, ${segment.parent}`);\n this.parent = segment.parent;\n sb.appendBuffer(segment.data);\n this.appendError = 0;\n this.appended++;\n this.appending = true;\n } else {\n segments.unshift(segment);\n }\n } else {\n // in case we don't have any source buffer matching with this segment type,\n // it means that Mediasource fails to create sourcebuffer\n // discard this segment, and trigger update end\n this.onSBUpdateEnd();\n }\n } catch(err) {\n // in case any error occured while appending, put back segment in segments table\n logger.error(`error while trying to append buffer:${err.message}`);\n segments.unshift(segment);\n var event = {type: ErrorTypes.MEDIA_ERROR};\n if(err.code !== 22) {\n if (this.appendError) {\n this.appendError++;\n } else {\n this.appendError = 1;\n }\n event.details = ErrorDetails.BUFFER_APPEND_ERROR;\n event.frag = this.fragCurrent;\n /* with UHD content, we could get loop of quota exceeded error until\n browser is able to evict some data from sourcebuffer. retrying help recovering this\n */\n if (this.appendError > hls.config.appendErrorMaxRetry) {\n logger.log(`fail ${hls.config.appendErrorMaxRetry} times to append segment in sourceBuffer`);\n segments = [];\n event.fatal = true;\n hls.trigger(Event.ERROR, event);\n return;\n } else {\n event.fatal = false;\n hls.trigger(Event.ERROR, event);\n }\n } else {\n // QuotaExceededError: http://www.w3.org/TR/html5/infrastructure.html#quotaexceedederror\n // let's stop appending any segments, and report BUFFER_FULL_ERROR error\n this.segments = [];\n event.details = ErrorDetails.BUFFER_FULL_ERROR;\n event.fatal = false;\n hls.trigger(Event.ERROR,event);\n return;\n }\n }\n }\n }\n }\n\n /*\n flush specified buffered range,\n return true once range has been flushed.\n as sourceBuffer.remove() is asynchronous, flushBuffer will be retriggered on sourceBuffer update end\n */\n flushBuffer(startOffset, endOffset, typeIn) {\n var sb, i, bufStart, bufEnd, flushStart, flushEnd, sourceBuffer = this.sourceBuffer;\n if (Object.keys(sourceBuffer).length) {\n logger.log(`flushBuffer,pos/start/end: ${this.media.currentTime.toFixed(3)}/${startOffset}/${endOffset}`);\n // safeguard to avoid infinite looping : don't try to flush more than the nb of appended segments\n if (this.flushBufferCounter < this.appended) {\n for (var type in sourceBuffer) {\n // check if sourcebuffer type is defined (typeIn): if yes, let's only flush this one\n // if no, let's flush all sourcebuffers\n if (typeIn && type !== typeIn) {\n continue;\n }\n sb = sourceBuffer[type];\n // we are going to flush buffer, mark source buffer as 'not ended'\n sb.ended = false;\n if (!sb.updating) {\n try {\n for (i = 0; i < sb.buffered.length; i++) {\n bufStart = sb.buffered.start(i);\n bufEnd = sb.buffered.end(i);\n // workaround firefox not able to properly flush multiple buffered range.\n if (navigator.userAgent.toLowerCase().indexOf('firefox') !== -1 && endOffset === Number.POSITIVE_INFINITY) {\n flushStart = startOffset;\n flushEnd = endOffset;\n } else {\n flushStart = Math.max(bufStart, startOffset);\n flushEnd = Math.min(bufEnd, endOffset);\n }\n /* sometimes sourcebuffer.remove() does not flush\n the exact expected time range.\n to avoid rounding issues/infinite loop,\n only flush buffer range of length greater than 500ms.\n */\n if (Math.min(flushEnd,bufEnd) - flushStart > 0.5 ) {\n this.flushBufferCounter++;\n logger.log(`flush ${type} [${flushStart},${flushEnd}], of [${bufStart},${bufEnd}], pos:${this.media.currentTime}`);\n sb.remove(flushStart, flushEnd);\n return false;\n }\n }\n } catch(e) {\n logger.warn('exception while accessing sourcebuffer, it might have been removed from MediaSource');\n }\n } else {\n //logger.log('abort ' + type + ' append in progress');\n // this will abort any appending in progress\n //sb.abort();\n logger.warn('cannot flush, sb updating in progress');\n return false;\n }\n }\n } else {\n logger.warn('abort flushing too many retries');\n }\n logger.log('buffer flushed');\n }\n // everything flushed !\n return true;\n }\n}\n\nexport default BufferController;\n",
"/*\n * cap stream level to media size dimension controller\n*/\n\nimport Event from '../events';\nimport EventHandler from '../event-handler';\n\nclass CapLevelController extends EventHandler {\n\tconstructor(hls) {\n super(hls,\n Event.FPS_DROP_LEVEL_CAPPING,\n Event.MEDIA_ATTACHING,\n Event.MANIFEST_PARSED); \n\t}\n\t\n\tdestroy() {\n if (this.hls.config.capLevelToPlayerSize) {\n this.media = this.restrictedLevels = null;\n this.autoLevelCapping = Number.POSITIVE_INFINITY;\n if (this.timer) {\n this.timer = clearInterval(this.timer);\n }\n }\n }\n\t\n onFpsDropLevelCapping(data) {\n if (!this.restrictedLevels) {\n this.restrictedLevels = [];\n }\n if (!this.isLevelRestricted(data.droppedLevel)) {\n this.restrictedLevels.push(data.droppedLevel);\n }\n }\n \n\tonMediaAttaching(data) {\n this.media = data.media instanceof HTMLVideoElement ? data.media : null; \n }\n\n onManifestParsed(data) {\n if (this.hls.config.capLevelToPlayerSize) {\n this.autoLevelCapping = Number.POSITIVE_INFINITY;\n this.levels = data.levels;\n this.hls.firstLevel = this.getMaxLevel(data.firstLevel);\n clearInterval(this.timer);\n this.timer = setInterval(this.detectPlayerSize.bind(this), 1000);\n this.detectPlayerSize();\n }\n }\n \n detectPlayerSize() {\n if (this.media) {\n let levelsLength = this.levels ? this.levels.length : 0;\n if (levelsLength) {\n this.hls.autoLevelCapping = this.getMaxLevel(levelsLength - 1);\n if (this.hls.autoLevelCapping > this.autoLevelCapping) {\n // if auto level capping has a higher value for the previous one, flush the buffer using nextLevelSwitch\n // usually happen when the user go to the fullscreen mode.\n this.hls.streamController.nextLevelSwitch();\n }\n this.autoLevelCapping = this.hls.autoLevelCapping; \n } \n }\n }\n \n /*\n * returns level should be the one with the dimensions equal or greater than the media (player) dimensions (so the video will be downscaled)\n */\n getMaxLevel(capLevelIndex) {\n let result = 0,\n i,\n level,\n mWidth = this.mediaWidth,\n mHeight = this.mediaHeight,\n lWidth = 0,\n lHeight = 0;\n \n for (i = 0; i <= capLevelIndex; i++) {\n level = this.levels[i];\n if (this.isLevelRestricted(i)) {\n break;\n }\n result = i;\n lWidth = level.width;\n lHeight = level.height;\n if (mWidth <= lWidth || mHeight <= lHeight) {\n break;\n }\n } \n return result;\n }\n \n isLevelRestricted(level) {\n return (this.restrictedLevels && this.restrictedLevels.indexOf(level) !== -1) ? true : false;\n }\n \n get contentScaleFactor() {\n let pixelRatio = 1;\n try {\n pixelRatio = window.devicePixelRatio;\n } catch(e) {}\n return pixelRatio;\n }\n \n get mediaWidth() {\n let width;\n if (this.media) {\n width = this.media.width || this.media.clientWidth || this.media.offsetWidth;\n width *= this.contentScaleFactor;\n }\n return width;\n }\n \n get mediaHeight() {\n let height;\n if (this.media) {\n height = this.media.height || this.media.clientHeight || this.media.offsetHeight;\n height *= this.contentScaleFactor; \n }\n return height;\n }\n}\n\nexport default CapLevelController;",
"/*\n * EWMA Bandwidth Estimator\n * - heavily inspired from shaka-player\n * Tracks bandwidth samples and estimates available bandwidth.\n * Based on the minimum of two exponentially-weighted moving averages with\n * different half-lives.\n */\n\nimport EWMA from '../utils/ewma';\n\n\nclass EwmaBandWidthEstimator {\n\n constructor(hls,slow,fast,defaultEstimate) {\n this.hls = hls;\n this.defaultEstimate_ = defaultEstimate;\n this.minWeight_ = 0.001;\n this.minDelayMs_ = 50;\n this.slow_ = new EWMA(slow);\n this.fast_ = new EWMA(fast);\n }\n\n sample(durationMs,numBytes) {\n durationMs = Math.max(durationMs, this.minDelayMs_);\n var bandwidth = 8000* numBytes / durationMs,\n //console.log('instant bw:'+ Math.round(bandwidth));\n // we weight sample using loading duration....\n weight = durationMs / 1000;\n this.fast_.sample(weight,bandwidth);\n this.slow_.sample(weight,bandwidth);\n }\n\n canEstimate() {\n let fast = this.fast_;\n return (fast && fast.getTotalWeight() >= this.minWeight_);\n }\n\n\n getEstimate() {\n if (this.canEstimate()) {\n //console.log('slow estimate:'+ Math.round(this.slow_.getEstimate()));\n //console.log('fast estimate:'+ Math.round(this.fast_.getEstimate()));\n // Take the minimum of these two estimates. This should have the effect of\n // adapting down quickly, but up more slowly.\n return Math.min(this.fast_.getEstimate(),this.slow_.getEstimate());\n } else {\n return this.defaultEstimate_;\n }\n }\n\n destroy() {\n }\n}\nexport default EwmaBandWidthEstimator;\n\n",
"/*\n * FPS Controller\n*/\n\nimport Event from '../events';\nimport EventHandler from '../event-handler';\nimport {logger} from '../utils/logger';\n\nclass FPSController extends EventHandler{\n\n constructor(hls) {\n super(hls, Event.MEDIA_ATTACHING);\n }\n\n destroy() {\n if (this.timer) {\n clearInterval(this.timer);\n }\n this.isVideoPlaybackQualityAvailable = false;\n }\n \n onMediaAttaching(data) {\n if (this.hls.config.capLevelOnFPSDrop) {\n this.video = data.media instanceof HTMLVideoElement ? data.media : null;\n if (typeof this.video.getVideoPlaybackQuality === 'function') {\n this.isVideoPlaybackQualityAvailable = true;\n }\n clearInterval(this.timer);\n this.timer = setInterval(this.checkFPSInterval.bind(this), this.hls.config.fpsDroppedMonitoringPeriod);\n } \n }\n \n checkFPS(video, decodedFrames, droppedFrames) {\n let currentTime = performance.now();\n if (decodedFrames) {\n if (this.lastTime) {\n let currentPeriod = currentTime - this.lastTime,\n currentDropped = droppedFrames - this.lastDroppedFrames,\n currentDecoded = decodedFrames - this.lastDecodedFrames,\n droppedFPS = 1000 * currentDropped / currentPeriod;\n this.hls.trigger(Event.FPS_DROP, {currentDropped: currentDropped, currentDecoded: currentDecoded, totalDroppedFrames: droppedFrames});\n if (droppedFPS > 0) {\n //logger.log('checkFPS : droppedFPS/decodedFPS:' + droppedFPS/(1000 * currentDecoded / currentPeriod));\n if (currentDropped > this.hls.config.fpsDroppedMonitoringThreshold * currentDecoded) {\n let currentLevel = this.hls.currentLevel;\n logger.warn('drop FPS ratio greater than max allowed value for currentLevel: ' + currentLevel);\n if (currentLevel > 0 && (this.hls.autoLevelCapping === -1 || this.hls.autoLevelCapping >= currentLevel)) {\n currentLevel = currentLevel - 1;\n this.hls.trigger(Event.FPS_DROP_LEVEL_CAPPING, {level: currentLevel, droppedLevel: this.hls.currentLevel});\n this.hls.autoLevelCapping = currentLevel;\n this.hls.streamController.nextLevelSwitch();\n }\n }\n }\n }\n this.lastTime = currentTime;\n this.lastDroppedFrames = droppedFrames;\n this.lastDecodedFrames = decodedFrames;\n }\n }\n \n checkFPSInterval() {\n if (this.video) {\n if (this.isVideoPlaybackQualityAvailable) {\n let videoPlaybackQuality = this.video.getVideoPlaybackQuality();\n this.checkFPS(this.video, videoPlaybackQuality.totalVideoFrames, videoPlaybackQuality.droppedVideoFrames);\n } else {\n this.checkFPS(this.video, this.video.webkitDecodedFrameCount, this.video.webkitDroppedFrameCount); \n }\n }\n } \n}\n\nexport default FPSController;\n\n",
"/*\n * Level Controller\n*/\n\nimport Event from '../events';\nimport EventHandler from '../event-handler';\nimport {logger} from '../utils/logger';\nimport {ErrorTypes, ErrorDetails} from '../errors';\nimport BufferHelper from '../helper/buffer-helper';\n\nclass LevelController extends EventHandler {\n\n constructor(hls) {\n super(hls,\n Event.MANIFEST_LOADED,\n Event.LEVEL_LOADED,\n Event.FRAG_LOADED,\n Event.ERROR);\n this.ontick = this.tick.bind(this);\n this._manualLevel = this._autoLevelCapping = -1;\n }\n\n destroy() {\n if (this.timer) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n this._manualLevel = -1;\n }\n\n startLoad() {\n this.canload = true;\n let levels = this._levels;\n // clean up live level details to force reload them, and reset load errors\n if(levels) {\n levels.forEach(level => {\n level.loadError = 0;\n const levelDetails = level.details;\n if (levelDetails && levelDetails.live) {\n level.details = undefined;\n }\n });\n }\n // speed up live playlist refresh if timer exists\n if (this.timer) {\n this.tick();\n }\n }\n\n stopLoad() {\n this.canload = false;\n }\n\n onManifestLoaded(data) {\n var levels0 = [],\n levels = [],\n bitrateStart,\n bitrateSet = {},\n videoCodecFound = false,\n audioCodecFound = false,\n hls = this.hls,\n brokenmp4inmp3 = /chrome|firefox/.test(navigator.userAgent.toLowerCase()),\n checkSupported = function(type,codec) { return MediaSource.isTypeSupported(`${type}/mp4;codecs=${codec}`);};\n\n // regroup redundant level together\n data.levels.forEach(level => {\n if(level.videoCodec) {\n videoCodecFound = true;\n }\n // erase audio codec info if browser does not support mp4a.40.34. demuxer will autodetect codec and fallback to mpeg/audio\n if(brokenmp4inmp3 && level.audioCodec && level.audioCodec.indexOf('mp4a.40.34') !== -1) {\n level.audioCodec = undefined;\n }\n if(level.audioCodec || (level.attrs && level.attrs.AUDIO)) {\n audioCodecFound = true;\n }\n let redundantLevelId = bitrateSet[level.bitrate];\n if (redundantLevelId === undefined) {\n bitrateSet[level.bitrate] = levels0.length;\n level.url = [level.url];\n level.urlId = 0;\n levels0.push(level);\n } else {\n levels0[redundantLevelId].url.push(level.url);\n }\n });\n\n // remove audio-only level if we also have levels with audio+video codecs signalled\n if(videoCodecFound && audioCodecFound) {\n levels0.forEach(level => {\n if(level.videoCodec) {\n levels.push(level);\n }\n });\n } else {\n levels = levels0;\n }\n // only keep level with supported audio/video codecs\n levels = levels.filter(function(level) {\n let audioCodec = level.audioCodec, videoCodec = level.videoCodec;\n return (!audioCodec || checkSupported('audio',audioCodec)) &&\n (!videoCodec || checkSupported('video',videoCodec));\n });\n\n if(levels.length) {\n // start bitrate is the first bitrate of the manifest\n bitrateStart = levels[0].bitrate;\n // sort level on bitrate\n levels.sort(function (a, b) {\n return a.bitrate - b.bitrate;\n });\n this._levels = levels;\n // find index of first level in sorted levels\n for (let i = 0; i < levels.length; i++) {\n if (levels[i].bitrate === bitrateStart) {\n this._firstLevel = i;\n logger.log(`manifest loaded,${levels.length} level(s) found, first bitrate:${bitrateStart}`);\n break;\n }\n }\n hls.trigger(Event.MANIFEST_PARSED, {levels: levels, firstLevel: this._firstLevel, stats: data.stats, audio : audioCodecFound, video : videoCodecFound, altAudio : data.audioTracks.length > 0});\n } else {\n hls.trigger(Event.ERROR, {type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.MANIFEST_INCOMPATIBLE_CODECS_ERROR, fatal: true, url: hls.url, reason: 'no level with compatible codecs found in manifest'});\n }\n return;\n }\n\n get levels() {\n return this._levels;\n }\n\n get level() {\n return this._level;\n }\n\n set level(newLevel) {\n let levels = this._levels;\n if (levels && levels.length > newLevel) {\n if (this._level !== newLevel || levels[newLevel].details === undefined) {\n this.setLevelInternal(newLevel);\n }\n }\n }\n\n setLevelInternal(newLevel) {\n let levels = this._levels;\n // check if level idx is valid\n if (newLevel >= 0 && newLevel < levels.length) {\n // stopping live reloading timer if any\n if (this.timer) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n if (this._level !== newLevel) {\n logger.log(`switching to level ${newLevel}`);\n this._level = newLevel;\n this.hls.trigger(Event.LEVEL_SWITCH, {level: newLevel});\n }\n var level = levels[newLevel], levelDetails = level.details;\n // check if we need to load playlist for this level\n if (!levelDetails || levelDetails.live === true) {\n // level not retrieved yet, or live playlist we need to (re)load it\n var urlId = level.urlId;\n this.hls.trigger(Event.LEVEL_LOADING, {url: level.url[urlId], level: newLevel, id: urlId});\n }\n } else {\n // invalid level id given, trigger error\n this.hls.trigger(Event.ERROR, {type : ErrorTypes.OTHER_ERROR, details: ErrorDetails.LEVEL_SWITCH_ERROR, level: newLevel, fatal: false, reason: 'invalid level idx'});\n }\n }\n\n get manualLevel() {\n return this._manualLevel;\n }\n\n set manualLevel(newLevel) {\n this._manualLevel = newLevel;\n if (this._startLevel === undefined) {\n this._startLevel = newLevel;\n }\n if (newLevel !== -1) {\n this.level = newLevel;\n }\n }\n\n get firstLevel() {\n return this._firstLevel;\n }\n\n set firstLevel(newLevel) {\n this._firstLevel = newLevel;\n }\n\n get startLevel() {\n // hls.startLevel takes precedence over config.startLevel\n // if none of these values are defined, fallback on this._firstLevel (first quality level appearing in variant manifest)\n if (this._startLevel === undefined) {\n let configStartLevel = this.hls.config.startLevel;\n if (configStartLevel !== undefined) {\n return configStartLevel;\n } else {\n return this._firstLevel;\n }\n } else {\n return this._startLevel;\n }\n }\n\n set startLevel(newLevel) {\n // if not in autostart level, ensure startLevel is greater than minAutoLevel\n if (newLevel !== -1) {\n newLevel = Math.max(newLevel, this.hls.abrController.minAutoLevel);\n }\n this._startLevel = newLevel;\n }\n\n onError(data) {\n if(data.fatal) {\n return;\n }\n\n let details = data.details, hls = this.hls, levelId, level, levelError = false, abrController = hls.abrController, minAutoLevel = abrController.minAutoLevel;\n // try to recover not fatal errors\n switch(details) {\n case ErrorDetails.FRAG_LOAD_ERROR:\n case ErrorDetails.FRAG_LOAD_TIMEOUT:\n case ErrorDetails.FRAG_LOOP_LOADING_ERROR:\n case ErrorDetails.KEY_LOAD_ERROR:\n case ErrorDetails.KEY_LOAD_TIMEOUT:\n levelId = data.frag.level;\n break;\n case ErrorDetails.LEVEL_LOAD_ERROR:\n case ErrorDetails.LEVEL_LOAD_TIMEOUT:\n levelId = data.context.level;\n levelError = true;\n break;\n case ErrorDetails.REMUX_ALLOC_ERROR:\n levelId = data.level;\n break;\n default:\n break;\n }\n /* try to switch to a redundant stream if any available.\n * if no redundant stream available, emergency switch down (if in auto mode and current level not 0)\n * otherwise, we cannot recover this network error ...\n */\n if (levelId !== undefined) {\n level = this._levels[levelId];\n if(!level.loadError) {\n level.loadError = 1;\n } else {\n level.loadError++;\n }\n // if any redundant streams available and if we haven't try them all (level.loadError is reseted on successful frag/level load.\n // if level.loadError reaches nbRedundantLevel it means that we tried them all, no hope => let's switch down\n const nbRedundantLevel = level.url.length;\n if (nbRedundantLevel > 1 && level.loadError < nbRedundantLevel) {\n level.urlId = (level.urlId + 1) % nbRedundantLevel;\n level.details = undefined;\n logger.warn(`level controller,${details} for level ${levelId}: switching to redundant stream id ${level.urlId}`);\n } else {\n // we could try to recover if in auto mode and current level not lowest level (0)\n let recoverable = ((this._manualLevel === -1) && levelId);\n if (recoverable) {\n logger.warn(`level controller,${details}: switch-down for next fragment`);\n abrController.nextAutoLevel = Math.max(minAutoLevel,levelId-1);\n } else if(level && level.details && level.details.live) {\n logger.warn(`level controller,${details} on live stream, discard`);\n if (levelError) {\n // reset this._level so that another call to set level() will retrigger a frag load\n this._level = undefined;\n }\n // other errors are handled by stream controller\n } else if (details === ErrorDetails.LEVEL_LOAD_ERROR ||\n details === ErrorDetails.LEVEL_LOAD_TIMEOUT) {\n let media = hls.media,\n // 0.5 : tolerance needed as some browsers stalls playback before reaching buffered end\n mediaBuffered = media && BufferHelper.isBuffered(media,media.currentTime) && BufferHelper.isBuffered(media,media.currentTime+0.5);\n if (mediaBuffered) {\n let retryDelay = hls.config.levelLoadingRetryDelay;\n logger.warn(`level controller,${details}, but media buffered, retry in ${retryDelay}ms`);\n this.timer = setTimeout(this.ontick,retryDelay);\n } else {\n logger.error(`cannot recover ${details} error`);\n this._level = undefined;\n // stopping live reloading timer if any\n if (this.timer) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n // redispatch same error but with fatal set to true\n data.fatal = true;\n hls.trigger(Event.ERROR, data);\n }\n }\n }\n }\n }\n\n // reset level load error counter on successful frag loaded\n onFragLoaded(data) {\n const fragLoaded = data.frag;\n if (fragLoaded && fragLoaded.type === 'main') {\n const level = this._levels[fragLoaded.level];\n if (level) {\n level.loadError = 0;\n }\n }\n }\n\n onLevelLoaded(data) {\n const levelId = data.level;\n // only process level loaded events matching with expected level\n if (levelId === this._level) {\n let curLevel = this._levels[levelId];\n // reset level load error counter on successful level loaded\n curLevel.loadError = 0;\n let newDetails = data.details;\n // if current playlist is a live playlist, arm a timer to reload it\n if (newDetails.live) {\n let reloadInterval = 1000*( newDetails.averagetargetduration ? newDetails.averagetargetduration : newDetails.targetduration),\n curDetails = curLevel.details;\n if (curDetails && newDetails.endSN === curDetails.endSN) {\n // follow HLS Spec, If the client reloads a Playlist file and finds that it has not\n // changed then it MUST wait for a period of one-half the target\n // duration before retrying.\n reloadInterval /=2;\n logger.log(`same live playlist, reload twice faster`);\n }\n // decrement reloadInterval with level loading delay\n reloadInterval -= performance.now() - data.stats.trequest;\n // in any case, don't reload more than every second\n reloadInterval = Math.max(1000,Math.round(reloadInterval));\n logger.log(`live playlist, reload in ${reloadInterval} ms`);\n this.timer = setTimeout(this.ontick,reloadInterval);\n } else {\n this.timer = null;\n }\n }\n }\n\n tick() {\n var levelId = this._level;\n if (levelId !== undefined && this.canload) {\n var level = this._levels[levelId], urlId = level.urlId;\n this.hls.trigger(Event.LEVEL_LOADING, {url: level.url[urlId], level: levelId, id: urlId});\n }\n }\n\n get nextLoadLevel() {\n if (this._manualLevel !== -1) {\n return this._manualLevel;\n } else {\n return this.hls.abrController.nextAutoLevel;\n }\n }\n\n set nextLoadLevel(nextLevel) {\n this.level = nextLevel;\n if (this._manualLevel === -1) {\n this.hls.abrController.nextAutoLevel = nextLevel;\n }\n }\n}\n\nexport default LevelController;\n\n",
"/*\n * Stream Controller\n*/\n\nimport BinarySearch from '../utils/binary-search';\nimport BufferHelper from '../helper/buffer-helper';\nimport Demuxer from '../demux/demuxer';\nimport Event from '../events';\nimport EventHandler from '../event-handler';\nimport LevelHelper from '../helper/level-helper';\nimport TimeRanges from '../utils/timeRanges';\nimport {ErrorTypes, ErrorDetails} from '../errors';\nimport {logger} from '../utils/logger';\n\nconst State = {\n STOPPED : 'STOPPED',\n IDLE : 'IDLE',\n KEY_LOADING : 'KEY_LOADING',\n FRAG_LOADING : 'FRAG_LOADING',\n FRAG_LOADING_WAITING_RETRY : 'FRAG_LOADING_WAITING_RETRY',\n WAITING_LEVEL : 'WAITING_LEVEL',\n PARSING : 'PARSING',\n PARSED : 'PARSED',\n BUFFER_FLUSHING : 'BUFFER_FLUSHING',\n ENDED : 'ENDED',\n ERROR : 'ERROR'\n};\n\nclass StreamController extends EventHandler {\n\n constructor(hls) {\n super(hls,\n Event.MEDIA_ATTACHED,\n Event.MEDIA_DETACHING,\n Event.MANIFEST_LOADING,\n Event.MANIFEST_PARSED,\n Event.LEVEL_LOADED,\n Event.KEY_LOADED,\n Event.FRAG_LOADED,\n Event.FRAG_LOAD_EMERGENCY_ABORTED,\n Event.FRAG_PARSING_INIT_SEGMENT,\n Event.FRAG_PARSING_DATA,\n Event.FRAG_PARSED,\n Event.ERROR,\n Event.AUDIO_TRACK_SWITCHING,\n Event.AUDIO_TRACK_SWITCHED,\n Event.BUFFER_CREATED,\n Event.BUFFER_APPENDED,\n Event.BUFFER_FLUSHED);\n\n this.config = hls.config;\n this.audioCodecSwap = false;\n this.ticks = 0;\n this.ontick = this.tick.bind(this);\n }\n\n destroy() {\n this.stopLoad();\n if (this.timer) {\n clearInterval(this.timer);\n this.timer = null;\n }\n EventHandler.prototype.destroy.call(this);\n this.state = State.STOPPED;\n }\n\n startLoad(startPosition) {\n if (this.levels) {\n let lastCurrentTime = this.lastCurrentTime, hls = this.hls;\n this.stopLoad();\n if (!this.timer) {\n this.timer = setInterval(this.ontick, 100);\n }\n this.level = -1;\n this.fragLoadError = 0;\n if (!this.startFragRequested) {\n // determine load level\n let startLevel = hls.startLevel;\n if (startLevel === -1) {\n // -1 : guess start Level by doing a bitrate test by loading first fragment of lowest quality level\n startLevel = 0;\n this.bitrateTest = true;\n }\n // set new level to playlist loader : this will trigger start level load\n // hls.nextLoadLevel remains until it is set to a new value or until a new frag is successfully loaded\n this.level = hls.nextLoadLevel = startLevel;\n this.loadedmetadata = false;\n }\n // if startPosition undefined but lastCurrentTime set, set startPosition to last currentTime\n if (lastCurrentTime > 0 && startPosition === -1) {\n logger.log(`override startPosition with lastCurrentTime @${lastCurrentTime.toFixed(3)}`);\n startPosition = lastCurrentTime;\n }\n this.state = State.IDLE;\n this.nextLoadPosition = this.startPosition = this.lastCurrentTime = startPosition;\n this.tick();\n } else {\n logger.warn('cannot start loading as manifest not parsed yet');\n this.state = State.STOPPED;\n }\n }\n\n stopLoad() {\n var frag = this.fragCurrent;\n if (frag) {\n if (frag.loader) {\n frag.loader.abort();\n }\n this.fragCurrent = null;\n }\n this.fragPrevious = null;\n if (this.demuxer) {\n this.demuxer.destroy();\n this.demuxer = null;\n }\n this.state = State.STOPPED;\n }\n\n tick() {\n this.ticks++;\n if (this.ticks === 1) {\n this.doTick();\n if (this.ticks > 1) {\n setTimeout(this.tick, 1);\n }\n this.ticks = 0;\n }\n }\n\n doTick() {\n switch(this.state) {\n case State.ERROR:\n //don't do anything in error state to avoid breaking further ...\n break;\n case State.BUFFER_FLUSHING:\n // in buffer flushing state, reset fragLoadError counter\n this.fragLoadError = 0;\n break;\n case State.IDLE:\n // when this returns false there was an error and we shall return immediatly\n // from current tick\n if (!this._doTickIdle()) {\n return;\n }\n break;\n case State.WAITING_LEVEL:\n var level = this.levels[this.level];\n // check if playlist is already loaded\n if (level && level.details) {\n this.state = State.IDLE;\n }\n break;\n case State.FRAG_LOADING_WAITING_RETRY:\n var now = performance.now();\n var retryDate = this.retryDate;\n // if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading\n if(!retryDate || (now >= retryDate) || (this.media && this.media.seeking)) {\n logger.log(`mediaController: retryDate reached, switch back to IDLE state`);\n this.state = State.IDLE;\n }\n break;\n case State.ERROR:\n case State.STOPPED:\n case State.FRAG_LOADING:\n case State.PARSING:\n case State.PARSED:\n case State.ENDED:\n break;\n default:\n break;\n }\n // check buffer\n this._checkBuffer();\n // check/update current fragment\n this._checkFragmentChanged();\n }\n\n // Ironically the \"idle\" state is the on we do the most logic in it seems ....\n // NOTE: Maybe we could rather schedule a check for buffer length after half of the currently\n // played segment, or on pause/play/seek instead of naively checking every 100ms?\n _doTickIdle() {\n const hls = this.hls,\n config = hls.config,\n media = this.media;\n\n // if video not attached AND\n // start fragment already requested OR start frag prefetch disable\n // exit loop\n // => if start level loaded and media not attached but start frag prefetch is enabled and start frag not requested yet, we will not exit loop\n if (this.levelLastLoaded !== undefined && !media &&\n (this.startFragRequested || !config.startFragPrefetch)) {\n return true;\n }\n\n // if we have not yet loaded any fragment, start loading from start position\n let pos;\n if (this.loadedmetadata) {\n pos = media.currentTime;\n } else {\n pos = this.nextLoadPosition;\n }\n // determine next load level\n let level = hls.nextLoadLevel,\n levelInfo = this.levels[level],\n levelBitrate = levelInfo.bitrate,\n maxBufLen;\n\n // compute max Buffer Length that we could get from this load level, based on level bitrate. don't buffer more than 60 MB and more than 30s\n if (levelBitrate) {\n maxBufLen = Math.max(8 * config.maxBufferSize / levelBitrate, config.maxBufferLength);\n } else {\n maxBufLen = config.maxBufferLength;\n }\n maxBufLen = Math.min(maxBufLen, config.maxMaxBufferLength);\n\n // determine next candidate fragment to be loaded, based on current position and end of buffer position\n // ensure up to `config.maxMaxBufferLength` of buffer upfront\n\n const bufferInfo = BufferHelper.bufferInfo(this.mediaBuffer ? this.mediaBuffer : media, pos, config.maxBufferHole),\n bufferLen = bufferInfo.len;\n // Stay idle if we are still with buffer margins\n if (bufferLen >= maxBufLen) {\n return true;\n }\n\n // if buffer length is less than maxBufLen try to load a new fragment ...\n logger.trace(`buffer length of ${bufferLen.toFixed(3)} is below max of ${maxBufLen.toFixed(3)}. checking for more payload ...`);\n\n // set next load level : this will trigger a playlist load if needed\n this.level = hls.nextLoadLevel = level;\n\n const levelDetails = levelInfo.details;\n // if level info not retrieved yet, switch state and wait for level retrieval\n // if live playlist, ensure that new playlist has been refreshed to avoid loading/try to load\n // a useless and outdated fragment (that might even introduce load error if it is already out of the live playlist)\n if (typeof levelDetails === 'undefined' || levelDetails.live && this.levelLastLoaded !== level) {\n this.state = State.WAITING_LEVEL;\n return true;\n }\n\n // we just got done loading the final fragment, check if we need to finalize media stream\n let fragPrevious = this.fragPrevious;\n if (!levelDetails.live && fragPrevious && fragPrevious.sn === levelDetails.endSN) {\n // if (we are not seeking AND current position is buffered) OR (if we are seeking but everything (almost) til the end is buffered), let's signal eos\n // we don't compare exactly media.duration === bufferInfo.end as there could be some subtle media duration difference when switching\n // between different renditions. using half frag duration should help cope with these cases.\n if ((!media.seeking && bufferInfo.len) || (media.duration-bufferInfo.end) <= fragPrevious.duration/2) {\n // Finalize the media stream\n let data = {};\n if (this.altAudio) {\n data.type = 'video';\n }\n this.hls.trigger(Event.BUFFER_EOS,data);\n this.state = State.ENDED;\n return true;\n }\n }\n\n // if we have the levelDetails for the selected variant, lets continue enrichen our stream (load keys/fragments or trigger EOS, etc..)\n return this._fetchPayloadOrEos({pos, bufferInfo, levelDetails});\n }\n\n _fetchPayloadOrEos({pos, bufferInfo, levelDetails}) {\n const fragPrevious = this.fragPrevious,\n level = this.level,\n fragments = levelDetails.fragments,\n fragLen = fragments.length;\n\n // empty playlist\n if (fragLen === 0) {\n return false;\n }\n\n // find fragment index, contiguous with end of buffer position\n let start = fragments[0].start,\n end = fragments[fragLen-1].start + fragments[fragLen-1].duration,\n bufferEnd = bufferInfo.end,\n frag;\n\n // in case of live playlist we need to ensure that requested position is not located before playlist start\n if (levelDetails.live) {\n let initialLiveManifestSize = this.config.initialLiveManifestSize;\n if(fragLen < initialLiveManifestSize){\n logger.warn(`Can not start playback of a level, reason: not enough fragments ${fragLen} < ${initialLiveManifestSize}`);\n return false;\n }\n\n frag = this._ensureFragmentAtLivePoint({levelDetails, bufferEnd, start, end, fragPrevious, fragments, fragLen});\n // if it explicitely returns null don't load any fragment and exit function now\n if (frag === null) {\n return false;\n }\n\n } else {\n // VoD playlist: if bufferEnd before start of playlist, load first fragment\n if (bufferEnd < start) {\n frag = fragments[0];\n }\n }\n if (!frag) {\n frag = this._findFragment({start, fragPrevious, fragLen, fragments, bufferEnd, end, levelDetails});\n }\n if(frag) {\n return this._loadFragmentOrKey({frag, level, levelDetails, pos, bufferEnd});\n }\n return true;\n }\n\n _ensureFragmentAtLivePoint({levelDetails, bufferEnd, start, end, fragPrevious, fragments, fragLen}) {\n const config = this.hls.config, media = this.media;\n\n let frag;\n\n // check if requested position is within seekable boundaries :\n //logger.log(`start/pos/bufEnd/seeking:${start.toFixed(3)}/${pos.toFixed(3)}/${bufferEnd.toFixed(3)}/${this.media.seeking}`);\n let maxLatency = config.liveMaxLatencyDuration !== undefined ? config.liveMaxLatencyDuration : config.liveMaxLatencyDurationCount*levelDetails.targetduration;\n\n if (bufferEnd < Math.max(start, end - maxLatency)) {\n let liveSyncPosition = this.liveSyncPosition = this.computeLivePosition(start, levelDetails);\n logger.log(`buffer end: ${bufferEnd.toFixed(3)} is located too far from the end of live sliding playlist, reset currentTime to : ${liveSyncPosition.toFixed(3)}`);\n bufferEnd = liveSyncPosition;\n if (media && media.readyState && media.duration > liveSyncPosition) {\n media.currentTime = liveSyncPosition;\n }\n }\n\n // if end of buffer greater than live edge, don't load any fragment\n // this could happen if live playlist intermittently slides in the past.\n // level 1 loaded [182580161,182580167]\n // level 1 loaded [182580162,182580169]\n // Loading 182580168 of [182580162 ,182580169],level 1 ..\n // Loading 182580169 of [182580162 ,182580169],level 1 ..\n // level 1 loaded [182580162,182580168] <============= here we should have bufferEnd > end. in that case break to avoid reloading 182580168\n // level 1 loaded [182580164,182580171]\n //\n // don't return null in case media not loaded yet (readystate === 0)\n if (levelDetails.PTSKnown && bufferEnd > end && media && media.readyState) {\n return null;\n }\n\n if (this.startFragRequested && !levelDetails.PTSKnown) {\n /* we are switching level on live playlist, but we don't have any PTS info for that quality level ...\n try to load frag matching with next SN.\n even if SN are not synchronized between playlists, loading this frag will help us\n compute playlist sliding and find the right one after in case it was not the right consecutive one */\n if (fragPrevious) {\n var targetSN = fragPrevious.sn + 1;\n if (targetSN >= levelDetails.startSN && targetSN <= levelDetails.endSN) {\n frag = fragments[targetSN - levelDetails.startSN];\n logger.log(`live playlist, switching playlist, load frag with next SN: ${frag.sn}`);\n }\n }\n if (!frag) {\n /* we have no idea about which fragment should be loaded.\n so let's load mid fragment. it will help computing playlist sliding and find the right one\n */\n frag = fragments[Math.min(fragLen - 1, Math.round(fragLen / 2))];\n logger.log(`live playlist, switching playlist, unknown, load middle frag : ${frag.sn}`);\n }\n }\n return frag;\n }\n\n _findFragment({start, fragPrevious, fragLen, fragments, bufferEnd, end, levelDetails}) {\n const config = this.hls.config;\n\n let frag,\n foundFrag,\n maxFragLookUpTolerance = config.maxFragLookUpTolerance;\n\n if (bufferEnd < end) {\n if (bufferEnd > end - maxFragLookUpTolerance) {\n maxFragLookUpTolerance = 0;\n }\n foundFrag = BinarySearch.search(fragments, (candidate) => {\n // offset should be within fragment boundary - config.maxFragLookUpTolerance\n // this is to cope with situations like\n // bufferEnd = 9.991\n // frag[Ø] : [0,10]\n // frag[1] : [10,20]\n // bufferEnd is within frag[0] range ... although what we are expecting is to return frag[1] here\n // frag start frag start+duration\n // |-----------------------------|\n // <---> <--->\n // ...--------><-----------------------------><---------....\n // previous frag matching fragment next frag\n // return -1 return 0 return 1\n //logger.log(`level/sn/start/end/bufEnd:${level}/${candidate.sn}/${candidate.start}/${(candidate.start+candidate.duration)}/${bufferEnd}`);\n if ((candidate.start + candidate.duration - maxFragLookUpTolerance) <= bufferEnd) {\n return 1;\n }// if maxFragLookUpTolerance will have negative value then don't return -1 for first element\n else if (candidate.start - maxFragLookUpTolerance > bufferEnd && candidate.start) {\n return -1;\n }\n return 0;\n });\n } else {\n // reach end of playlist\n foundFrag = fragments[fragLen-1];\n }\n if (foundFrag) {\n frag = foundFrag;\n start = foundFrag.start;\n //logger.log('find SN matching with pos:' + bufferEnd + ':' + frag.sn);\n if (fragPrevious && frag.level === fragPrevious.level && frag.sn === fragPrevious.sn) {\n if (frag.sn < levelDetails.endSN) {\n let deltaPTS = fragPrevious.deltaPTS,\n curSNIdx = frag.sn - levelDetails.startSN;\n // if there is a significant delta between audio and video, larger than max allowed hole,\n // and if previous remuxed fragment did not start with a keyframe. (fragPrevious.dropped)\n // let's try to load previous fragment again to get last keyframe\n // then we will reload again current fragment (that way we should be able to fill the buffer hole ...)\n if (deltaPTS && deltaPTS > config.maxBufferHole && fragPrevious.dropped && curSNIdx) {\n frag = fragments[curSNIdx-1];\n logger.warn(`SN just loaded, with large PTS gap between audio and video, maybe frag is not starting with a keyframe ? load previous one to try to overcome this`);\n // decrement previous frag load counter to avoid frag loop loading error when next fragment will get reloaded\n fragPrevious.loadCounter--;\n } else {\n frag = fragments[curSNIdx+1];\n logger.log(`SN just loaded, load next one: ${frag.sn}`);\n }\n } else {\n frag = null;\n }\n }\n }\n return frag;\n }\n\n _loadFragmentOrKey({frag, level, levelDetails, pos, bufferEnd}) {\n const hls = this.hls,\n config = hls.config;\n\n //logger.log('loading frag ' + i +',pos/bufEnd:' + pos.toFixed(3) + '/' + bufferEnd.toFixed(3));\n if ((frag.decryptdata.uri != null) && (frag.decryptdata.key == null)) {\n logger.log(`Loading key for ${frag.sn} of [${levelDetails.startSN} ,${levelDetails.endSN}],level ${level}`);\n this.state = State.KEY_LOADING;\n hls.trigger(Event.KEY_LOADING, {frag: frag});\n } else {\n logger.log(`Loading ${frag.sn} of [${levelDetails.startSN} ,${levelDetails.endSN}],level ${level}, currentTime:${pos.toFixed(3)},bufferEnd:${bufferEnd.toFixed(3)}`);\n // ensure that we are not reloading the same fragments in loop ...\n if (this.fragLoadIdx !== undefined) {\n this.fragLoadIdx++;\n } else {\n this.fragLoadIdx = 0;\n }\n if (frag.loadCounter) {\n frag.loadCounter++;\n let maxThreshold = config.fragLoadingLoopThreshold;\n // if this frag has already been loaded 3 times, and if it has been reloaded recently\n if (frag.loadCounter > maxThreshold && (Math.abs(this.fragLoadIdx - frag.loadIdx) < maxThreshold)) {\n hls.trigger(Event.ERROR, {type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.FRAG_LOOP_LOADING_ERROR, fatal: false, frag: frag});\n return false;\n }\n } else {\n frag.loadCounter = 1;\n }\n frag.loadIdx = this.fragLoadIdx;\n this.fragCurrent = frag;\n this.startFragRequested = true;\n this.nextLoadPosition = frag.start + frag.duration;\n frag.autoLevel = hls.autoLevelEnabled;\n frag.bitrateTest = this.bitrateTest;\n hls.trigger(Event.FRAG_LOADING, {frag: frag});\n // lazy demuxer init, as this could take some time ... do it during frag loading\n if (!this.demuxer) {\n this.demuxer = new Demuxer(hls,'main');\n }\n this.state = State.FRAG_LOADING;\n return true;\n }\n }\n\n set state(nextState) {\n if (this.state !== nextState) {\n const previousState = this.state;\n this._state = nextState;\n logger.log(`engine state transition from ${previousState} to ${nextState}`);\n this.hls.trigger(Event.STREAM_STATE_TRANSITION, {previousState, nextState});\n }\n }\n\n get state() {\n return this._state;\n }\n\n getBufferRange(position) {\n var i, range,\n bufferRange = this.bufferRange;\n if (bufferRange) {\n for (i = bufferRange.length - 1; i >=0; i--) {\n range = bufferRange[i];\n if (position >= range.start && position <= range.end) {\n return range;\n }\n }\n }\n return null;\n }\n\n get currentLevel() {\n let media = this.media;\n if (media) {\n var range = this.getBufferRange(media.currentTime);\n if (range) {\n return range.frag.level;\n }\n }\n return -1;\n }\n\n get nextBufferRange() {\n let media = this.media;\n if (media) {\n // first get end range of current fragment\n return this.followingBufferRange(this.getBufferRange(media.currentTime));\n } else {\n return null;\n }\n }\n\n followingBufferRange(range) {\n if (range) {\n // try to get range of next fragment (500ms after this range)\n return this.getBufferRange(range.end + 0.5);\n }\n return null;\n }\n\n get nextLevel() {\n var range = this.nextBufferRange;\n if (range) {\n return range.frag.level;\n } else {\n return -1;\n }\n }\n\n _checkFragmentChanged() {\n var rangeCurrent, currentTime, video = this.media;\n if (video && video.readyState && video.seeking === false) {\n currentTime = video.currentTime;\n /* if video element is in seeked state, currentTime can only increase.\n (assuming that playback rate is positive ...)\n As sometimes currentTime jumps back to zero after a\n media decode error, check this, to avoid seeking back to\n wrong position after a media decode error\n */\n if(currentTime > video.playbackRate*this.lastCurrentTime) {\n this.lastCurrentTime = currentTime;\n }\n if (BufferHelper.isBuffered(video,currentTime)) {\n rangeCurrent = this.getBufferRange(currentTime);\n } else if (BufferHelper.isBuffered(video,currentTime + 0.1)) {\n /* ensure that FRAG_CHANGED event is triggered at startup,\n when first video frame is displayed and playback is paused.\n add a tolerance of 100ms, in case current position is not buffered,\n check if current pos+100ms is buffered and use that buffer range\n for FRAG_CHANGED event reporting */\n rangeCurrent = this.getBufferRange(currentTime + 0.1);\n }\n if (rangeCurrent) {\n var fragPlaying = rangeCurrent.frag;\n if (fragPlaying !== this.fragPlaying) {\n this.fragPlaying = fragPlaying;\n this.hls.trigger(Event.FRAG_CHANGED, {frag: fragPlaying});\n }\n }\n }\n }\n\n /*\n on immediate level switch :\n - pause playback if playing\n - cancel any pending load request\n - and trigger a buffer flush\n */\n immediateLevelSwitch() {\n logger.log('immediateLevelSwitch');\n if (!this.immediateSwitch) {\n this.immediateSwitch = true;\n let media = this.media, previouslyPaused;\n if (media) {\n previouslyPaused = media.paused;\n media.pause();\n } else {\n // don't restart playback after instant level switch in case media not attached\n previouslyPaused = true;\n }\n this.previouslyPaused = previouslyPaused;\n }\n var fragCurrent = this.fragCurrent;\n if (fragCurrent && fragCurrent.loader) {\n fragCurrent.loader.abort();\n }\n this.fragCurrent = null;\n // increase fragment load Index to avoid frag loop loading error after buffer flush\n this.fragLoadIdx += 2 * this.config.fragLoadingLoopThreshold;\n // flush everything\n this.flushMainBuffer(0,Number.POSITIVE_INFINITY);\n }\n\n /*\n on immediate level switch end, after new fragment has been buffered :\n - nudge video decoder by slightly adjusting video currentTime (if currentTime buffered)\n - resume the playback if needed\n */\n immediateLevelSwitchEnd() {\n let media = this.media;\n if (media && media.buffered.length) {\n this.immediateSwitch = false;\n if(BufferHelper.isBuffered(media,media.currentTime)) {\n // only nudge if currentTime is buffered\n media.currentTime -= 0.0001;\n }\n if (!this.previouslyPaused) {\n media.play();\n }\n }\n }\n\n nextLevelSwitch() {\n /* try to switch ASAP without breaking video playback :\n in order to ensure smooth but quick level switching,\n we need to find the next flushable buffer range\n we should take into account new segment fetch time\n */\n let media = this.media;\n // ensure that media is defined and that metadata are available (to retrieve currentTime)\n if (media && media.readyState) {\n let fetchdelay, currentRange, nextRange;\n // increase fragment load Index to avoid frag loop loading error after buffer flush\n this.fragLoadIdx += 2 * this.config.fragLoadingLoopThreshold;\n currentRange = this.getBufferRange(media.currentTime);\n if (currentRange && currentRange.start > 1) {\n // flush buffer preceding current fragment (flush until current fragment start offset)\n // minus 1s to avoid video freezing, that could happen if we flush keyframe of current video ...\n this.flushMainBuffer(0,currentRange.start - 1);\n }\n if (!media.paused) {\n // add a safety delay of 1s\n var nextLevelId = this.hls.nextLoadLevel,nextLevel = this.levels[nextLevelId], fragLastKbps = this.fragLastKbps;\n if (fragLastKbps && this.fragCurrent) {\n fetchdelay = this.fragCurrent.duration * nextLevel.bitrate / (1000 * fragLastKbps) + 1;\n } else {\n fetchdelay = 0;\n }\n } else {\n fetchdelay = 0;\n }\n //logger.log('fetchdelay:'+fetchdelay);\n // find buffer range that will be reached once new fragment will be fetched\n nextRange = this.getBufferRange(media.currentTime + fetchdelay);\n if (nextRange) {\n // we can flush buffer range following this one without stalling playback\n nextRange = this.followingBufferRange(nextRange);\n if (nextRange) {\n // if we are here, we can also cancel any loading/demuxing in progress, as they are useless\n var fragCurrent = this.fragCurrent;\n if (fragCurrent && fragCurrent.loader) {\n fragCurrent.loader.abort();\n }\n this.fragCurrent = null;\n // flush position is the start position of this new buffer\n this.flushMainBuffer(nextRange.start , Number.POSITIVE_INFINITY);\n }\n }\n }\n }\n\n flushMainBuffer(startOffset,endOffset) {\n this.state = State.BUFFER_FLUSHING;\n let flushScope = {startOffset: startOffset, endOffset: endOffset};\n // if alternate audio tracks are used, only flush video, otherwise flush everything\n if (this.altAudio) {\n flushScope.type = 'video';\n }\n this.hls.trigger(Event.BUFFER_FLUSHING, flushScope);\n }\n\n onMediaAttached(data) {\n var media = this.media = this.mediaBuffer = data.media;\n this.onvseeking = this.onMediaSeeking.bind(this);\n this.onvseeked = this.onMediaSeeked.bind(this);\n this.onvended = this.onMediaEnded.bind(this);\n media.addEventListener('seeking', this.onvseeking);\n media.addEventListener('seeked', this.onvseeked);\n media.addEventListener('ended', this.onvended);\n let config = this.config;\n if(this.levels && config.autoStartLoad) {\n this.hls.startLoad(config.startPosition);\n }\n }\n\n onMediaDetaching() {\n var media = this.media;\n if (media && media.ended) {\n logger.log('MSE detaching and video ended, reset startPosition');\n this.startPosition = this.lastCurrentTime = 0;\n }\n\n // reset fragment loading counter on MSE detaching to avoid reporting FRAG_LOOP_LOADING_ERROR after error recovery\n var levels = this.levels;\n if (levels) {\n // reset fragment load counter\n levels.forEach(level => {\n if(level.details) {\n level.details.fragments.forEach(fragment => {\n fragment.loadCounter = undefined;\n });\n }\n });\n }\n // remove video listeners\n if (media) {\n media.removeEventListener('seeking', this.onvseeking);\n media.removeEventListener('seeked', this.onvseeked);\n media.removeEventListener('ended', this.onvended);\n this.onvseeking = this.onvseeked = this.onvended = null;\n }\n this.media = this.mediaBuffer = null;\n this.loadedmetadata = false;\n this.stopLoad();\n }\n\n onMediaSeeking() {\n let media = this.media, currentTime = media ? media.currentTime : undefined, config = this.config;\n logger.log(`media seeking to ${currentTime.toFixed(3)}`);\n if (this.state === State.FRAG_LOADING) {\n let mediaBuffer = this.mediaBuffer ? this.mediaBuffer : media;\n let bufferInfo = BufferHelper.bufferInfo(mediaBuffer,currentTime,this.config.maxBufferHole),\n fragCurrent = this.fragCurrent;\n // check if we are seeking to a unbuffered area AND if frag loading is in progress\n if (bufferInfo.len === 0 && fragCurrent) {\n let tolerance = config.maxFragLookUpTolerance,\n fragStartOffset = fragCurrent.start - tolerance,\n fragEndOffset = fragCurrent.start + fragCurrent.duration + tolerance;\n // check if we seek position will be out of currently loaded frag range : if out cancel frag load, if in, don't do anything\n if (currentTime < fragStartOffset || currentTime > fragEndOffset) {\n if (fragCurrent.loader) {\n logger.log('seeking outside of buffer while fragment load in progress, cancel fragment load');\n fragCurrent.loader.abort();\n }\n this.fragCurrent = null;\n this.fragPrevious = null;\n // switch to IDLE state to load new fragment\n this.state = State.IDLE;\n } else {\n logger.log('seeking outside of buffer but within currently loaded fragment range');\n }\n }\n } else if (this.state === State.ENDED) {\n // switch to IDLE state to check for potential new fragment\n this.state = State.IDLE;\n }\n if (media) {\n this.lastCurrentTime = currentTime;\n }\n // avoid reporting fragment loop loading error in case user is seeking several times on same position\n if (this.state !== State.FRAG_LOADING && this.fragLoadIdx !== undefined) {\n this.fragLoadIdx += 2 * config.fragLoadingLoopThreshold;\n }\n // in case seeking occurs although no media buffered, adjust startPosition and nextLoadPosition to seek target\n if(!this.loadedmetadata) {\n this.nextLoadPosition = this.startPosition = currentTime;\n }\n // tick to speed up processing\n this.tick();\n }\n\n onMediaSeeked() {\n logger.log(`media seeked to ${this.media.currentTime.toFixed(3)}`);\n // tick to speed up FRAGMENT_PLAYING triggering\n this.tick();\n }\n\n onMediaEnded() {\n logger.log('media ended');\n // reset startPosition and lastCurrentTime to restart playback @ stream beginning\n this.startPosition = this.lastCurrentTime = 0;\n }\n\n\n onManifestLoading() {\n // reset buffer on manifest loading\n logger.log('trigger BUFFER_RESET');\n this.hls.trigger(Event.BUFFER_RESET);\n this.bufferRange = [];\n this.stalled = false;\n this.startPosition = this.lastCurrentTime = 0;\n }\n\n onManifestParsed(data) {\n var aac = false, heaac = false, codec;\n data.levels.forEach(level => {\n // detect if we have different kind of audio codecs used amongst playlists\n codec = level.audioCodec;\n if (codec) {\n if (codec.indexOf('mp4a.40.2') !== -1) {\n aac = true;\n }\n if (codec.indexOf('mp4a.40.5') !== -1) {\n heaac = true;\n }\n }\n });\n this.audioCodecSwitch = (aac && heaac);\n if (this.audioCodecSwitch) {\n logger.log('both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC');\n }\n this.levels = data.levels;\n this.startLevelLoaded = false;\n this.startFragRequested = false;\n let config = this.config;\n if (config.autoStartLoad) {\n this.hls.startLoad(config.startPosition);\n }\n }\n\n onLevelLoaded(data) {\n var newDetails = data.details,\n newLevelId = data.level,\n curLevel = this.levels[newLevelId],\n duration = newDetails.totalduration,\n sliding = 0;\n\n logger.log(`level ${newLevelId} loaded [${newDetails.startSN},${newDetails.endSN}],duration:${duration}`);\n this.levelLastLoaded = newLevelId;\n\n if (newDetails.live) {\n var curDetails = curLevel.details;\n if (curDetails && newDetails.fragments.length > 0) {\n // we already have details for that level, merge them\n LevelHelper.mergeDetails(curDetails,newDetails);\n sliding = newDetails.fragments[0].start;\n this.liveSyncPosition = this.computeLivePosition(sliding, curDetails);\n if (newDetails.PTSKnown) {\n logger.log(`live playlist sliding:${sliding.toFixed(3)}`);\n } else {\n logger.log('live playlist - outdated PTS, unknown sliding');\n }\n } else {\n newDetails.PTSKnown = false;\n logger.log('live playlist - first load, unknown sliding');\n }\n } else {\n newDetails.PTSKnown = false;\n }\n // override level info\n curLevel.details = newDetails;\n this.hls.trigger(Event.LEVEL_UPDATED, { details: newDetails, level: newLevelId });\n\n if (this.startFragRequested === false) {\n // compute start position if set to -1. use it straight away if value is defined\n if (this.startPosition === -1 || this.lastCurrentTime === -1) {\n // first, check if start time offset has been set in playlist, if yes, use this value\n let startTimeOffset = newDetails.startTimeOffset;\n if(!isNaN(startTimeOffset)) {\n if (startTimeOffset < 0) {\n logger.log(`negative start time offset ${startTimeOffset}, count from end of last fragment`);\n startTimeOffset = sliding + duration + startTimeOffset;\n }\n logger.log(`start time offset found in playlist, adjust startPosition to ${startTimeOffset}`);\n this.startPosition = startTimeOffset;\n } else {\n // if live playlist, set start position to be fragment N-this.config.liveSyncDurationCount (usually 3)\n if (newDetails.live) {\n this.startPosition = this.computeLivePosition(sliding, newDetails);\n logger.log(`configure startPosition to ${this.startPosition}`);\n } else {\n this.startPosition = 0;\n }\n }\n this.lastCurrentTime = this.startPosition;\n }\n this.nextLoadPosition = this.startPosition;\n }\n // only switch batck to IDLE state if we were waiting for level to start downloading a new fragment\n if (this.state === State.WAITING_LEVEL) {\n this.state = State.IDLE;\n }\n //trigger handler right now\n this.tick();\n }\n\n onKeyLoaded() {\n if (this.state === State.KEY_LOADING) {\n this.state = State.IDLE;\n this.tick();\n }\n }\n\n onFragLoaded(data) {\n var fragCurrent = this.fragCurrent,\n fragLoaded = data.frag;\n if (this.state === State.FRAG_LOADING &&\n fragCurrent &&\n fragLoaded.type === 'main' &&\n fragLoaded.level === fragCurrent.level &&\n fragLoaded.sn === fragCurrent.sn) {\n let stats = data.stats,\n currentLevel = this.levels[fragCurrent.level],\n details = currentLevel.details;\n logger.log(`Loaded ${fragCurrent.sn} of [${details.startSN} ,${details.endSN}],level ${fragCurrent.level}`);\n // reset frag bitrate test in any case after frag loaded event\n this.bitrateTest = false;\n // if this frag was loaded to perform a bitrate test AND if hls.nextLoadLevel is greater than 0\n // then this means that we should be able to load a fragment at a higher quality level\n if (fragLoaded.bitrateTest === true && this.hls.nextLoadLevel) {\n // switch back to IDLE state ... we just loaded a fragment to determine adequate start bitrate and initialize autoswitch algo\n this.state = State.IDLE;\n this.startFragRequested = false;\n stats.tparsed = stats.tbuffered = performance.now();\n this.hls.trigger(Event.FRAG_BUFFERED, {stats: stats, frag: fragCurrent, id : 'main'});\n this.tick();\n } else {\n this.state = State.PARSING;\n // transmux the MPEG-TS data to ISO-BMFF segments\n this.stats = stats;\n let duration = details.totalduration,\n start = !isNaN(fragCurrent.startDTS) ? fragCurrent.startDTS : fragCurrent.start,\n level = fragCurrent.level,\n sn = fragCurrent.sn,\n audioCodec = this.config.defaultAudioCodec || currentLevel.audioCodec;\n if(this.audioCodecSwap) {\n logger.log('swapping playlist audio codec');\n if(audioCodec === undefined) {\n audioCodec = this.lastAudioCodec;\n }\n if(audioCodec) {\n if(audioCodec.indexOf('mp4a.40.5') !==-1) {\n audioCodec = 'mp4a.40.2';\n } else {\n audioCodec = 'mp4a.40.5';\n }\n }\n }\n this.pendingBuffering = true;\n this.appended = false;\n logger.log(`Parsing ${sn} of [${details.startSN} ,${details.endSN}],level ${level}, cc ${fragCurrent.cc}`);\n let demuxer = this.demuxer;\n if (!demuxer) {\n demuxer = this.demuxer = new Demuxer(this.hls,'main');\n }\n // time Offset is accurate if level PTS is known, or if playlist is not sliding (not live) and if media is not seeking (this is to overcome potential timestamp drifts between playlists and fragments)\n let media = this.media;\n let mediaSeeking = media && media.seeking;\n let accurateTimeOffset = !mediaSeeking && (details.PTSKnown || !details.live);\n demuxer.push(data.payload, audioCodec, currentLevel.videoCodec, start, fragCurrent.cc, level, sn, duration, fragCurrent.decryptdata, accurateTimeOffset,null);\n }\n }\n this.fragLoadError = 0;\n }\n\n onFragParsingInitSegment(data) {\n let fragCurrent = this.fragCurrent;\n if (fragCurrent &&\n data.id === 'main' &&\n data.sn === fragCurrent.sn &&\n data.level === fragCurrent.level &&\n this.state === State.PARSING) {\n var tracks = data.tracks, trackName, track;\n\n // if audio track is expected to come from audio stream controller, discard any coming from main\n if (tracks.audio && this.altAudio) {\n delete tracks.audio;\n }\n // include levelCodec in audio and video tracks\n track = tracks.audio;\n if(track) {\n var audioCodec = this.levels[this.level].audioCodec,\n ua = navigator.userAgent.toLowerCase();\n if(audioCodec && this.audioCodecSwap) {\n logger.log('swapping playlist audio codec');\n if(audioCodec.indexOf('mp4a.40.5') !==-1) {\n audioCodec = 'mp4a.40.2';\n } else {\n audioCodec = 'mp4a.40.5';\n }\n }\n // in case AAC and HE-AAC audio codecs are signalled in manifest\n // force HE-AAC , as it seems that most browsers prefers that way,\n // except for mono streams OR on FF\n // these conditions might need to be reviewed ...\n if (this.audioCodecSwitch) {\n // don't force HE-AAC if mono stream\n if(track.metadata.channelCount !== 1 &&\n // don't force HE-AAC if firefox\n ua.indexOf('firefox') === -1) {\n audioCodec = 'mp4a.40.5';\n }\n }\n // HE-AAC is broken on Android, always signal audio codec as AAC even if variant manifest states otherwise\n if(ua.indexOf('android') !== -1 && track.container !== 'audio/mpeg') { // Exclude mpeg audio\n audioCodec = 'mp4a.40.2';\n logger.log(`Android: force audio codec to ${audioCodec}`);\n }\n track.levelCodec = audioCodec;\n track.id = data.id;\n }\n track = tracks.video;\n if(track) {\n track.levelCodec = this.levels[this.level].videoCodec;\n track.id = data.id;\n }\n\n // if remuxer specify that a unique track needs to generated,\n // let's merge all tracks together\n if (data.unique) {\n var mergedTrack = {\n codec : '',\n levelCodec : ''\n };\n for (trackName in data.tracks) {\n track = tracks[trackName];\n mergedTrack.container = track.container;\n if (mergedTrack.codec) {\n mergedTrack.codec += ',';\n mergedTrack.levelCodec += ',';\n }\n if(track.codec) {\n mergedTrack.codec += track.codec;\n }\n if (track.levelCodec) {\n mergedTrack.levelCodec += track.levelCodec;\n }\n }\n tracks = { audiovideo : mergedTrack };\n }\n this.hls.trigger(Event.BUFFER_CODECS,tracks);\n // loop through tracks that are going to be provided to bufferController\n for (trackName in tracks) {\n track = tracks[trackName];\n logger.log(`main track:${trackName},container:${track.container},codecs[level/parsed]=[${track.levelCodec}/${track.codec}]`);\n var initSegment = track.initSegment;\n if (initSegment) {\n this.appended = true;\n // arm pending Buffering flag before appending a segment\n this.pendingBuffering = true;\n this.hls.trigger(Event.BUFFER_APPENDING, {type: trackName, data: initSegment, parent : 'main', content : 'initSegment'});\n }\n }\n //trigger handler right now\n this.tick();\n }\n }\n\n onFragParsingData(data) {\n let fragCurrent = this.fragCurrent;\n if (fragCurrent &&\n data.id === 'main' &&\n data.sn === fragCurrent.sn &&\n data.level === fragCurrent.level &&\n !(data.type === 'audio' && this.altAudio) && // filter out main audio if audio track is loaded through audio stream controller\n this.state === State.PARSING) {\n var level = this.levels[this.level],\n frag = this.fragCurrent;\n\n logger.log(`Parsed ${data.type},PTS:[${data.startPTS.toFixed(3)},${data.endPTS.toFixed(3)}],DTS:[${data.startDTS.toFixed(3)}/${data.endDTS.toFixed(3)}],nb:${data.nb},dropped:${data.dropped || 0}`);\n\n var drift = LevelHelper.updateFragPTSDTS(level.details,frag.sn,data.startPTS,data.endPTS,data.startDTS,data.endDTS),\n hls = this.hls;\n hls.trigger(Event.LEVEL_PTS_UPDATED, {details: level.details, level: this.level, drift: drift, type: data.type, start: data.startPTS, end: data.endPTS});\n\n // has remuxer dropped video frames located before first keyframe ?\n if(data.type === 'video') {\n frag.dropped = data.dropped;\n }\n\n [data.data1, data.data2].forEach(buffer => {\n if (buffer) {\n this.appended = true;\n // arm pending Buffering flag before appending a segment\n this.pendingBuffering = true;\n hls.trigger(Event.BUFFER_APPENDING, {type: data.type, data: buffer, parent : 'main',content : 'data'});\n }\n });\n\n this.bufferRange.push({type: data.type, start: data.startPTS, end: data.endPTS, frag: frag});\n\n //trigger handler right now\n this.tick();\n }\n }\n\n onFragParsed(data) {\n let fragCurrent = this.fragCurrent;\n if (fragCurrent &&\n data.id === 'main' &&\n data.sn === fragCurrent.sn &&\n data.level === fragCurrent.level &&\n this.state === State.PARSING) {\n this.stats.tparsed = performance.now();\n this.state = State.PARSED;\n this._checkAppendedParsed();\n }\n }\n\n onAudioTrackSwitching(data) {\n // if any URL found on new audio track, it is an alternate audio track\n var altAudio = !!data.url,\n trackId = data.id;\n // if we switch on main audio, ensure that main fragment scheduling is synced with media.buffered\n // don't do anything if we switch to alt audio: audio stream controller is handling it.\n // we will just have to change buffer scheduling on audioTrackSwitched\n if (!altAudio) {\n if (this.mediaBuffer !== this.media) {\n logger.log(`switching on main audio, use media.buffered to schedule main fragment loading`);\n this.mediaBuffer = this.media;\n let fragCurrent = this.fragCurrent;\n // we need to refill audio buffer from main: cancel any frag loading to speed up audio switch\n if (fragCurrent.loader) {\n logger.log('switching to main audio track, cancel main fragment load');\n fragCurrent.loader.abort();\n }\n this.fragCurrent = null;\n this.fragPrevious = null;\n // destroy demuxer to force init segment generation (following audio switch)\n if (this.demuxer) {\n this.demuxer.destroy();\n this.demuxer = null;\n }\n // switch to IDLE state to load new fragment\n this.state = State.IDLE;\n }\n let hls = this.hls;\n // switching to main audio, flush all audio and trigger track switched\n hls.trigger(Event.BUFFER_FLUSHING, {startOffset: 0 , endOffset: Number.POSITIVE_INFINITY, type : 'audio'});\n hls.trigger(Event.AUDIO_TRACK_SWITCHED, {id : trackId});\n this.altAudio = false;\n }\n }\n\n onAudioTrackSwitched(data) {\n var trackId = data.id,\n altAudio = !!this.hls.audioTracks[trackId].url;\n if (altAudio) {\n let videoBuffer = this.videoBuffer;\n // if we switched on alternate audio, ensure that main fragment scheduling is synced with video sourcebuffer buffered\n if (videoBuffer && this.mediaBuffer !== videoBuffer) {\n logger.log(`switching on alternate audio, use video.buffered to schedule main fragment loading`);\n this.mediaBuffer = videoBuffer;\n }\n }\n this.altAudio = altAudio;\n this.tick();\n }\n\n\n\n onBufferCreated(data) {\n let tracks = data.tracks, mediaTrack, name, alternate = false;\n for(var type in tracks) {\n let track = tracks[type];\n if (track.id === 'main') {\n name = type;\n mediaTrack = track;\n // keep video source buffer reference\n if (type === 'video') {\n this.videoBuffer = tracks[type].buffer;\n }\n } else {\n alternate = true;\n }\n }\n if (alternate && mediaTrack) {\n logger.log(`alternate track found, use ${name}.buffered to schedule main fragment loading`);\n this.mediaBuffer = mediaTrack.buffer;\n } else {\n this.mediaBuffer = this.media;\n }\n }\n\n onBufferAppended(data) {\n if (data.parent === 'main') {\n const state = this.state;\n if (state === State.PARSING || state === State.PARSED) {\n // check if all buffers have been appended\n this.pendingBuffering = (data.pending > 0);\n this._checkAppendedParsed();\n }\n }\n }\n\n _checkAppendedParsed() {\n //trigger handler right now\n if (this.state === State.PARSED && (!this.appended || !this.pendingBuffering)) {\n var frag = this.fragCurrent, stats = this.stats;\n if (frag) {\n this.fragPrevious = frag;\n stats.tbuffered = performance.now();\n // we should get rid of this.fragLastKbps\n this.fragLastKbps = Math.round(8 * stats.total / (stats.tbuffered - stats.tfirst));\n this.hls.trigger(Event.FRAG_BUFFERED, {stats: stats, frag: frag, id : 'main'});\n let media = this.mediaBuffer ? this.mediaBuffer : this.media;\n logger.log(`main buffered : ${TimeRanges.toString(media.buffered)}`);\n this.state = State.IDLE;\n }\n this.tick();\n }\n }\n\n onError(data) {\n let frag = data.frag || this.fragCurrent;\n // don't handle frag error not related to main fragment\n if (frag && frag.type !== 'main') {\n return;\n }\n let media = this.media,\n // 0.5 : tolerance needed as some browsers stalls playback before reaching buffered end\n mediaBuffered = media && BufferHelper.isBuffered(media,media.currentTime) && BufferHelper.isBuffered(media,media.currentTime+0.5);\n switch(data.details) {\n case ErrorDetails.FRAG_LOAD_ERROR:\n case ErrorDetails.FRAG_LOAD_TIMEOUT:\n case ErrorDetails.KEY_LOAD_ERROR:\n case ErrorDetails.KEY_LOAD_TIMEOUT:\n if(!data.fatal) {\n var loadError = this.fragLoadError;\n if(loadError) {\n loadError++;\n } else {\n loadError=1;\n }\n let config = this.config;\n // keep retrying / don't raise fatal network error if current position is buffered or if in automode with current level not 0\n if (loadError <= config.fragLoadingMaxRetry || mediaBuffered || (frag.autoLevel && frag.level)) {\n this.fragLoadError = loadError;\n // reset load counter to avoid frag loop loading error\n frag.loadCounter = 0;\n // exponential backoff capped to config.fragLoadingMaxRetryTimeout\n var delay = Math.min(Math.pow(2,loadError-1)*config.fragLoadingRetryDelay,config.fragLoadingMaxRetryTimeout);\n logger.warn(`mediaController: frag loading failed, retry in ${delay} ms`);\n this.retryDate = performance.now() + delay;\n // retry loading state\n // if loadedmetadata is not set, it means that we are emergency switch down on first frag\n // in that case, reset startFragRequested flag\n if(!this.loadedmetadata) {\n this.startFragRequested = false;\n this.nextLoadPosition = this.startPosition;\n }\n this.state = State.FRAG_LOADING_WAITING_RETRY;\n } else {\n logger.error(`mediaController: ${data.details} reaches max retry, redispatch as fatal ...`);\n // redispatch same error but with fatal set to true\n data.fatal = true;\n this.hls.trigger(Event.ERROR, data);\n this.state = State.ERROR;\n }\n }\n break;\n case ErrorDetails.FRAG_LOOP_LOADING_ERROR:\n if(!data.fatal) {\n // if buffer is not empty\n if (mediaBuffered) {\n // try to reduce max buffer length : rationale is that we could get\n // frag loop loading error because of buffer eviction\n this._reduceMaxBufferLength(frag.duration);\n this.state = State.IDLE;\n } else {\n // buffer empty. report as fatal if in manual mode or if lowest level.\n // level controller takes care of emergency switch down logic\n if (!frag.autoLevel || frag.level === 0) {\n // redispatch same error but with fatal set to true\n data.fatal = true;\n this.hls.trigger(Event.ERROR, data);\n this.state = State.ERROR;\n }\n }\n }\n break;\n case ErrorDetails.LEVEL_LOAD_ERROR:\n case ErrorDetails.LEVEL_LOAD_TIMEOUT:\n if(this.state !== State.ERROR) {\n if (data.fatal) {\n // if fatal error, stop processing\n this.state = State.ERROR;\n logger.warn(`streamController: ${data.details},switch to ${this.state} state ...`);\n } else {\n // in cas of non fatal error while waiting level load to be completed, switch back to IDLE\n if (this.state === State.WAITING_LEVEL) {\n this.state = State.IDLE;\n }\n }\n }\n break;\n case ErrorDetails.BUFFER_FULL_ERROR:\n // if in appending state\n if (this.state === State.PARSING || this.state === State.PARSED) {\n // reduce max buf len if current position is buffered\n if (mediaBuffered) {\n this._reduceMaxBufferLength(frag.duration);\n this.state = State.IDLE;\n } else {\n // current position is not buffered, but browser is still complaining about buffer full error\n // this happens on IE/Edge, refer to https://github.com/dailymotion/hls.js/pull/708\n // in that case flush the whole buffer to recover\n logger.warn('buffer full error also media.currentTime is not buffered, flush everything');\n this.fragCurrent = null;\n // flush everything\n this.flushMainBuffer(0,Number.POSITIVE_INFINITY);\n }\n }\n break;\n default:\n break;\n }\n }\n\n _reduceMaxBufferLength(minLength) {\n let config = this.config;\n if (config.maxMaxBufferLength >= minLength) {\n // reduce max buffer length as it might be too high. we do this to avoid loop flushing ...\n config.maxMaxBufferLength/=2;\n logger.warn(`reduce max buffer length to ${config.maxMaxBufferLength}s and switch to IDLE state`);\n // increase fragment load Index to avoid frag loop loading error after buffer flush\n this.fragLoadIdx += 2 * config.fragLoadingLoopThreshold;\n }\n }\n\n_checkBuffer() {\n var media = this.media;\n // if ready state different from HAVE_NOTHING (numeric value 0), we are allowed to seek\n if(media && media.readyState) {\n let currentTime = media.currentTime,\n mediaBuffer = this.mediaBuffer ? this.mediaBuffer : media,\n buffered = mediaBuffer.buffered;\n // adjust currentTime to start position on loaded metadata\n if(!this.loadedmetadata && buffered.length && !media.seeking) {\n this.loadedmetadata = true;\n this.nudgeRetry = 0;\n // only adjust currentTime if different from startPosition or if startPosition not buffered\n // at that stage, there should be only one buffered range, as we reach that code after first fragment has been buffered\n let startPosition = this.startPosition,\n startPositionBuffered = BufferHelper.isBuffered(mediaBuffer,startPosition);\n // if currentTime not matching with expected startPosition or startPosition not buffered\n if (currentTime !== startPosition || !startPositionBuffered) {\n logger.log(`target start position:${startPosition}`);\n // if startPosition not buffered, let's seek to buffered.start(0)\n if(!startPositionBuffered) {\n startPosition = buffered.start(0);\n logger.log(`target start position not buffered, seek to buffered.start(0) ${startPosition}`);\n }\n logger.log(`adjust currentTime from ${currentTime} to ${startPosition}`);\n media.currentTime = startPosition;\n }\n } else if (this.immediateSwitch) {\n this.immediateLevelSwitchEnd();\n } else {\n let bufferInfo = BufferHelper.bufferInfo(media,currentTime,0),\n expectedPlaying = !(media.paused || // not playing when media is paused\n media.ended || // not playing when media is ended\n media.buffered.length === 0), // not playing if nothing buffered\n jumpThreshold = 0.5, // tolerance needed as some browsers stalls playback before reaching buffered range end\n playheadMoving = currentTime > media.playbackRate*this.lastCurrentTime,\n config = this.config;\n\n if (playheadMoving) {\n // played moving, but was previously stalled => now not stuck anymore\n if (this.stalled) {\n this.stalled = undefined;\n this.stallCount = 0;\n logger.log(`playback not stuck anymore @${currentTime}`);\n }\n } else {\n // playhead not moving\n if(expectedPlaying) {\n // playhead not moving BUT media expected to play\n const tnow = performance.now();\n const hls = this.hls;\n if(!this.stalled) {\n // stall just detected, store current time\n logger.log(`playback seems stuck @${currentTime}`);\n hls.trigger(Event.ERROR, {type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.BUFFER_STALLED_ERROR, fatal: false});\n this.stalled = tnow;\n } else {\n // playback already stalled, check stalling duration\n // if stalling for more than a given threshold, let's try to recover\n const stalledDuration = tnow - this.stalled;\n // have we reached stall deadline ?\n if (stalledDuration > config.nudgeWatchdogPeriod * 1000) {\n const nudgeRetry = this.nudgeRetry++;\n const nudgeOffset = nudgeRetry * config.nudgeOffset;\n // if buffer len is below threshold, try to jump to start of next buffer range if close\n if(bufferInfo.len <= jumpThreshold) {\n // no buffer available @ currentTime, check if next buffer is close (within a config.maxSeekHole second range)\n var nextBufferStart = bufferInfo.nextStart, delta = nextBufferStart-currentTime;\n if(nextBufferStart &&\n (delta < config.maxSeekHole) &&\n (delta > 0)) {\n // next buffer is close ! adjust currentTime to nextBufferStart\n // this will ensure effective video decoding\n logger.log(`adjust currentTime from ${media.currentTime} to next buffered @ ${nextBufferStart} + nudge ${nudgeOffset}`);\n let hole = nextBufferStart + nudgeOffset - media.currentTime;\n media.currentTime = nextBufferStart + nudgeOffset;\n this.stalled = undefined;\n hls.trigger(Event.ERROR, {type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.BUFFER_SEEK_OVER_HOLE, fatal: false, hole : hole});\n }\n } else {\n this.stalled = undefined;\n if (nudgeRetry < config.nudgeMaxRetry) {\n // playback stalled in buffered area ... let's nudge currentTime to try to overcome this\n media.currentTime += config.nudgeOffset + nudgeOffset;\n hls.trigger(Event.ERROR, {type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.BUFFER_NUDGE_ON_STALL, fatal: false});\n } else {\n hls.trigger(Event.ERROR, {type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.BUFFER_STALLED_ERROR, fatal: true});\n }\n }\n }\n }\n }\n }\n }\n }\n }\n\n onFragLoadEmergencyAborted() {\n this.state = State.IDLE;\n // if loadedmetadata is not set, it means that we are emergency switch down on first frag\n // in that case, reset startFragRequested flag\n if(!this.loadedmetadata) {\n this.startFragRequested = false;\n this.nextLoadPosition = this.startPosition;\n }\n this.tick();\n }\n\n onBufferFlushed() {\n /* after successful buffer flushing, rebuild buffer Range array\n loop through existing buffer range and check if\n corresponding range is still buffered. only push to new array already buffered range\n use mediaBuffered instead of media (so that we will check against video.buffered ranges in case of alt audio track)\n */\n let media = this.mediaBuffer ? this.mediaBuffer : this.media,\n bufferRange = this.bufferRange,\n newRange = [],range,i;\n for (i = 0; i < bufferRange.length; i++) {\n range = bufferRange[i];\n if (BufferHelper.isBuffered(media,(range.start + range.end) / 2)) {\n newRange.push(range);\n }\n }\n this.bufferRange = newRange;\n\n // increase fragment load Index to avoid frag loop loading error after buffer flush\n this.fragLoadIdx += 2 * this.config.fragLoadingLoopThreshold;\n // move to IDLE once flush complete. this should trigger new fragment loading\n this.state = State.IDLE;\n // reset reference to frag\n this.fragPrevious = null;\n }\n\n swapAudioCodec() {\n this.audioCodecSwap = !this.audioCodecSwap;\n }\n\n computeLivePosition(sliding, levelDetails) {\n let targetLatency = this.config.liveSyncDuration !== undefined ? this.config.liveSyncDuration : this.config.liveSyncDurationCount * levelDetails.targetduration;\n return sliding + Math.max(0, levelDetails.totalduration - targetLatency);\n }\n\n get liveSyncPosition() {\n return this._liveSyncPosition;\n }\n\n set liveSyncPosition(value) {\n this._liveSyncPosition = value;\n }\n}\nexport default StreamController;\n\n",
"/*\n * Timeline Controller\n*/\n\nimport Event from '../events';\nimport EventHandler from '../event-handler';\nimport Cea608Parser from '../utils/cea-608-parser';\n\nclass TimelineController extends EventHandler {\n\n constructor(hls) {\n super(hls, Event.MEDIA_ATTACHING,\n Event.MEDIA_DETACHING,\n Event.FRAG_PARSING_USERDATA,\n Event.MANIFEST_LOADING,\n Event.FRAG_LOADED,\n Event.LEVEL_SWITCH);\n\n this.hls = hls;\n this.config = hls.config;\n this.enabled = true;\n this.Cues = hls.config.cueHandler;\n\n if (this.config.enableCEA708Captions)\n {\n var self = this;\n var sendAddTrackEvent = function (track, media)\n {\n var e = null;\n try {\n e = new window.Event('addtrack');\n } catch (err) {\n //for IE11\n e = document.createEvent('Event');\n e.initEvent('addtrack', false, false);\n }\n e.track = track;\n media.dispatchEvent(e);\n };\n\n var channel1 =\n {\n 'newCue': function(startTime, endTime, screen)\n {\n if (!self.textTrack1)\n {\n //Enable reuse of existing text track.\n var existingTrack1 = self.getExistingTrack('1');\n if(!existingTrack1)\n {\n self.textTrack1 = self.createTextTrack('captions', 'English', 'en');\n self.textTrack1.textTrack1 = true;\n }\n else\n {\n self.textTrack1 = existingTrack1;\n self.clearCurrentCues(self.textTrack1);\n\n sendAddTrackEvent(self.textTrack1, self.media);\n }\n }\n\n self.Cues.newCue(self.textTrack1, startTime, endTime, screen);\n }\n };\n\n var channel2 =\n {\n 'newCue': function(startTime, endTime, screen)\n {\n if (!self.textTrack2)\n {\n //Enable reuse of existing text track.\n var existingTrack2 = self.getExistingTrack('2');\n if(!existingTrack2)\n {\n self.textTrack2 = self.createTextTrack('captions', 'Spanish', 'es');\n self.textTrack2.textTrack2 = true;\n }\n else\n {\n self.textTrack2 = existingTrack2;\n self.clearCurrentCues(self.textTrack2);\n\n sendAddTrackEvent(self.textTrack2, self.media);\n }\n }\n\n self.Cues.newCue(self.textTrack2, startTime, endTime, screen); }\n };\n\n this.cea608Parser = new Cea608Parser(0, channel1, channel2);\n }\n }\n\n clearCurrentCues(track)\n {\n if (track && track.cues)\n {\n while (track.cues.length > 0)\n {\n track.removeCue(track.cues[0]);\n }\n }\n }\n\n getExistingTrack(channelNumber)\n {\n let media = this.media;\n if (media)\n {\n for (let i = 0; i < media.textTracks.length; i++)\n {\n let textTrack = media.textTracks[i];\n let propName = 'textTrack' + channelNumber;\n if (textTrack[propName] === true)\n {\n return textTrack;\n }\n }\n }\n return null;\n }\n\n createTextTrack(kind, label, lang)\n {\n if (this.media)\n {\n return this.media.addTextTrack(kind, label, lang);\n }\n }\n\n destroy() {\n EventHandler.prototype.destroy.call(this);\n }\n\n onMediaAttaching(data) {\n this.media = data.media;\n }\n\n onMediaDetaching() {\n this.clearCurrentCues(this.textTrack1);\n this.clearCurrentCues(this.textTrack2);\n }\n\n onManifestLoading()\n {\n this.lastPts = Number.NEGATIVE_INFINITY;\n }\n\n onLevelSwitch()\n {\n if (this.hls.currentLevel.closedCaptions === 'NONE')\n {\n this.enabled = false;\n }\n else\n {\n this.enabled = true;\n }\n }\n\n onFragLoaded(data)\n {\n if (data.frag.type === 'main') {\n var pts = data.frag.start; //Number.POSITIVE_INFINITY;\n // if this is a frag for a previously loaded timerange, remove all captions\n // TODO: consider just removing captions for the timerange\n if (pts <= this.lastPts)\n {\n this.clearCurrentCues(this.textTrack1);\n this.clearCurrentCues(this.textTrack2);\n }\n this.lastPts = pts;\n }\n }\n\n onFragParsingUserdata(data) {\n // push all of the CEA-708 messages into the interpreter\n // immediately. It will create the proper timestamps based on our PTS value\n if (this.enabled && this.config.enableCEA708Captions)\n {\n for (var i=0; i<data.samples.length; i++)\n {\n var ccdatas = this.extractCea608Data(data.samples[i].bytes);\n this.cea608Parser.addData(data.samples[i].pts, ccdatas);\n }\n }\n }\n\n extractCea608Data(byteArray)\n {\n var count = byteArray[0] & 31;\n var position = 2;\n var tmpByte, ccbyte1, ccbyte2, ccValid, ccType;\n var actualCCBytes = [];\n\n for (var j = 0; j < count; j++) {\n tmpByte = byteArray[position++];\n ccbyte1 = 0x7F & byteArray[position++];\n ccbyte2 = 0x7F & byteArray[position++];\n ccValid = (4 & tmpByte) === 0 ? false : true;\n ccType = 3 & tmpByte;\n\n if (ccbyte1 === 0 && ccbyte2 === 0) {\n continue;\n }\n\n if (ccValid) {\n if (ccType === 0) // || ccType === 1\n {\n actualCCBytes.push(ccbyte1);\n actualCCBytes.push(ccbyte2);\n }\n }\n }\n return actualCCBytes;\n }\n}\n\nexport default TimelineController;\n",
"export default class AESCrypto {\n constructor(subtle,iv) {\n this.subtle = subtle;\n this.aesIV = iv;\n }\n\n decrypt(data, key) {\n return this.subtle.decrypt({name: 'AES-CBC', iv: this.aesIV}, key, data);\n }\n}\n",
"class AESDecryptor {\n constructor() {\n // Static after running initTable\n this.rcon = [0x0, 0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36];\n\n this.subMix = [];\n this.subMix[0] = new Uint32Array(256);\n this.subMix[1] = new Uint32Array(256);\n this.subMix[2] = new Uint32Array(256);\n this.subMix[3] = new Uint32Array(256);\n\n this.invSubMix = [];\n this.invSubMix[0] = new Uint32Array(256);\n this.invSubMix[1] = new Uint32Array(256);\n this.invSubMix[2] = new Uint32Array(256);\n this.invSubMix[3] = new Uint32Array(256);\n\n this.sBox = new Uint32Array(256);\n this.invSBox = new Uint32Array(256);\n\n // Changes during runtime\n this.key = new Uint32Array(0);\n\n this.initTable();\n }\n\n // Using view.getUint32() also swaps the byte order.\n uint8ArrayToUint32Array_(arrayBuffer) {\n let view = new DataView(arrayBuffer);\n let newArray = new Uint32Array(4);\n for (let i = 0; i < newArray.length; i++) {\n newArray[i] = view.getUint32(i * 4);\n }\n return newArray;\n }\n\n initTable() {\n let sBox = this.sBox;\n let invSBox = this.invSBox;\n let subMix0 = this.subMix[0];\n let subMix1 = this.subMix[1];\n let subMix2 = this.subMix[2];\n let subMix3 = this.subMix[3];\n let invSubMix0 = this.invSubMix[0];\n let invSubMix1 = this.invSubMix[1];\n let invSubMix2 = this.invSubMix[2];\n let invSubMix3 = this.invSubMix[3];\n\n let d = new Uint32Array(256);\n let x = 0;\n let xi = 0;\n let i = 0;\n for (i = 0; i < 256; i++) {\n if (i < 128) {\n d[i] = i << 1;\n } else {\n d[i] = (i << 1) ^ 0x11b;\n }\n }\n\n for (i = 0; i < 256; i++) {\n let sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4);\n sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63;\n sBox[x] = sx;\n invSBox[sx] = x;\n\n // Compute multiplication\n let x2 = d[x];\n let x4 = d[x2];\n let x8 = d[x4];\n\n // Compute sub/invSub bytes, mix columns tables\n let t = (d[sx] * 0x101) ^ (sx * 0x1010100);\n subMix0[x] = (t << 24) | (t >>> 8);\n subMix1[x] = (t << 16) | (t >>> 16);\n subMix2[x] = (t << 8) | (t >>> 24);\n subMix3[x] = t;\n\n // Compute inv sub bytes, inv mix columns tables\n t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100);\n invSubMix0[sx] = (t << 24) | (t >>> 8);\n invSubMix1[sx] = (t << 16) | (t >>> 16);\n invSubMix2[sx] = (t << 8) | (t >>> 24);\n invSubMix3[sx] = t;\n\n // Compute next counter\n if (!x) {\n x = xi = 1;\n } else {\n x = x2 ^ d[d[d[x8 ^ x2]]];\n xi ^= d[d[xi]];\n }\n }\n }\n\n expandKey(keyBuffer) {\n // convert keyBuffer to Uint32Array\n let key = this.uint8ArrayToUint32Array_(keyBuffer);\n let sameKey = true;\n let offset = 0;\n\n while (offset < key.length && sameKey) {\n sameKey = (key[offset] === this.key[offset]);\n offset++;\n }\n\n if (sameKey) {\n return;\n }\n\n this.key = key;\n let keySize = this.keySize = key.length;\n\n if (keySize !== 4 && keySize !== 6 && keySize !== 8) {\n throw new Error('Invalid aes key size=' + keySize);\n }\n\n let ksRows = this.ksRows = (keySize + 6 + 1) * 4;\n let ksRow;\n let invKsRow;\n\n let keySchedule = this.keySchedule = new Uint32Array(this.ksRows);\n let invKeySchedule = this.invKeySchedule = new Uint32Array(this.ksRows);\n let sbox = this.sBox;\n let rcon = this.rcon;\n\n let invSubMix0 = this.invSubMix[0];\n let invSubMix1 = this.invSubMix[1];\n let invSubMix2 = this.invSubMix[2];\n let invSubMix3 = this.invSubMix[3];\n\n let prev;\n let t;\n\n for (ksRow = 0; ksRow < ksRows; ksRow++) {\n if (ksRow < keySize) {\n prev = keySchedule[ksRow] = key[ksRow];\n continue;\n }\n t = prev;\n\n if (ksRow % keySize === 0) {\n // Rot word\n t = (t << 8) | (t >>> 24);\n\n // Sub word\n t = (sbox[t >>> 24] << 24) | (sbox[(t >>> 16) & 0xff] << 16) | (sbox[(t >>> 8) & 0xff] << 8) | sbox[t & 0xff];\n\n // Mix Rcon\n t ^= rcon[(ksRow / keySize) | 0] << 24;\n } else if (keySize > 6 && ksRow % keySize === 4) {\n // Sub word\n t = (sbox[t >>> 24] << 24) | (sbox[(t >>> 16) & 0xff] << 16) | (sbox[(t >>> 8) & 0xff] << 8) | sbox[t & 0xff];\n }\n\n keySchedule[ksRow] = prev = (keySchedule[ksRow - keySize] ^ t) >>> 0;\n }\n\n for (invKsRow = 0; invKsRow < ksRows; invKsRow++) {\n ksRow = ksRows - invKsRow;\n if (invKsRow & 3) {\n t = keySchedule[ksRow];\n } else {\n t = keySchedule[ksRow - 4];\n }\n\n if (invKsRow < 4 || ksRow <= 4) {\n invKeySchedule[invKsRow] = t;\n } else {\n invKeySchedule[invKsRow] = invSubMix0[sbox[t >>> 24]] ^ invSubMix1[sbox[(t >>> 16) & 0xff]] ^ invSubMix2[sbox[(t >>> 8) & 0xff]] ^ invSubMix3[sbox[t & 0xff]];\n }\n\n invKeySchedule[invKsRow] = invKeySchedule[invKsRow] >>> 0;\n }\n }\n\n // Adding this as a method greatly improves performance.\n networkToHostOrderSwap(word) {\n return (word << 24) | ((word & 0xff00) << 8) | ((word & 0xff0000) >> 8) | (word >>> 24);\n }\n\n decrypt(inputArrayBuffer, offset, aesIV) {\n let nRounds = this.keySize + 6;\n let invKeySchedule = this.invKeySchedule;\n let invSBOX = this.invSBox;\n\n let invSubMix0 = this.invSubMix[0];\n let invSubMix1 = this.invSubMix[1];\n let invSubMix2 = this.invSubMix[2];\n let invSubMix3 = this.invSubMix[3];\n\n let initVector = this.uint8ArrayToUint32Array_(aesIV);\n let initVector0 = initVector[0];\n let initVector1 = initVector[1];\n let initVector2 = initVector[2];\n let initVector3 = initVector[3];\n\n let inputInt32 = new Int32Array(inputArrayBuffer);\n let outputInt32 = new Int32Array(inputInt32.length);\n\n let t0, t1, t2, t3;\n let s0, s1, s2, s3;\n let inputWords0, inputWords1, inputWords2, inputWords3;\n\n var ksRow, i;\n\n while (offset < inputInt32.length) {\n inputWords0 = this.networkToHostOrderSwap(inputInt32[offset]);\n inputWords1 = this.networkToHostOrderSwap(inputInt32[offset + 1]);\n inputWords2 = this.networkToHostOrderSwap(inputInt32[offset + 2]);\n inputWords3 = this.networkToHostOrderSwap(inputInt32[offset + 3]);\n\n s0 = inputWords0 ^ invKeySchedule[0];\n s1 = inputWords3 ^ invKeySchedule[1];\n s2 = inputWords2 ^ invKeySchedule[2];\n s3 = inputWords1 ^ invKeySchedule[3];\n\n ksRow = 4;\n\n // Iterate through the rounds of decryption\n for (i = 1; i < nRounds; i++) {\n t0 = invSubMix0[s0 >>> 24] ^ invSubMix1[(s1 >> 16) & 0xff] ^ invSubMix2[(s2 >> 8) & 0xff] ^ invSubMix3[s3 & 0xff] ^ invKeySchedule[ksRow];\n t1 = invSubMix0[s1 >>> 24] ^ invSubMix1[(s2 >> 16) & 0xff] ^ invSubMix2[(s3 >> 8) & 0xff] ^ invSubMix3[s0 & 0xff] ^ invKeySchedule[ksRow + 1];\n t2 = invSubMix0[s2 >>> 24] ^ invSubMix1[(s3 >> 16) & 0xff] ^ invSubMix2[(s0 >> 8) & 0xff] ^ invSubMix3[s1 & 0xff] ^ invKeySchedule[ksRow + 2];\n t3 = invSubMix0[s3 >>> 24] ^ invSubMix1[(s0 >> 16) & 0xff] ^ invSubMix2[(s1 >> 8) & 0xff] ^ invSubMix3[s2 & 0xff] ^ invKeySchedule[ksRow + 3];\n // Update state\n s0 = t0;\n s1 = t1;\n s2 = t2;\n s3 = t3;\n\n ksRow = ksRow + 4;\n }\n\n // Shift rows, sub bytes, add round key\n t0 = ((invSBOX[s0 >>> 24] << 24) ^ (invSBOX[(s1 >> 16) & 0xff] << 16) ^ (invSBOX[(s2 >> 8) & 0xff] << 8) ^ invSBOX[s3 & 0xff]) ^ invKeySchedule[ksRow];\n t1 = ((invSBOX[s1 >>> 24] << 24) ^ (invSBOX[(s2 >> 16) & 0xff] << 16) ^ (invSBOX[(s3 >> 8) & 0xff] << 8) ^ invSBOX[s0 & 0xff]) ^ invKeySchedule[ksRow + 1];\n t2 = ((invSBOX[s2 >>> 24] << 24) ^ (invSBOX[(s3 >> 16) & 0xff] << 16) ^ (invSBOX[(s0 >> 8) & 0xff] << 8) ^ invSBOX[s1 & 0xff]) ^ invKeySchedule[ksRow + 2];\n t3 = ((invSBOX[s3 >>> 24] << 24) ^ (invSBOX[(s0 >> 16) & 0xff] << 16) ^ (invSBOX[(s1 >> 8) & 0xff] << 8) ^ invSBOX[s2 & 0xff]) ^ invKeySchedule[ksRow + 3];\n ksRow = ksRow + 3;\n\n // Write\n outputInt32[offset] = this.networkToHostOrderSwap(t0 ^ initVector0);\n outputInt32[offset + 1] = this.networkToHostOrderSwap(t3 ^ initVector1);\n outputInt32[offset + 2] = this.networkToHostOrderSwap(t2 ^ initVector2);\n outputInt32[offset + 3] = this.networkToHostOrderSwap(t1 ^ initVector3);\n\n // reset initVector to last 4 unsigned int\n initVector0 = inputWords0;\n initVector1 = inputWords1;\n initVector2 = inputWords2;\n initVector3 = inputWords3;\n\n offset = offset + 4;\n }\n\n return outputInt32.buffer;\n }\n\n destroy() {\n this.key = undefined;\n this.keySize = undefined;\n this.ksRows = undefined;\n\n this.sBox = undefined;\n this.invSBox = undefined;\n this.subMix = undefined;\n this.invSubMix = undefined;\n this.keySchedule = undefined;\n this.invKeySchedule = undefined;\n\n this.rcon = undefined;\n }\n}\n\nexport default AESDecryptor;\n",
"import AESCrypto from './aes-crypto';\nimport FastAESKey from './fast-aes-key';\nimport AESDecryptor from './aes-decryptor';\n\nimport {ErrorTypes, ErrorDetails} from '../errors';\nimport {logger} from '../utils/logger';\n\nclass Decrypter {\n constructor(hls) {\n this.hls = hls;\n try {\n const browserCrypto = window ? window.crypto : crypto;\n this.subtle = browserCrypto.subtle || browserCrypto.webkitSubtle;\n } catch (e) {}\n\n this.disableWebCrypto = !this.supportsWebCrypto();\n }\n\n supportsWebCrypto() {\n return this.subtle && window.location.protocol === 'https:';\n }\n\n decrypt(data, key, iv, callback) {\n if (this.disableWebCrypto && this.hls.config.enableSoftwareAES) {\n logger.log('decrypting by JavaScript Implementation');\n if (!this.decryptor) {\n this.decryptor = new AESDecryptor();\n }\n this.decryptor.expandKey(key);\n callback(this.decryptor.decrypt(data, 0, iv));\n }\n else {\n logger.log('decrypting by WebCrypto API');\n const subtle = this.subtle;\n if (this.key !== key) {\n this.key = key;\n this.fastAesKey = new FastAESKey(subtle,key);\n }\n\n this.fastAesKey.expandKey().\n then((aesKey) => {\n // decrypt using web crypto\n let crypto = new AESCrypto(subtle,iv);\n crypto.decrypt(data, aesKey).\n then((result) => {\n callback(result);\n });\n }).\n catch ((err) => {\n this.onWebCryptoError(err, data, key, iv, callback);\n });\n }\n }\n\n onWebCryptoError(err, data, key, iv, callback) {\n let hls = this.hls;\n if (hls.config.enableSoftwareAES) {\n logger.log('disabling to use WebCrypto API');\n this.disableWebCrypto = true;\n this.decrypt(data, key, iv, callback);\n }\n else {\n logger.error(`decrypting error : ${err.message}`);\n hls.trigger(Event.ERROR, {type : ErrorTypes.MEDIA_ERROR, details : ErrorDetails.FRAG_DECRYPT_ERROR, fatal : true, reason : err.message});\n }\n }\n\n destroy() {\n let decryptor = this.decryptor;\n if (decryptor) {\n decryptor.destroy();\n this.decryptor = undefined;\n }\n }\n}\n\nexport default Decrypter;\n",
"class FastAESKey {\n constructor(subtle,key) {\n this.subtle = subtle;\n this.key = key;\n }\n\n expandKey() {\n return this.subtle.importKey('raw', this.key, {name: 'AES-CBC'}, false, ['encrypt', 'decrypt']);\n }\n}\n\nexport default FastAESKey;\n",
"/**\n * AAC demuxer\n */\nimport ADTS from './adts';\nimport {logger} from '../utils/logger';\nimport ID3 from '../demux/id3';\n\n class AACDemuxer {\n\n constructor(observer, id, remuxerClass, config, typeSupported) {\n this.observer = observer;\n this.id = id;\n this.remuxerClass = remuxerClass;\n this.config = config;\n this.remuxer = new this.remuxerClass(observer,id, config, typeSupported);\n this.insertDiscontinuity();\n }\n\n insertDiscontinuity() {\n this._aacTrack = {container : 'audio/adts', type: 'audio', id :-1, sequenceNumber: 0, isAAC : true , samples : [], len : 0};\n }\n\n static probe(data) {\n // check if data contains ID3 timestamp and ADTS sync worc\n var id3 = new ID3(data), offset,len;\n if(id3.hasTimeStamp) {\n // look for ADTS header (0xFFFx)\n for (offset = id3.length, len = data.length; offset < len - 1; offset++) {\n if ((data[offset] === 0xff) && (data[offset+1] & 0xf0) === 0xf0) {\n //logger.log('ADTS sync word found !');\n return true;\n }\n }\n }\n return false;\n }\n\n\n // feed incoming data to the front of the parsing pipeline\n push(data, audioCodec, videoCodec, timeOffset, cc, level, sn, duration,accurateTimeOffset, defaultInitPTS) {\n var track,\n id3 = new ID3(data),\n pts = 90*id3.timeStamp,\n config, frameLength, frameDuration, frameIndex, offset, headerLength, stamp, len, aacSample;\n\n let contiguous = false;\n if (cc !== this.lastCC) {\n logger.log(`${this.id} discontinuity detected`);\n this.lastCC = cc;\n this.insertDiscontinuity();\n this.remuxer.switchLevel();\n this.remuxer.insertDiscontinuity();\n } else if (level !== this.lastLevel) {\n logger.log('audio track switch detected');\n this.lastLevel = level;\n this.remuxer.switchLevel();\n this.insertDiscontinuity();\n } else if (sn === (this.lastSN+1)) {\n contiguous = true;\n }\n track = this._aacTrack;\n this.lastSN = sn;\n this.lastLevel = level;\n\n // look for ADTS header (0xFFFx)\n for (offset = id3.length, len = data.length; offset < len - 1; offset++) {\n if ((data[offset] === 0xff) && (data[offset+1] & 0xf0) === 0xf0) {\n break;\n }\n }\n\n if (!track.audiosamplerate) {\n config = ADTS.getAudioConfig(this.observer,data, offset, audioCodec);\n track.config = config.config;\n track.audiosamplerate = config.samplerate;\n track.channelCount = config.channelCount;\n track.codec = config.codec;\n track.manifestCodec = config.manifestCodec;\n track.duration = duration;\n logger.log(`parsed codec:${track.codec},rate:${config.samplerate},nb channel:${config.channelCount}`);\n }\n frameIndex = 0;\n frameDuration = 1024 * 90000 / track.audiosamplerate;\n while ((offset + 5) < len) {\n // The protection skip bit tells us if we have 2 bytes of CRC data at the end of the ADTS header\n headerLength = (!!(data[offset + 1] & 0x01) ? 7 : 9);\n // retrieve frame size\n frameLength = ((data[offset + 3] & 0x03) << 11) |\n (data[offset + 4] << 3) |\n ((data[offset + 5] & 0xE0) >>> 5);\n frameLength -= headerLength;\n //stamp = pes.pts;\n\n if ((frameLength > 0) && ((offset + headerLength + frameLength) <= len)) {\n stamp = pts + frameIndex * frameDuration;\n //logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}/${(stamp/90).toFixed(0)}`);\n aacSample = {unit: data.subarray(offset + headerLength, offset + headerLength + frameLength), pts: stamp, dts: stamp};\n track.samples.push(aacSample);\n track.len += frameLength;\n offset += frameLength + headerLength;\n frameIndex++;\n // look for ADTS header (0xFFFx)\n for ( ; offset < (len - 1); offset++) {\n if ((data[offset] === 0xff) && ((data[offset + 1] & 0xf0) === 0xf0)) {\n break;\n }\n }\n } else {\n break;\n }\n }\n this.remuxer.remux(level, sn , cc, this._aacTrack,{samples : []}, {samples : [ { pts: pts, dts : pts, unit : id3.payload} ]}, { samples: [] }, timeOffset, contiguous,accurateTimeOffset, defaultInitPTS);\n }\n\n destroy() {\n }\n\n}\n\nexport default AACDemuxer;\n",
"/**\n * ADTS parser helper\n */\nimport {logger} from '../utils/logger';\nimport {ErrorTypes, ErrorDetails} from '../errors';\n\n class ADTS {\n\n static getAudioConfig(observer, data, offset, audioCodec) {\n var adtsObjectType, // :int\n adtsSampleingIndex, // :int\n adtsExtensionSampleingIndex, // :int\n adtsChanelConfig, // :int\n config,\n userAgent = navigator.userAgent.toLowerCase(),\n manifestCodec = audioCodec,\n adtsSampleingRates = [\n 96000, 88200,\n 64000, 48000,\n 44100, 32000,\n 24000, 22050,\n 16000, 12000,\n 11025, 8000,\n 7350];\n // byte 2\n adtsObjectType = ((data[offset + 2] & 0xC0) >>> 6) + 1;\n adtsSampleingIndex = ((data[offset + 2] & 0x3C) >>> 2);\n if(adtsSampleingIndex > adtsSampleingRates.length-1) {\n observer.trigger(Event.ERROR, {type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.FRAG_PARSING_ERROR, fatal: true, reason: `invalid ADTS sampling index:${adtsSampleingIndex}`});\n return;\n }\n adtsChanelConfig = ((data[offset + 2] & 0x01) << 2);\n // byte 3\n adtsChanelConfig |= ((data[offset + 3] & 0xC0) >>> 6);\n logger.log(`manifest codec:${audioCodec},ADTS data:type:${adtsObjectType},sampleingIndex:${adtsSampleingIndex}[${adtsSampleingRates[adtsSampleingIndex]}Hz],channelConfig:${adtsChanelConfig}`);\n // firefox/Opera: freq less than 24kHz = AAC SBR (HE-AAC)\n if (/firefox|OPR/i.test(userAgent)) {\n if (adtsSampleingIndex >= 6) {\n adtsObjectType = 5;\n config = new Array(4);\n // HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies\n // there is a factor 2 between frame sample rate and output sample rate\n // multiply frequency by 2 (see table below, equivalent to substract 3)\n adtsExtensionSampleingIndex = adtsSampleingIndex - 3;\n } else {\n adtsObjectType = 2;\n config = new Array(2);\n adtsExtensionSampleingIndex = adtsSampleingIndex;\n }\n // Android : always use AAC\n } else if (userAgent.indexOf('android') !== -1) {\n adtsObjectType = 2;\n config = new Array(2);\n adtsExtensionSampleingIndex = adtsSampleingIndex;\n } else {\n /* for other browsers (Chrome/Vivaldi ...)\n always force audio type to be HE-AAC SBR, as some browsers do not support audio codec switch properly (like Chrome ...)\n */\n adtsObjectType = 5;\n config = new Array(4);\n // if (manifest codec is HE-AAC or HE-AACv2) OR (manifest codec not specified AND frequency less than 24kHz)\n if ((audioCodec && ((audioCodec.indexOf('mp4a.40.29') !== -1) ||\n (audioCodec.indexOf('mp4a.40.5') !== -1))) ||\n (!audioCodec && adtsSampleingIndex >= 6)) {\n // HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies\n // there is a factor 2 between frame sample rate and output sample rate\n // multiply frequency by 2 (see table below, equivalent to substract 3)\n adtsExtensionSampleingIndex = adtsSampleingIndex - 3;\n } else {\n // if (manifest codec is AAC) AND (frequency less than 24kHz AND nb channel is 1) OR (manifest codec not specified and mono audio)\n // Chrome fails to play back with low frequency AAC LC mono when initialized with HE-AAC. This is not a problem with stereo.\n if (audioCodec && audioCodec.indexOf('mp4a.40.2') !== -1 && (adtsSampleingIndex >= 6 && adtsChanelConfig === 1) ||\n (!audioCodec && adtsChanelConfig === 1)) {\n adtsObjectType = 2;\n config = new Array(2);\n }\n adtsExtensionSampleingIndex = adtsSampleingIndex;\n }\n }\n /* refer to http://wiki.multimedia.cx/index.php?title=MPEG-4_Audio#Audio_Specific_Config\n ISO 14496-3 (AAC).pdf - Table 1.13 — Syntax of AudioSpecificConfig()\n Audio Profile / Audio Object Type\n 0: Null\n 1: AAC Main\n 2: AAC LC (Low Complexity)\n 3: AAC SSR (Scalable Sample Rate)\n 4: AAC LTP (Long Term Prediction)\n 5: SBR (Spectral Band Replication)\n 6: AAC Scalable\n sampling freq\n 0: 96000 Hz\n 1: 88200 Hz\n 2: 64000 Hz\n 3: 48000 Hz\n 4: 44100 Hz\n 5: 32000 Hz\n 6: 24000 Hz\n 7: 22050 Hz\n 8: 16000 Hz\n 9: 12000 Hz\n 10: 11025 Hz\n 11: 8000 Hz\n 12: 7350 Hz\n 13: Reserved\n 14: Reserved\n 15: frequency is written explictly\n Channel Configurations\n These are the channel configurations:\n 0: Defined in AOT Specifc Config\n 1: 1 channel: front-center\n 2: 2 channels: front-left, front-right\n */\n // audioObjectType = profile => profile, the MPEG-4 Audio Object Type minus 1\n config[0] = adtsObjectType << 3;\n // samplingFrequencyIndex\n config[0] |= (adtsSampleingIndex & 0x0E) >> 1;\n config[1] |= (adtsSampleingIndex & 0x01) << 7;\n // channelConfiguration\n config[1] |= adtsChanelConfig << 3;\n if (adtsObjectType === 5) {\n // adtsExtensionSampleingIndex\n config[1] |= (adtsExtensionSampleingIndex & 0x0E) >> 1;\n config[2] = (adtsExtensionSampleingIndex & 0x01) << 7;\n // adtsObjectType (force to 2, chrome is checking that object type is less than 5 ???\n // https://chromium.googlesource.com/chromium/src.git/+/master/media/formats/mp4/aac.cc\n config[2] |= 2 << 2;\n config[3] = 0;\n }\n // trick manifest codec on Opera and Vivaldi, always use AAC LC\n if (/Vivaldi|OPR/i.test(userAgent)) {\n manifestCodec = 'mp4a.40.2';\n }\n return {config: config, samplerate: adtsSampleingRates[adtsSampleingIndex], channelCount: adtsChanelConfig, codec: ('mp4a.40.' + adtsObjectType), manifestCodec : manifestCodec};\n }\n}\n\nexport default ADTS;\n",
"/* inline demuxer.\n * probe fragments and instantiate appropriate demuxer depending on content type (TSDemuxer, AACDemuxer, ...)\n */\n\nimport Event from '../events';\nimport {ErrorTypes, ErrorDetails} from '../errors';\nimport AACDemuxer from '../demux/aacdemuxer';\nimport TSDemuxer from '../demux/tsdemuxer';\nimport MP4Remuxer from '../remux/mp4-remuxer';\nimport PassThroughRemuxer from '../remux/passthrough-remuxer';\n\nclass DemuxerInline {\n\n constructor(hls,id, typeSupported, config=null) {\n this.hls = hls;\n this.id = id;\n this.config = this.hls.config || config;\n this.typeSupported = typeSupported;\n }\n\n destroy() {\n var demuxer = this.demuxer;\n if (demuxer) {\n demuxer.destroy();\n }\n }\n\n push(data, audioCodec, videoCodec, timeOffset, cc, level, sn, duration,accurateTimeOffset,defaultInitPTS) {\n var demuxer = this.demuxer;\n if (!demuxer || \n // in case of continuity change, we might switch from content type (AAC container to TS container for example)\n // so let's check that current demuxer is still valid\n (cc !== this.cc && !demuxer.probe(data))) {\n let hls = this.hls,\n id = this.id,\n config = this.config,\n typeSupported = this.typeSupported;\n // probe for content type\n if (TSDemuxer.probe(data)) {\n if (this.typeSupported.mp2t === true) {\n demuxer = new TSDemuxer(hls, id, PassThroughRemuxer, config, typeSupported);\n } else {\n demuxer = new TSDemuxer(hls, id, MP4Remuxer, config, typeSupported);\n }\n demuxer.probe = TSDemuxer.probe;\n } else if(AACDemuxer.probe(data)) {\n demuxer = new AACDemuxer(hls, id, MP4Remuxer, config, typeSupported);\n demuxer.probe = AACDemuxer.probe;\n } else {\n hls.trigger(Event.ERROR, {type : ErrorTypes.MEDIA_ERROR, id : id, details: ErrorDetails.FRAG_PARSING_ERROR, fatal: true, reason: 'no demux matching with content found'});\n return;\n }\n this.demuxer = demuxer;\n }\n demuxer.push(data,audioCodec,videoCodec,timeOffset,cc,level,sn,duration,accurateTimeOffset,defaultInitPTS);\n this.cc = cc;\n }\n}\n\nexport default DemuxerInline;\n",
"/* demuxer web worker.\n * - listen to worker message, and trigger DemuxerInline upon reception of Fragments.\n * - provides MP4 Boxes back to main thread using [transferable objects](https://developers.google.com/web/updates/2011/12/Transferable-Objects-Lightning-Fast) in order to minimize message passing overhead.\n */\n\n import DemuxerInline from '../demux/demuxer-inline';\n import Event from '../events';\n import {enableLogs} from '../utils/logger';\n import EventEmitter from 'events';\n\nvar DemuxerWorker = function (self) {\n // observer setup\n var observer = new EventEmitter();\n observer.trigger = function trigger (event, ...data) {\n observer.emit(event, event, ...data);\n };\n\n observer.off = function off (event, ...data) {\n observer.removeListener(event, ...data);\n };\n\n var forwardMessage = function(ev,data) {\n self.postMessage({event: ev, data:data });\n };\n\n self.addEventListener('message', function (ev) {\n var data = ev.data;\n //console.log('demuxer cmd:' + data.cmd);\n switch (data.cmd) {\n case 'init':\n let config = JSON.parse(data.config);\n self.demuxer = new DemuxerInline(observer, data.id, data.typeSupported, config);\n try {\n enableLogs(config.debug === true);\n } catch(err) {\n console.warn('demuxerWorker: unable to enable logs');\n }\n // signal end of worker init\n forwardMessage('init',null);\n break;\n case 'demux':\n self.demuxer.push(new Uint8Array(data.data), data.audioCodec, data.videoCodec, data.timeOffset, data.cc, data.level, data.sn, data.duration,data.accurateTimeOffset,data.defaultInitPTS);\n break;\n default:\n break;\n }\n });\n\n // forward events to main thread\n observer.on(Event.FRAG_PARSING_INIT_SEGMENT, forwardMessage);\n observer.on(Event.FRAG_PARSED, forwardMessage);\n observer.on(Event.ERROR, forwardMessage);\n observer.on(Event.FRAG_PARSING_METADATA, forwardMessage);\n observer.on(Event.FRAG_PARSING_USERDATA, forwardMessage);\n observer.on(Event.INIT_PTS_FOUND, forwardMessage);\n\n // special case for FRAG_PARSING_DATA: pass data1/data2 as transferable object (no copy)\n observer.on(Event.FRAG_PARSING_DATA, function(ev, data) {\n let data1 = data.data1.buffer, data2 = data.data2.buffer;\n // remove data1 and data2 reference from data to avoid copying them ...\n delete data.data1;\n delete data.data2;\n self.postMessage({event: ev, data:data , data1 : data1, data2 : data2},[data1, data2]);\n });\n};\n\nexport default DemuxerWorker;\n\n",
"import Event from '../events';\nimport DemuxerInline from '../demux/demuxer-inline';\nimport DemuxerWorker from '../demux/demuxer-worker';\nimport {logger} from '../utils/logger';\nimport Decrypter from '../crypt/decrypter';\nimport {ErrorTypes, ErrorDetails} from '../errors';\n\nclass Demuxer {\n\n constructor(hls, id) {\n this.hls = hls;\n this.id = id;\n var typeSupported = {\n mp4 : MediaSource.isTypeSupported('video/mp4'),\n mp2t : hls.config.enableMP2TPassThrough && MediaSource.isTypeSupported('video/mp2t'),\n mpeg: MediaSource.isTypeSupported('audio/mpeg'),\n mp3: MediaSource.isTypeSupported('audio/mp4; codecs=\"mp3\"')\n };\n if (hls.config.enableWorker && (typeof(Worker) !== 'undefined')) {\n logger.log('demuxing in webworker');\n let w;\n try {\n let work = require('webworkify');\n w = this.w = work(DemuxerWorker);\n this.onwmsg = this.onWorkerMessage.bind(this);\n w.addEventListener('message', this.onwmsg);\n w.onerror = function(event) { hls.trigger(Event.ERROR, {type: ErrorTypes.OTHER_ERROR, details: ErrorDetails.INTERNAL_EXCEPTION, fatal: true, event : 'demuxerWorker', err : { message : event.message + ' (' + event.filename + ':' + event.lineno + ')' }});};\n w.postMessage({cmd: 'init', typeSupported : typeSupported, id : id, config: JSON.stringify(hls.config)});\n } catch(err) {\n logger.error('error while initializing DemuxerWorker, fallback on DemuxerInline');\n if (w) {\n // revoke the Object URL that was used to create demuxer worker, so as not to leak it\n URL.revokeObjectURL(w.objectURL);\n }\n this.demuxer = new DemuxerInline(hls,id,typeSupported);\n }\n } else {\n this.demuxer = new DemuxerInline(hls,id,typeSupported);\n }\n this.demuxInitialized = true;\n }\n\n destroy() {\n let w = this.w;\n if (w) {\n w.removeEventListener('message', this.onwmsg);\n w.terminate();\n this.w = null;\n } else {\n let demuxer = this.demuxer;\n if (demuxer) {\n demuxer.destroy();\n this.demuxer = null;\n }\n }\n let decrypter = this.decrypter;\n if (decrypter) {\n decrypter.destroy();\n this.decrypter = null;\n }\n }\n\n pushDecrypted(data, audioCodec, videoCodec, timeOffset, cc, level, sn, duration,accurateTimeOffset,defaultInitPTS) {\n let w = this.w;\n if (w) {\n // post fragment payload as transferable objects (no copy)\n w.postMessage({cmd: 'demux', data: data, audioCodec: audioCodec, videoCodec: videoCodec, timeOffset: timeOffset, cc: cc, level: level, sn : sn, duration: duration, accurateTimeOffset : accurateTimeOffset, defaultInitPTS : defaultInitPTS }, [data]);\n } else {\n let demuxer = this.demuxer;\n if (demuxer) {\n demuxer.push(new Uint8Array(data), audioCodec, videoCodec, timeOffset, cc, level, sn, duration,accurateTimeOffset,defaultInitPTS);\n }\n }\n }\n\n push(data, audioCodec, videoCodec, timeOffset, cc, level, sn, duration, decryptdata,accurateTimeOffset,defaultInitPTS) {\n if ((data.byteLength > 0) && (decryptdata != null) && (decryptdata.key != null) && (decryptdata.method === 'AES-128')) {\n if (this.decrypter == null) {\n this.decrypter = new Decrypter(this.hls);\n }\n var localthis = this;\n var startTime = performance.now();\n this.decrypter.decrypt(data, decryptdata.key.buffer, decryptdata.iv.buffer, function (decryptedData) {\n localthis.hls.trigger(Event.FRAG_DECRYPTED, { level : level, sn : sn, stats: { tstart: startTime, tdecrypt: performance.now() } });\n localthis.pushDecrypted(decryptedData, audioCodec, videoCodec, timeOffset, cc, level, sn, duration, accurateTimeOffset,defaultInitPTS);\n });\n } else {\n this.pushDecrypted(data, audioCodec, videoCodec, timeOffset, cc, level, sn, duration,accurateTimeOffset,defaultInitPTS);\n }\n }\n\n onWorkerMessage(ev) {\n let data = ev.data,\n hls = this.hls;\n //console.log('onWorkerMessage:' + data.event);\n switch(data.event) {\n case 'init':\n // revoke the Object URL that was used to create demuxer worker, so as not to leak it\n URL.revokeObjectURL(this.w.objectURL);\n break;\n // special case for FRAG_PARSING_DATA: data1 and data2 are transferable objects\n case Event.FRAG_PARSING_DATA:\n data.data.data1 = new Uint8Array(data.data1);\n data.data.data2 = new Uint8Array(data.data2);\n /* falls through */\n default:\n hls.trigger(data.event, data.data);\n break;\n }\n }\n}\n\nexport default Demuxer;\n\n",
"/**\n * Parser for exponential Golomb codes, a variable-bitwidth number encoding scheme used by h264.\n*/\n\nimport {logger} from '../utils/logger';\n\nclass ExpGolomb {\n\n constructor(data) {\n this.data = data;\n // the number of bytes left to examine in this.data\n this.bytesAvailable = data.byteLength;\n // the current word being examined\n this.word = 0; // :uint\n // the number of bits left to examine in the current word\n this.bitsAvailable = 0; // :uint\n }\n\n // ():void\n loadWord() {\n var\n data = this.data,\n bytesAvailable = this.bytesAvailable,\n position = data.byteLength - bytesAvailable,\n workingBytes = new Uint8Array(4),\n availableBytes = Math.min(4, bytesAvailable);\n if (availableBytes === 0) {\n throw new Error('no bytes available');\n }\n workingBytes.set(data.subarray(position, position + availableBytes));\n this.word = new DataView(workingBytes.buffer).getUint32(0);\n // track the amount of this.data that has been processed\n this.bitsAvailable = availableBytes * 8;\n this.bytesAvailable -= availableBytes;\n }\n\n // (count:int):void\n skipBits(count) {\n var skipBytes; // :int\n if (this.bitsAvailable > count) {\n this.word <<= count;\n this.bitsAvailable -= count;\n } else {\n count -= this.bitsAvailable;\n skipBytes = count >> 3;\n count -= (skipBytes >> 3);\n this.bytesAvailable -= skipBytes;\n this.loadWord();\n this.word <<= count;\n this.bitsAvailable -= count;\n }\n }\n\n // (size:int):uint\n readBits(size) {\n var\n bits = Math.min(this.bitsAvailable, size), // :uint\n valu = this.word >>> (32 - bits); // :uint\n if (size > 32) {\n logger.error('Cannot read more than 32 bits at a time');\n }\n this.bitsAvailable -= bits;\n if (this.bitsAvailable > 0) {\n this.word <<= bits;\n } else if (this.bytesAvailable > 0) {\n this.loadWord();\n }\n bits = size - bits;\n if (bits > 0 && this.bitsAvailable) {\n return valu << bits | this.readBits(bits);\n } else {\n return valu;\n }\n }\n\n // ():uint\n skipLZ() {\n var leadingZeroCount; // :uint\n for (leadingZeroCount = 0; leadingZeroCount < this.bitsAvailable; ++leadingZeroCount) {\n if (0 !== (this.word & (0x80000000 >>> leadingZeroCount))) {\n // the first bit of working word is 1\n this.word <<= leadingZeroCount;\n this.bitsAvailable -= leadingZeroCount;\n return leadingZeroCount;\n }\n }\n // we exhausted word and still have not found a 1\n this.loadWord();\n return leadingZeroCount + this.skipLZ();\n }\n\n // ():void\n skipUEG() {\n this.skipBits(1 + this.skipLZ());\n }\n\n // ():void\n skipEG() {\n this.skipBits(1 + this.skipLZ());\n }\n\n // ():uint\n readUEG() {\n var clz = this.skipLZ(); // :uint\n return this.readBits(clz + 1) - 1;\n }\n\n // ():int\n readEG() {\n var valu = this.readUEG(); // :int\n if (0x01 & valu) {\n // the number is odd if the low order bit is set\n return (1 + valu) >>> 1; // add 1 to make it even, and divide by 2\n } else {\n return -1 * (valu >>> 1); // divide by two then make it negative\n }\n }\n\n // Some convenience functions\n // :Boolean\n readBoolean() {\n return 1 === this.readBits(1);\n }\n\n // ():int\n readUByte() {\n return this.readBits(8);\n }\n\n // ():int\n readUShort() {\n return this.readBits(16);\n }\n // ():int\n readUInt() {\n return this.readBits(32);\n }\n\n /**\n * Advance the ExpGolomb decoder past a scaling list. The scaling\n * list is optionally transmitted as part of a sequence parameter\n * set and is not relevant to transmuxing.\n * @param count {number} the number of entries in this scaling list\n * @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1\n */\n skipScalingList(count) {\n var\n lastScale = 8,\n nextScale = 8,\n j,\n deltaScale;\n for (j = 0; j < count; j++) {\n if (nextScale !== 0) {\n deltaScale = this.readEG();\n nextScale = (lastScale + deltaScale + 256) % 256;\n }\n lastScale = (nextScale === 0) ? lastScale : nextScale;\n }\n }\n\n /**\n * Read a sequence parameter set and return some interesting video\n * properties. A sequence parameter set is the H264 metadata that\n * describes the properties of upcoming video frames.\n * @param data {Uint8Array} the bytes of a sequence parameter set\n * @return {object} an object with configuration parsed from the\n * sequence parameter set, including the dimensions of the\n * associated video frames.\n */\n readSPS() {\n var\n frameCropLeftOffset = 0,\n frameCropRightOffset = 0,\n frameCropTopOffset = 0,\n frameCropBottomOffset = 0,\n sarScale = 1,\n profileIdc,profileCompat,levelIdc,\n numRefFramesInPicOrderCntCycle, picWidthInMbsMinus1,\n picHeightInMapUnitsMinus1,\n frameMbsOnlyFlag,\n scalingListCount,\n i,\n readUByte = this.readUByte.bind(this),\n readBits = this.readBits.bind(this),\n readUEG = this.readUEG.bind(this),\n readBoolean = this.readBoolean.bind(this),\n skipBits = this.skipBits.bind(this),\n skipEG = this.skipEG.bind(this),\n skipUEG = this.skipUEG.bind(this),\n skipScalingList = this.skipScalingList.bind(this);\n\n readUByte();\n profileIdc = readUByte(); // profile_idc\n profileCompat = readBits(5); // constraint_set[0-4]_flag, u(5)\n skipBits(3); // reserved_zero_3bits u(3),\n levelIdc = readUByte(); //level_idc u(8)\n skipUEG(); // seq_parameter_set_id\n // some profiles have more optional data we don't need\n if (profileIdc === 100 ||\n profileIdc === 110 ||\n profileIdc === 122 ||\n profileIdc === 244 ||\n profileIdc === 44 ||\n profileIdc === 83 ||\n profileIdc === 86 ||\n profileIdc === 118 ||\n profileIdc === 128) {\n var chromaFormatIdc = readUEG();\n if (chromaFormatIdc === 3) {\n skipBits(1); // separate_colour_plane_flag\n }\n skipUEG(); // bit_depth_luma_minus8\n skipUEG(); // bit_depth_chroma_minus8\n skipBits(1); // qpprime_y_zero_transform_bypass_flag\n if (readBoolean()) { // seq_scaling_matrix_present_flag\n scalingListCount = (chromaFormatIdc !== 3) ? 8 : 12;\n for (i = 0; i < scalingListCount; i++) {\n if (readBoolean()) { // seq_scaling_list_present_flag[ i ]\n if (i < 6) {\n skipScalingList(16);\n } else {\n skipScalingList(64);\n }\n }\n }\n }\n }\n skipUEG(); // log2_max_frame_num_minus4\n var picOrderCntType = readUEG();\n if (picOrderCntType === 0) {\n readUEG(); //log2_max_pic_order_cnt_lsb_minus4\n } else if (picOrderCntType === 1) {\n skipBits(1); // delta_pic_order_always_zero_flag\n skipEG(); // offset_for_non_ref_pic\n skipEG(); // offset_for_top_to_bottom_field\n numRefFramesInPicOrderCntCycle = readUEG();\n for(i = 0; i < numRefFramesInPicOrderCntCycle; i++) {\n skipEG(); // offset_for_ref_frame[ i ]\n }\n }\n skipUEG(); // max_num_ref_frames\n skipBits(1); // gaps_in_frame_num_value_allowed_flag\n picWidthInMbsMinus1 = readUEG();\n picHeightInMapUnitsMinus1 = readUEG();\n frameMbsOnlyFlag = readBits(1);\n if (frameMbsOnlyFlag === 0) {\n skipBits(1); // mb_adaptive_frame_field_flag\n }\n skipBits(1); // direct_8x8_inference_flag\n if (readBoolean()) { // frame_cropping_flag\n frameCropLeftOffset = readUEG();\n frameCropRightOffset = readUEG();\n frameCropTopOffset = readUEG();\n frameCropBottomOffset = readUEG();\n }\n if (readBoolean()) {\n // vui_parameters_present_flag\n if (readBoolean()) {\n // aspect_ratio_info_present_flag\n let sarRatio;\n const aspectRatioIdc = readUByte();\n switch (aspectRatioIdc) {\n case 1: sarRatio = [1,1]; break;\n case 2: sarRatio = [12,11]; break;\n case 3: sarRatio = [10,11]; break;\n case 4: sarRatio = [16,11]; break;\n case 5: sarRatio = [40,33]; break;\n case 6: sarRatio = [24,11]; break;\n case 7: sarRatio = [20,11]; break;\n case 8: sarRatio = [32,11]; break;\n case 9: sarRatio = [80,33]; break;\n case 10: sarRatio = [18,11]; break;\n case 11: sarRatio = [15,11]; break;\n case 12: sarRatio = [64,33]; break;\n case 13: sarRatio = [160,99]; break;\n case 14: sarRatio = [4,3]; break;\n case 15: sarRatio = [3,2]; break;\n case 16: sarRatio = [2,1]; break;\n case 255: {\n sarRatio = [readUByte() << 8 | readUByte(), readUByte() << 8 | readUByte()];\n break;\n }\n }\n if (sarRatio) {\n sarScale = sarRatio[0] / sarRatio[1];\n }\n }\n }\n return {\n width: Math.ceil((((picWidthInMbsMinus1 + 1) * 16) - frameCropLeftOffset * 2 - frameCropRightOffset * 2) * sarScale),\n height: ((2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16) - ((frameMbsOnlyFlag? 2 : 4) * (frameCropTopOffset + frameCropBottomOffset))\n };\n }\n\n readSliceType() {\n // skip NALu type\n this.readUByte();\n // discard first_mb_in_slice\n this.readUEG();\n // return slice_type\n return this.readUEG();\n }\n}\n\nexport default ExpGolomb;\n",
"/**\n * ID3 parser\n */\nimport {logger} from '../utils/logger';\n//import Hex from '../utils/hex';\n\n class ID3 {\n\n constructor(data) {\n this._hasTimeStamp = false;\n var offset = 0, byte1,byte2,byte3,byte4,tagSize,endPos,header,len;\n do {\n header = this.readUTF(data,offset,3);\n offset+=3;\n // first check for ID3 header\n if (header === 'ID3') {\n // skip 24 bits\n offset += 3;\n // retrieve tag(s) length\n byte1 = data[offset++] & 0x7f;\n byte2 = data[offset++] & 0x7f;\n byte3 = data[offset++] & 0x7f;\n byte4 = data[offset++] & 0x7f;\n tagSize = (byte1 << 21) + (byte2 << 14) + (byte3 << 7) + byte4;\n endPos = offset + tagSize;\n //logger.log(`ID3 tag found, size/end: ${tagSize}/${endPos}`);\n\n // read ID3 tags\n this._parseID3Frames(data, offset,endPos);\n offset = endPos;\n } else if (header === '3DI') {\n // http://id3.org/id3v2.4.0-structure chapter 3.4. ID3v2 footer\n offset += 7;\n logger.log(`3DI footer found, end: ${offset}`);\n } else {\n offset -= 3;\n len = offset;\n if (len) {\n //logger.log(`ID3 len: ${len}`);\n if (!this.hasTimeStamp) {\n logger.warn('ID3 tag found, but no timestamp');\n }\n this._length = len;\n this._payload = data.subarray(0,len);\n }\n return;\n }\n } while (true);\n }\n\n readUTF(data,start,len) {\n\n var result = '',offset = start, end = start + len;\n do {\n result += String.fromCharCode(data[offset++]);\n } while(offset < end);\n return result;\n }\n\n _parseID3Frames(data,offset,endPos) {\n var tagId,tagLen,tagStart,tagFlags,timestamp;\n while(offset + 8 <= endPos) {\n tagId = this.readUTF(data,offset,4);\n offset +=4;\n\n tagLen = data[offset++] << 24 +\n data[offset++] << 16 +\n data[offset++] << 8 +\n data[offset++];\n\n tagFlags = data[offset++] << 8 +\n data[offset++];\n\n tagStart = offset;\n //logger.log(\"ID3 tag id:\" + tagId);\n switch(tagId) {\n case 'PRIV':\n //logger.log('parse frame:' + Hex.hexDump(data.subarray(offset,endPos)));\n // owner should be \"com.apple.streaming.transportStreamTimestamp\"\n if (this.readUTF(data,offset,44) === 'com.apple.streaming.transportStreamTimestamp') {\n offset+=44;\n // smelling even better ! we found the right descriptor\n // skip null character (string end) + 3 first bytes\n offset+= 4;\n\n // timestamp is 33 bit expressed as a big-endian eight-octet number, with the upper 31 bits set to zero.\n var pts33Bit = data[offset++] & 0x1;\n this._hasTimeStamp = true;\n\n timestamp = ((data[offset++] << 23) +\n (data[offset++] << 15) +\n (data[offset++] << 7) +\n data[offset++]) /45;\n\n if (pts33Bit) {\n timestamp += 47721858.84; // 2^32 / 90\n }\n timestamp = Math.round(timestamp);\n logger.trace(`ID3 timestamp found: ${timestamp}`);\n this._timeStamp = timestamp;\n }\n break;\n default:\n break;\n }\n }\n }\n\n get hasTimeStamp() {\n return this._hasTimeStamp;\n }\n\n get timeStamp() {\n return this._timeStamp;\n }\n\n get length() {\n return this._length;\n }\n\n get payload() {\n return this._payload;\n }\n\n}\n\nexport default ID3;\n\n",
"/**\n * highly optimized TS demuxer:\n * parse PAT, PMT\n * extract PES packet from audio and video PIDs\n * extract AVC/H264 NAL units and AAC/ADTS samples from PES packet\n * trigger the remuxer upon parsing completion\n * it also tries to workaround as best as it can audio codec switch (HE-AAC to AAC and vice versa), without having to restart the MediaSource.\n * it also controls the remuxing process :\n * upon discontinuity or level switch detection, it will also notifies the remuxer so that it can reset its state.\n*/\n\n import ADTS from './adts';\n import Event from '../events';\n import ExpGolomb from './exp-golomb';\n// import Hex from '../utils/hex';\n import {logger} from '../utils/logger';\n import {ErrorTypes, ErrorDetails} from '../errors';\n\n class TSDemuxer {\n\n constructor(observer, id, remuxerClass, config, typeSupported) {\n this.observer = observer;\n this.id = id;\n this.remuxerClass = remuxerClass;\n this.config = config;\n this.typeSupported = typeSupported;\n this.lastCC = 0;\n this.remuxer = new this.remuxerClass(observer, id, config, typeSupported);\n }\n\n static probe(data) {\n // a TS fragment should contain at least 3 TS packets, a PAT, a PMT, and one PID, each starting with 0x47\n if (data.length >= 3*188 && data[0] === 0x47 && data[188] === 0x47 && data[2*188] === 0x47) {\n return true;\n } else {\n return false;\n }\n }\n\n switchLevel() {\n this.pmtParsed = false;\n this._pmtId = -1;\n this._avcTrack = {container : 'video/mp2t', type: 'video', id :-1, sequenceNumber: 0, samples : [], len : 0, dropped : 0};\n this._audioTrack = {container : 'video/mp2t', type: 'audio', id :-1, sequenceNumber: 0, samples : [], len : 0, isAAC: true};\n this._id3Track = {type: 'id3', id :-1, sequenceNumber: 0, samples : [], len : 0};\n this._txtTrack = {type: 'text', id: -1, sequenceNumber: 0, samples : [], len : 0};\n // flush any partial content\n this.aacOverFlow = null;\n this.aacLastPTS = null;\n this.avcSample = null;\n this.remuxer.switchLevel();\n }\n\n insertDiscontinuity() {\n this.switchLevel();\n this.remuxer.insertDiscontinuity();\n }\n\n // feed incoming data to the front of the parsing pipeline\n push(data, audioCodec, videoCodec, timeOffset, cc, level, sn, duration,accurateTimeOffset,defaultInitPTS) {\n var start, len = data.length, stt, pid, atf, offset,pes,\n codecsOnly = this.remuxer.passthrough,\n unknownPIDs = false;\n\n this.audioCodec = audioCodec;\n this.videoCodec = videoCodec;\n this._duration = duration;\n this.contiguous = false;\n this.accurateTimeOffset = accurateTimeOffset;\n if (cc !== this.lastCC) {\n logger.log('discontinuity detected');\n this.insertDiscontinuity();\n this.lastCC = cc;\n }\n if (level !== this.lastLevel) {\n logger.log('level switch detected');\n this.switchLevel();\n this.lastLevel = level;\n } else if (sn === (this.lastSN+1)) {\n this.contiguous = true;\n }\n this.lastSN = sn;\n\n var pmtParsed = this.pmtParsed,\n avcTrack = this._avcTrack,\n audioTrack = this._audioTrack,\n id3Track = this._id3Track,\n avcId = avcTrack.id,\n audioId = audioTrack.id,\n id3Id = id3Track.id,\n pmtId = this._pmtId,\n avcData = avcTrack.pesData,\n audioData = audioTrack.pesData,\n id3Data = id3Track.pesData,\n parsePAT = this._parsePAT,\n parsePMT = this._parsePMT,\n parsePES = this._parsePES,\n parseAVCPES = this._parseAVCPES.bind(this),\n parseAACPES = this._parseAACPES.bind(this),\n parseMPEGPES = this._parseMPEGPES.bind(this),\n parseID3PES = this._parseID3PES.bind(this);\n\n // don't parse last TS packet if incomplete\n len -= len % 188;\n // loop through TS packets\n for (start = 0; start < len; start += 188) {\n if (data[start] === 0x47) {\n stt = !!(data[start + 1] & 0x40);\n // pid is a 13-bit field starting at the last bit of TS[1]\n pid = ((data[start + 1] & 0x1f) << 8) + data[start + 2];\n atf = (data[start + 3] & 0x30) >> 4;\n // if an adaption field is present, its length is specified by the fifth byte of the TS packet header.\n if (atf > 1) {\n offset = start + 5 + data[start + 4];\n // continue if there is only adaptation field\n if (offset === (start + 188)) {\n continue;\n }\n } else {\n offset = start + 4;\n }\n switch(pid) {\n case avcId:\n if (stt) {\n if (avcData && (pes = parsePES(avcData))) {\n parseAVCPES(pes,false);\n if (codecsOnly) {\n // if we have video codec info AND\n // if audio PID is undefined OR if we have audio codec info,\n // we have all codec info !\n if (avcTrack.codec && (audioId === -1 || audioTrack.codec)) {\n this.remux(level,sn,cc,data,timeOffset);\n return;\n }\n }\n }\n avcData = {data: [], size: 0};\n }\n if (avcData) {\n avcData.data.push(data.subarray(offset, start + 188));\n avcData.size += start + 188 - offset;\n }\n break;\n case audioId:\n if (stt) {\n if (audioData && (pes = parsePES(audioData))) {\n if (audioTrack.isAAC) {\n parseAACPES(pes);\n } else {\n parseMPEGPES(pes);\n }\n if (codecsOnly) {\n // here we now that we have audio codec info\n // if video PID is undefined OR if we have video codec info,\n // we have all codec infos !\n if (audioTrack.codec && (avcId === -1 || avcTrack.codec)) {\n this.remux(level,sn,cc,data,timeOffset);\n return;\n }\n }\n }\n audioData = {data: [], size: 0};\n }\n if (audioData) {\n audioData.data.push(data.subarray(offset, start + 188));\n audioData.size += start + 188 - offset;\n }\n break;\n case id3Id:\n if (stt) {\n if (id3Data && (pes = parsePES(id3Data))) {\n parseID3PES(pes);\n }\n id3Data = {data: [], size: 0};\n }\n if (id3Data) {\n id3Data.data.push(data.subarray(offset, start + 188));\n id3Data.size += start + 188 - offset;\n }\n break;\n case 0:\n if (stt) {\n offset += data[offset] + 1;\n }\n pmtId = this._pmtId = parsePAT(data, offset);\n break;\n case pmtId:\n if (stt) {\n offset += data[offset] + 1;\n }\n let parsedPIDs = parsePMT(data, offset, this.typeSupported.mpeg === true || this.typeSupported.mp3 === true);\n\n // only update track id if track PID found while parsing PMT\n // this is to avoid resetting the PID to -1 in case\n // track PID transiently disappears from the stream\n // this could happen in case of transient missing audio samples for example\n avcId = parsedPIDs.avc;\n if (avcId > 0) {\n avcTrack.id = avcId;\n }\n audioId = parsedPIDs.audio;\n if (audioId > 0) {\n audioTrack.id = audioId;\n audioTrack.isAAC = parsedPIDs.isAAC;\n }\n id3Id = parsedPIDs.id3;\n if (id3Id > 0) {\n id3Track.id = id3Id;\n }\n if (unknownPIDs && !pmtParsed) {\n logger.log('reparse from beginning');\n unknownPIDs = false;\n // we set it to -188, the += 188 in the for loop will reset start to 0\n start = -188;\n }\n pmtParsed = this.pmtParsed = true;\n break;\n case 17:\n case 0x1fff:\n break;\n default:\n unknownPIDs = true;\n break;\n }\n } else {\n this.observer.trigger(Event.ERROR, {type : ErrorTypes.MEDIA_ERROR, id : this.id, details: ErrorDetails.FRAG_PARSING_ERROR, fatal: false, reason: 'TS packet did not start with 0x47'});\n }\n }\n // try to parse last PES packets\n if (avcData && (pes = parsePES(avcData))) {\n parseAVCPES(pes,true);\n avcTrack.pesData = null;\n } else {\n // either avcData null or PES truncated, keep it for next frag parsing\n avcTrack.pesData = avcData;\n }\n\n if (audioData && (pes = parsePES(audioData))) {\n if (audioTrack.isAAC) {\n parseAACPES(pes);\n } else {\n parseMPEGPES(pes);\n }\n audioTrack.pesData = null;\n } else {\n if (audioData && audioData.size) {\n logger.log('last AAC PES packet truncated,might overlap between fragments');\n }\n // either audioData null or PES truncated, keep it for next frag parsing\n audioTrack.pesData = audioData;\n }\n\n if (id3Data && (pes = parsePES(id3Data))) {\n parseID3PES(pes);\n id3Track.pesData = null;\n } else {\n // either id3Data null or PES truncated, keep it for next frag parsing\n id3Track.pesData = id3Data;\n }\n this.remux(level,sn,cc,null,timeOffset,defaultInitPTS);\n }\n\n remux(level, sn, cc, data, timeOffset,defaultInitPTS) {\n let avcTrack = this._avcTrack, samples = avcTrack.samples, nbNalu = 0, naluLen = 0;\n\n // compute total/avc sample length and nb of NAL units\n for (let i = 0; i < samples.length; i++) {\n let sample = samples[i], units = sample.units.units, nbUnits = units.length, sampleLen = 0;\n for (let j = 0; j < nbUnits; j++) {\n sampleLen += units[j].data.length;\n }\n naluLen += sampleLen;\n nbNalu += nbUnits;\n sample.length = sampleLen;\n }\n avcTrack.len = naluLen;\n avcTrack.nbNalu = nbNalu;\n this.remuxer.remux(level, sn, cc, this._audioTrack, this._avcTrack, this._id3Track, this._txtTrack, timeOffset, this.contiguous, this.accurateTimeOffset, defaultInitPTS, data);\n }\n\n destroy() {\n this.switchLevel();\n this._initPTS = this._initDTS = undefined;\n this._duration = 0;\n }\n\n _parsePAT(data, offset) {\n // skip the PSI header and parse the first PMT entry\n return (data[offset + 10] & 0x1F) << 8 | data[offset + 11];\n //logger.log('PMT PID:' + this._pmtId);\n }\n\n _parsePMT(data, offset, mpegSupported) {\n var sectionLength, tableEnd, programInfoLength, pid, result = { audio : -1, avc : -1, id3 : -1, isAAC : true};\n sectionLength = (data[offset + 1] & 0x0f) << 8 | data[offset + 2];\n tableEnd = offset + 3 + sectionLength - 4;\n // to determine where the table is, we have to figure out how\n // long the program info descriptors are\n programInfoLength = (data[offset + 10] & 0x0f) << 8 | data[offset + 11];\n // advance the offset to the first entry in the mapping table\n offset += 12 + programInfoLength;\n while (offset < tableEnd) {\n pid = (data[offset + 1] & 0x1F) << 8 | data[offset + 2];\n switch(data[offset]) {\n // ISO/IEC 13818-7 ADTS AAC (MPEG-2 lower bit-rate audio)\n case 0x0f:\n //logger.log('AAC PID:' + pid);\n if (result.audio === -1) {\n result.audio = pid;\n }\n break;\n // Packetized metadata (ID3)\n case 0x15:\n //logger.log('ID3 PID:' + pid);\n if (result.id3 === -1) {\n result.id3 = pid;\n }\n break;\n // ITU-T Rec. H.264 and ISO/IEC 14496-10 (lower bit-rate video)\n case 0x1b:\n //logger.log('AVC PID:' + pid);\n if (result.avc === -1) {\n result.avc = pid;\n }\n break;\n // ISO/IEC 11172-3 (MPEG-1 audio)\n // or ISO/IEC 13818-3 (MPEG-2 halved sample rate audio)\n case 0x03:\n case 0x04:\n //logger.log('MPEG PID:' + pid);\n if (!mpegSupported) {\n logger.log('MPEG audio found, not supported in this browser for now');\n } else if (result.audio === -1) {\n result.audio = pid;\n result.isAAC = false;\n }\n break;\n case 0x24:\n logger.warn('HEVC stream type found, not supported for now');\n break;\n default:\n logger.log('unkown stream type:' + data[offset]);\n break;\n }\n // move to the next table entry\n // skip past the elementary stream descriptors, if present\n offset += ((data[offset + 3] & 0x0F) << 8 | data[offset + 4]) + 5;\n }\n return result;\n }\n\n _parsePES(stream) {\n var i = 0, frag, pesFlags, pesPrefix, pesLen, pesHdrLen, pesData, pesPts, pesDts, payloadStartOffset, data = stream.data;\n // safety check\n if (!stream || stream.size === 0) {\n return null;\n }\n\n // we might need up to 19 bytes to read PES header\n // if first chunk of data is less than 19 bytes, let's merge it with following ones until we get 19 bytes\n // usually only one merge is needed (and this is rare ...)\n while(data[0].length < 19 && data.length > 1) {\n let newData = new Uint8Array(data[0].length + data[1].length);\n newData.set(data[0]);\n newData.set(data[1], data[0].length);\n data[0] = newData;\n data.splice(1,1);\n }\n //retrieve PTS/DTS from first fragment\n frag = data[0];\n pesPrefix = (frag[0] << 16) + (frag[1] << 8) + frag[2];\n if (pesPrefix === 1) {\n pesLen = (frag[4] << 8) + frag[5];\n // if PES parsed length is not zero and greater than total received length, stop parsing. PES might be truncated\n // minus 6 : PES header size\n if (pesLen && pesLen > stream.size - 6) {\n return null;\n }\n pesFlags = frag[7];\n if (pesFlags & 0xC0) {\n /* PES header described here : http://dvd.sourceforge.net/dvdinfo/pes-hdr.html\n as PTS / DTS is 33 bit we cannot use bitwise operator in JS,\n as Bitwise operators treat their operands as a sequence of 32 bits */\n pesPts = (frag[9] & 0x0E) * 536870912 +// 1 << 29\n (frag[10] & 0xFF) * 4194304 +// 1 << 22\n (frag[11] & 0xFE) * 16384 +// 1 << 14\n (frag[12] & 0xFF) * 128 +// 1 << 7\n (frag[13] & 0xFE) / 2;\n // check if greater than 2^32 -1\n if (pesPts > 4294967295) {\n // decrement 2^33\n pesPts -= 8589934592;\n }\n if (pesFlags & 0x40) {\n pesDts = (frag[14] & 0x0E ) * 536870912 +// 1 << 29\n (frag[15] & 0xFF ) * 4194304 +// 1 << 22\n (frag[16] & 0xFE ) * 16384 +// 1 << 14\n (frag[17] & 0xFF ) * 128 +// 1 << 7\n (frag[18] & 0xFE ) / 2;\n // check if greater than 2^32 -1\n if (pesDts > 4294967295) {\n // decrement 2^33\n pesDts -= 8589934592;\n }\n if (pesPts - pesDts > 60*90000) {\n logger.warn(`${Math.round((pesPts - pesDts)/90000)}s delta between PTS and DTS, align them`);\n pesPts = pesDts;\n }\n } else {\n pesDts = pesPts;\n }\n }\n pesHdrLen = frag[8];\n // 9 bytes : 6 bytes for PES header + 3 bytes for PES extension\n payloadStartOffset = pesHdrLen + 9;\n\n stream.size -= payloadStartOffset;\n //reassemble PES packet\n pesData = new Uint8Array(stream.size);\n for( let j = 0, dataLen = data.length; j < dataLen ; j++) {\n frag = data[j];\n let len = frag.byteLength;\n if (payloadStartOffset) {\n if (payloadStartOffset > len) {\n // trim full frag if PES header bigger than frag\n payloadStartOffset-=len;\n continue;\n } else {\n // trim partial frag if PES header smaller than frag\n frag = frag.subarray(payloadStartOffset);\n len-=payloadStartOffset;\n payloadStartOffset = 0;\n }\n }\n pesData.set(frag, i);\n i+=len;\n }\n if (pesLen) {\n // payload size : remove PES header + PES extension\n pesLen -= pesHdrLen+3;\n }\n return {data: pesData, pts: pesPts, dts: pesDts, len: pesLen};\n } else {\n return null;\n }\n }\n\n pushAccesUnit(avcSample,avcTrack) {\n if (avcSample.units.units.length && avcSample.frame) {\n // only push AVC sample if starting with a keyframe is not mandatory OR\n // if keyframe already found in this fragment OR\n // keyframe found in last fragment (track.sps) AND\n // samples already appended (we already found a keyframe in this fragment) OR fragment is contiguous\n if (!this.config.forceKeyFrameOnDiscontinuity ||\n avcSample.key === true ||\n (avcTrack.sps && (avcTrack.samples.length || this.contiguous))) {\n avcTrack.samples.push(avcSample);\n } else {\n // dropped samples, track it\n avcTrack.dropped++;\n }\n }\n if(avcSample.debug.length) {\n logger.log(avcSample.pts + '/' + avcSample.dts + ':' + avcSample.debug + ',' + avcSample.units.length);\n }\n }\n\n _parseAVCPES(pes,last) {\n //logger.log('parse new PES');\n var track = this._avcTrack,\n units = this._parseAVCNALu(pes.data),\n debug = false,\n expGolombDecoder,\n avcSample = this.avcSample,\n push,\n i;\n //free pes.data to save up some memory\n pes.data = null;\n\n units.forEach(unit => {\n switch(unit.type) {\n //NDR\n case 1:\n push = true;\n if(debug && avcSample) {\n avcSample.debug += 'NDR ';\n }\n avcSample.frame = true;\n // retrieve slice type by parsing beginning of NAL unit (follow H264 spec, slice_header definition) to detect keyframe embedded in NDR\n let data = unit.data;\n if (data.length > 4) {\n let sliceType = new ExpGolomb(data).readSliceType();\n // 2 : I slice, 4 : SI slice, 7 : I slice, 9: SI slice\n // SI slice : A slice that is coded using intra prediction only and using quantisation of the prediction samples.\n // An SI slice can be coded such that its decoded samples can be constructed identically to an SP slice.\n // I slice: A slice that is not an SI slice that is decoded using intra prediction only.\n //if (sliceType === 2 || sliceType === 7) {\n if (sliceType === 2 || sliceType === 4 || sliceType === 7 || sliceType === 9) {\n avcSample.key = true;\n }\n }\n break;\n //IDR\n case 5:\n push = true;\n // handle PES not starting with AUD\n if (!avcSample) {\n avcSample = this.avcSample = this._createAVCSample(true,pes.pts,pes.dts,'');\n }\n if(debug) {\n avcSample.debug += 'IDR ';\n }\n avcSample.key = true;\n avcSample.frame = true;\n break;\n //SEI\n case 6:\n push = true;\n if(debug && avcSample) {\n avcSample.debug += 'SEI ';\n }\n expGolombDecoder = new ExpGolomb(this.discardEPB(unit.data));\n\n // skip frameType\n expGolombDecoder.readUByte();\n\n var payloadType = 0;\n var payloadSize = 0;\n var endOfCaptions = false;\n var b = 0;\n\n while (!endOfCaptions && expGolombDecoder.bytesAvailable > 1) {\n payloadType = 0;\n do {\n b = expGolombDecoder.readUByte();\n payloadType += b;\n } while (b === 0xFF);\n\n // Parse payload size.\n payloadSize = 0;\n do {\n b = expGolombDecoder.readUByte();\n payloadSize += b;\n } while (b === 0xFF);\n\n // TODO: there can be more than one payload in an SEI packet...\n // TODO: need to read type and size in a while loop to get them all\n if (payloadType === 4 && expGolombDecoder.bytesAvailable !== 0) {\n\n endOfCaptions = true;\n\n var countryCode = expGolombDecoder.readUByte();\n\n if (countryCode === 181) {\n var providerCode = expGolombDecoder.readUShort();\n\n if (providerCode === 49) {\n var userStructure = expGolombDecoder.readUInt();\n\n if (userStructure === 0x47413934) {\n var userDataType = expGolombDecoder.readUByte();\n\n // Raw CEA-608 bytes wrapped in CEA-708 packet\n if (userDataType === 3) {\n var firstByte = expGolombDecoder.readUByte();\n var secondByte = expGolombDecoder.readUByte();\n\n var totalCCs = 31 & firstByte;\n var byteArray = [firstByte, secondByte];\n\n for (i = 0; i < totalCCs; i++) {\n // 3 bytes per CC\n byteArray.push(expGolombDecoder.readUByte());\n byteArray.push(expGolombDecoder.readUByte());\n byteArray.push(expGolombDecoder.readUByte());\n }\n\n this._insertSampleInOrder(this._txtTrack.samples, { type: 3, pts: pes.pts, bytes: byteArray });\n }\n }\n }\n }\n }\n else if (payloadSize < expGolombDecoder.bytesAvailable)\n {\n for (i = 0; i<payloadSize; i++)\n {\n expGolombDecoder.readUByte();\n }\n }\n }\n break;\n //SPS\n case 7:\n push = true;\n if(debug && avcSample) {\n avcSample.debug += 'SPS ';\n }\n if(!track.sps) {\n expGolombDecoder = new ExpGolomb(unit.data);\n var config = expGolombDecoder.readSPS();\n track.width = config.width;\n track.height = config.height;\n track.sps = [unit.data];\n track.duration = this._duration;\n var codecarray = unit.data.subarray(1, 4);\n var codecstring = 'avc1.';\n for (i = 0; i < 3; i++) {\n var h = codecarray[i].toString(16);\n if (h.length < 2) {\n h = '0' + h;\n }\n codecstring += h;\n }\n track.codec = codecstring;\n }\n break;\n //PPS\n case 8:\n push = true;\n if(debug && avcSample) {\n avcSample.debug += 'PPS ';\n }\n if (!track.pps) {\n track.pps = [unit.data];\n }\n break;\n // AUD\n case 9:\n push = false;\n if (avcSample) {\n this.pushAccesUnit(avcSample,track);\n }\n avcSample = this.avcSample = this._createAVCSample(false,pes.pts,pes.dts,debug ? 'AUD ': '');\n break;\n // Filler Data\n case 12:\n push = false;\n break;\n default:\n push = false;\n if (avcSample) {\n avcSample.debug += 'unknown NAL ' + unit.type + ' ';\n }\n break;\n }\n if(avcSample && push) {\n let units = avcSample.units;\n units.units.push(unit);\n }\n });\n // if last PES packet, push samples\n if (last && avcSample) {\n this.pushAccesUnit(avcSample,track);\n this.avcSample = null;\n }\n }\n\n _createAVCSample(key,pts,dts,debug) {\n return { key : key, pts : pts, dts : dts, units : { units : [], length : 0}, debug : debug};\n }\n\n _insertSampleInOrder(arr, data) {\n var len = arr.length;\n if (len > 0) {\n if (data.pts >= arr[len-1].pts)\n {\n arr.push(data);\n }\n else {\n for (var pos = len - 1; pos >= 0; pos--) {\n if (data.pts < arr[pos].pts) {\n arr.splice(pos, 0, data);\n break;\n }\n }\n }\n }\n else {\n arr.push(data);\n }\n }\n\n _getLastNalUnit() {\n let avcSample = this.avcSample, lastUnit;\n // try to fallback to previous sample if current one is empty\n if (!avcSample || avcSample.units.units.length === 0) {\n let track = this._avcTrack, samples = track.samples;\n avcSample = samples[samples.length-1];\n }\n if (avcSample) {\n let units = avcSample.units.units;\n lastUnit = units[units.length - 1];\n }\n return lastUnit;\n }\n\n _parseAVCNALu(array) {\n var i = 0, len = array.byteLength, value, overflow, track = this._avcTrack, state = track.naluState || 0, lastState = state;\n var units = [], unit, unitType, lastUnitStart = -1, lastUnitType;\n //logger.log('PES:' + Hex.hexDump(array));\n\n if (state === -1) {\n // special use case where we found 3 or 4-byte start codes exactly at the end of previous PES packet\n lastUnitStart = 0;\n // NALu type is value read from offset 0\n lastUnitType = array[0] & 0x1f;\n state = 0;\n i = 1;\n }\n\n while (i < len) {\n value = array[i++];\n // optimization. state 0 and 1 are the predominant case. let's handle them outside of the switch/case\n if (!state) {\n state = value ? 0 : 1;\n continue;\n }\n if (state === 1) {\n state = value ? 0 : 2;\n continue;\n }\n // here we have state either equal to 2 or 3\n if(!value) {\n state = 3;\n } else if (value === 1) {\n if (lastUnitStart >=0) {\n unit = {data: array.subarray(lastUnitStart, i - state - 1), type: lastUnitType};\n //logger.log('pushing NALU, type/size:' + unit.type + '/' + unit.data.byteLength);\n units.push(unit);\n } else {\n // lastUnitStart is undefined => this is the first start code found in this PES packet\n // first check if start code delimiter is overlapping between 2 PES packets,\n // ie it started in last packet (lastState not zero)\n // and ended at the beginning of this PES packet (i <= 4 - lastState)\n let lastUnit = this._getLastNalUnit();\n if (lastUnit) {\n if(lastState && (i <= 4 - lastState)) {\n // start delimiter overlapping between PES packets\n // strip start delimiter bytes from the end of last NAL unit\n // check if lastUnit had a state different from zero\n if (lastUnit.state) {\n // strip last bytes\n lastUnit.data = lastUnit.data.subarray(0,lastUnit.data.byteLength - lastState);\n }\n }\n // If NAL units are not starting right at the beginning of the PES packet, push preceding data into previous NAL unit.\n overflow = i - state - 1;\n if (overflow > 0) {\n //logger.log('first NALU found with overflow:' + overflow);\n let tmp = new Uint8Array(lastUnit.data.byteLength + overflow);\n tmp.set(lastUnit.data, 0);\n tmp.set(array.subarray(0, overflow), lastUnit.data.byteLength);\n lastUnit.data = tmp;\n }\n }\n }\n // check if we can read unit type\n if (i < len) {\n unitType = array[i] & 0x1f;\n //logger.log('find NALU @ offset:' + i + ',type:' + unitType);\n lastUnitStart = i;\n lastUnitType = unitType;\n state = 0;\n } else {\n // not enough byte to read unit type. let's read it on next PES parsing\n state = -1;\n }\n } else {\n state = 0;\n }\n }\n if (lastUnitStart >=0 && state >=0) {\n unit = {data: array.subarray(lastUnitStart, len), type: lastUnitType, state : state};\n units.push(unit);\n //logger.log('pushing NALU, type/size/state:' + unit.type + '/' + unit.data.byteLength + '/' + state);\n }\n // no NALu found\n if (units.length === 0) {\n // append pes.data to previous NAL unit\n let lastUnit = this._getLastNalUnit();\n if (lastUnit) {\n let tmp = new Uint8Array(lastUnit.data.byteLength + array.byteLength);\n tmp.set(lastUnit.data, 0);\n tmp.set(array, lastUnit.data.byteLength);\n lastUnit.data = tmp;\n }\n }\n track.naluState = state;\n return units;\n }\n\n /**\n * remove Emulation Prevention bytes from a RBSP\n */\n discardEPB(data) {\n var length = data.byteLength,\n EPBPositions = [],\n i = 1,\n newLength, newData;\n\n // Find all `Emulation Prevention Bytes`\n while (i < length - 2) {\n if (data[i] === 0 &&\n data[i + 1] === 0 &&\n data[i + 2] === 0x03) {\n EPBPositions.push(i + 2);\n i += 2;\n } else {\n i++;\n }\n }\n\n // If no Emulation Prevention Bytes were found just return the original\n // array\n if (EPBPositions.length === 0) {\n return data;\n }\n\n // Create a new array to hold the NAL unit data\n newLength = length - EPBPositions.length;\n newData = new Uint8Array(newLength);\n var sourceIndex = 0;\n\n for (i = 0; i < newLength; sourceIndex++, i++) {\n if (sourceIndex === EPBPositions[0]) {\n // Skip this byte\n sourceIndex++;\n // Remove this position index\n EPBPositions.shift();\n }\n newData[i] = data[sourceIndex];\n }\n return newData;\n }\n\n _parseAACPES(pes) {\n var track = this._audioTrack,\n data = pes.data,\n pts = pes.pts,\n startOffset = 0,\n aacOverFlow = this.aacOverFlow,\n aacLastPTS = this.aacLastPTS,\n config, frameLength, frameDuration, frameIndex, offset, headerLength, stamp, len, aacSample;\n if (aacOverFlow) {\n var tmp = new Uint8Array(aacOverFlow.byteLength + data.byteLength);\n tmp.set(aacOverFlow, 0);\n tmp.set(data, aacOverFlow.byteLength);\n //logger.log(`AAC: append overflowing ${aacOverFlow.byteLength} bytes to beginning of new PES`);\n data = tmp;\n }\n // look for ADTS header (0xFFFx)\n for (offset = startOffset, len = data.length; offset < len - 1; offset++) {\n if ((data[offset] === 0xff) && (data[offset+1] & 0xf0) === 0xf0) {\n break;\n }\n }\n // if ADTS header does not start straight from the beginning of the PES payload, raise an error\n if (offset) {\n var reason, fatal;\n if (offset < len - 1) {\n reason = `AAC PES did not start with ADTS header,offset:${offset}`;\n fatal = false;\n } else {\n reason = 'no ADTS header found in AAC PES';\n fatal = true;\n }\n logger.warn(`parsing error:${reason}`);\n this.observer.trigger(Event.ERROR, {type: ErrorTypes.MEDIA_ERROR, id : this.id, details: ErrorDetails.FRAG_PARSING_ERROR, fatal: fatal, reason: reason});\n if (fatal) {\n return;\n }\n }\n if (!track.audiosamplerate) {\n const audioCodec = this.audioCodec;\n config = ADTS.getAudioConfig(this.observer,data, offset, audioCodec);\n track.config = config.config;\n track.audiosamplerate = config.samplerate;\n track.channelCount = config.channelCount;\n track.codec = config.codec;\n track.manifestCodec = config.manifestCodec;\n track.duration = this._duration;\n logger.log(`parsed codec:${track.codec},rate:${config.samplerate},nb channel:${config.channelCount}`);\n }\n frameIndex = 0;\n frameDuration = 1024 * 90000 / track.audiosamplerate;\n\n // if last AAC frame is overflowing, we should ensure timestamps are contiguous:\n // first sample PTS should be equal to last sample PTS + frameDuration\n if(aacOverFlow && aacLastPTS) {\n var newPTS = aacLastPTS+frameDuration;\n if(Math.abs(newPTS-pts) > 1) {\n logger.log(`AAC: align PTS for overlapping frames by ${Math.round((newPTS-pts)/90)}`);\n pts=newPTS;\n }\n }\n\n while ((offset + 5) < len) {\n // The protection skip bit tells us if we have 2 bytes of CRC data at the end of the ADTS header\n headerLength = (!!(data[offset + 1] & 0x01) ? 7 : 9);\n // retrieve frame size\n frameLength = ((data[offset + 3] & 0x03) << 11) |\n (data[offset + 4] << 3) |\n ((data[offset + 5] & 0xE0) >>> 5);\n frameLength -= headerLength;\n //stamp = pes.pts;\n\n if ((frameLength > 0) && ((offset + headerLength + frameLength) <= len)) {\n stamp = pts + frameIndex * frameDuration;\n //logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}/${(stamp/90).toFixed(0)}`);\n aacSample = {unit: data.subarray(offset + headerLength, offset + headerLength + frameLength), pts: stamp, dts: stamp};\n track.samples.push(aacSample);\n track.len += frameLength;\n offset += frameLength + headerLength;\n frameIndex++;\n // look for ADTS header (0xFFFx)\n for ( ; offset < (len - 1); offset++) {\n if ((data[offset] === 0xff) && ((data[offset + 1] & 0xf0) === 0xf0)) {\n break;\n }\n }\n } else {\n break;\n }\n }\n if (offset < len) {\n aacOverFlow = data.subarray(offset, len);\n //logger.log(`AAC: overflow detected:${len-offset}`);\n } else {\n aacOverFlow = null;\n }\n this.aacOverFlow = aacOverFlow;\n this.aacLastPTS = stamp;\n }\n\n _parseMPEGPES(pes) {\n var data = pes.data;\n var pts = pes.pts;\n var length = data.length;\n var frameIndex = 0;\n var offset = 0;\n var parsed;\n\n while (offset < length &&\n (parsed = this._parseMpeg(data, offset, length, frameIndex++, pts)) > 0) {\n offset += parsed;\n }\n }\n\n _onMpegFrame(data, bitRate, sampleRate, channelCount, frameIndex, pts) {\n var frameDuration = (1152 / sampleRate) * 1000;\n var stamp = pts + frameIndex * frameDuration;\n var track = this._audioTrack;\n\n track.config = [];\n track.channelCount = channelCount;\n track.audiosamplerate = sampleRate;\n track.duration = this._duration;\n track.samples.push({unit: data, pts: stamp, dts: stamp});\n track.len += data.length;\n }\n\n _onMpegNoise(data) {\n logger.warn('mpeg audio has noise: ' + data.length + ' bytes');\n }\n\n _parseMpeg(data, start, end, frameIndex, pts) {\n var BitratesMap = [\n 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448,\n 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384,\n 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320,\n 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256,\n 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160];\n var SamplingRateMap = [44100, 48000, 32000, 22050, 24000, 16000, 11025, 12000, 8000];\n\n if (start + 2 > end) {\n return -1; // we need at least 2 bytes to detect sync pattern\n }\n if (data[start] === 0xFF || (data[start + 1] & 0xE0) === 0xE0) {\n // Using http://www.datavoyage.com/mpgscript/mpeghdr.htm as a reference\n if (start + 24 > end) {\n return -1;\n }\n var headerB = (data[start + 1] >> 3) & 3;\n var headerC = (data[start + 1] >> 1) & 3;\n var headerE = (data[start + 2] >> 4) & 15;\n var headerF = (data[start + 2] >> 2) & 3;\n var headerG = !!(data[start + 2] & 2);\n if (headerB !== 1 && headerE !== 0 && headerE !== 15 && headerF !== 3) {\n var columnInBitrates = headerB === 3 ? (3 - headerC) : (headerC === 3 ? 3 : 4);\n var bitRate = BitratesMap[columnInBitrates * 14 + headerE - 1] * 1000;\n var columnInSampleRates = headerB === 3 ? 0 : headerB === 2 ? 1 : 2;\n var sampleRate = SamplingRateMap[columnInSampleRates * 3 + headerF];\n var padding = headerG ? 1 : 0;\n var channelCount = data[start + 3] >> 6 === 3 ? 1 : 2; // If bits of channel mode are `11` then it is a single channel (Mono)\n var frameLength = headerC === 3 ?\n ((headerB === 3 ? 12 : 6) * bitRate / sampleRate + padding) << 2 :\n ((headerB === 3 ? 144 : 72) * bitRate / sampleRate + padding) | 0;\n if (start + frameLength > end) {\n return -1;\n }\n if (this._onMpegFrame) {\n this._onMpegFrame(data.subarray(start, start + frameLength), bitRate, sampleRate, channelCount, frameIndex, pts);\n }\n return frameLength;\n }\n }\n // noise or ID3, trying to skip\n var offset = start + 2;\n while (offset < end) {\n if (data[offset - 1] === 0xFF && (data[offset] & 0xE0) === 0xE0) {\n // sync pattern is found\n if (this._onMpegNoise) {\n this._onMpegNoise(data.subarray(start, offset - 1));\n }\n return offset - start - 1;\n }\n offset++;\n }\n return -1;\n }\n\n _parseID3PES(pes) {\n this._id3Track.samples.push(pes);\n }\n}\n\nexport default TSDemuxer;\n",
"export const ErrorTypes = {\n // Identifier for a network error (loading error / timeout ...)\n NETWORK_ERROR: 'networkError',\n // Identifier for a media Error (video/parsing/mediasource error)\n MEDIA_ERROR: 'mediaError',\n // Identifier for a mux Error (demuxing/remuxing)\n MUX_ERROR: 'muxError',\n // Identifier for all other errors\n OTHER_ERROR: 'otherError'\n};\n\nexport const ErrorDetails = {\n // Identifier for a manifest load error - data: { url : faulty URL, response : { code: error code, text: error text }}\n MANIFEST_LOAD_ERROR: 'manifestLoadError',\n // Identifier for a manifest load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}\n MANIFEST_LOAD_TIMEOUT: 'manifestLoadTimeOut',\n // Identifier for a manifest parsing error - data: { url : faulty URL, reason : error reason}\n MANIFEST_PARSING_ERROR: 'manifestParsingError',\n // Identifier for a manifest with only incompatible codecs error - data: { url : faulty URL, reason : error reason}\n MANIFEST_INCOMPATIBLE_CODECS_ERROR: 'manifestIncompatibleCodecsError',\n // Identifier for a level load error - data: { url : faulty URL, response : { code: error code, text: error text }}\n LEVEL_LOAD_ERROR: 'levelLoadError',\n // Identifier for a level load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}\n LEVEL_LOAD_TIMEOUT: 'levelLoadTimeOut',\n // Identifier for a level switch error - data: { level : faulty level Id, event : error description}\n LEVEL_SWITCH_ERROR: 'levelSwitchError',\n // Identifier for an audio track load error - data: { url : faulty URL, response : { code: error code, text: error text }}\n AUDIO_TRACK_LOAD_ERROR: 'audioTrackLoadError',\n // Identifier for an audio track load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}\n AUDIO_TRACK_LOAD_TIMEOUT: 'audioTrackLoadTimeOut',\n // Identifier for fragment load error - data: { frag : fragment object, response : { code: error code, text: error text }}\n FRAG_LOAD_ERROR: 'fragLoadError',\n // Identifier for fragment loop loading error - data: { frag : fragment object}\n FRAG_LOOP_LOADING_ERROR: 'fragLoopLoadingError',\n // Identifier for fragment load timeout error - data: { frag : fragment object}\n FRAG_LOAD_TIMEOUT: 'fragLoadTimeOut',\n // Identifier for a fragment decryption error event - data: parsing error description\n FRAG_DECRYPT_ERROR: 'fragDecryptError',\n // Identifier for a fragment parsing error event - data: { id : demuxer Id, reason : parsing error description }\n // will be renamed DEMUX_PARSING_ERROR and switched to MUX_ERROR in the next major release\n FRAG_PARSING_ERROR: 'fragParsingError',\n // Identifier for a remux alloc error event - data: { id : demuxer Id, bytes : nb of bytes on which allocation failed , reason : error text }\n REMUX_ALLOC_ERROR : 'remuxAllocError',\n // Identifier for decrypt key load error - data: { frag : fragment object, response : { code: error code, text: error text }}\n KEY_LOAD_ERROR: 'keyLoadError',\n // Identifier for decrypt key load timeout error - data: { frag : fragment object}\n KEY_LOAD_TIMEOUT: 'keyLoadTimeOut',\n // Triggered when an exception occurs while adding a sourceBuffer to MediaSource - data : { err : exception , mimeType : mimeType }\n BUFFER_ADD_CODEC_ERROR: 'bufferAddCodecError',\n // Identifier for a buffer append error - data: append error description\n BUFFER_APPEND_ERROR: 'bufferAppendError',\n // Identifier for a buffer appending error event - data: appending error description\n BUFFER_APPENDING_ERROR: 'bufferAppendingError',\n // Identifier for a buffer stalled error event\n BUFFER_STALLED_ERROR: 'bufferStalledError',\n // Identifier for a buffer full event\n BUFFER_FULL_ERROR: 'bufferFullError',\n // Identifier for a buffer seek over hole event\n BUFFER_SEEK_OVER_HOLE: 'bufferSeekOverHole',\n // Identifier for a buffer nudge on stall (playback is stuck although currentTime is in a buffered area)\n BUFFER_NUDGE_ON_STALL : 'bufferNudgeOnStall',\n // Identifier for an internal exception happening inside hls.js while handling an event\n INTERNAL_EXCEPTION: 'internalException'\n};\n",
"/*\n*\n* All objects in the event handling chain should inherit from this class\n*\n*/\n\nimport {logger} from './utils/logger';\nimport {ErrorTypes, ErrorDetails} from './errors';\nimport Event from './events';\n\nclass EventHandler {\n\n constructor(hls, ...events) {\n this.hls = hls;\n this.onEvent = this.onEvent.bind(this);\n this.handledEvents = events;\n this.useGenericHandler = true;\n\n this.registerListeners();\n }\n\n destroy() {\n this.unregisterListeners();\n }\n\n isEventHandler() {\n return typeof this.handledEvents === 'object' && this.handledEvents.length && typeof this.onEvent === 'function';\n }\n\n registerListeners() {\n if (this.isEventHandler()) {\n this.handledEvents.forEach(function(event) {\n if (event === 'hlsEventGeneric') {\n throw new Error('Forbidden event name: ' + event);\n }\n this.hls.on(event, this.onEvent);\n }.bind(this));\n }\n }\n\n unregisterListeners() {\n if (this.isEventHandler()) {\n this.handledEvents.forEach(function(event) {\n this.hls.off(event, this.onEvent);\n }.bind(this));\n }\n }\n\n /**\n * arguments: event (string), data (any)\n */\n onEvent(event, data) {\n this.onEventGeneric(event, data);\n }\n\n onEventGeneric(event, data) {\n var eventToFunction = function(event, data) {\n var funcName = 'on' + event.replace('hls', '');\n if (typeof this[funcName] !== 'function') {\n throw new Error(`Event ${event} has no generic handler in this ${this.constructor.name} class (tried ${funcName})`);\n }\n return this[funcName].bind(this, data);\n };\n try {\n eventToFunction.call(this, event, data).call();\n } catch (err) {\n logger.error(`internal error happened while processing ${event}:${err.message}`);\n this.hls.trigger(Event.ERROR, {type: ErrorTypes.OTHER_ERROR, details: ErrorDetails.INTERNAL_EXCEPTION, fatal: false, event : event, err : err});\n }\n }\n}\n\nexport default EventHandler;\n",
"module.exports = {\n // fired before MediaSource is attaching to media element - data: { media }\n MEDIA_ATTACHING: 'hlsMediaAttaching',\n // fired when MediaSource has been succesfully attached to media element - data: { }\n MEDIA_ATTACHED: 'hlsMediaAttached',\n // fired before detaching MediaSource from media element - data: { }\n MEDIA_DETACHING: 'hlsMediaDetaching',\n // fired when MediaSource has been detached from media element - data: { }\n MEDIA_DETACHED: 'hlsMediaDetached',\n // fired when we buffer is going to be resetted\n BUFFER_RESET: 'hlsBufferReset',\n // fired when we know about the codecs that we need buffers for to push into - data: {tracks : { container, codec, levelCodec, initSegment, metadata }}\n BUFFER_CODECS: 'hlsBufferCodecs',\n // fired when sourcebuffers have been created data: { tracks : tracks}\n BUFFER_CREATED: 'hlsBufferCreated',\n // fired when we append a segment to the buffer - data: { segment: segment object }\n BUFFER_APPENDING: 'hlsBufferAppending',\n // fired when we are done with appending a media segment to the buffer data : { parent : segment parent that triggered BUFFER_APPENDING , pending : nb of segments waiting for appending for this segment parent}\n BUFFER_APPENDED: 'hlsBufferAppended',\n // fired when the stream is finished and we want to notify the media buffer that there will be no more data\n BUFFER_EOS: 'hlsBufferEos',\n // fired when the media buffer should be flushed - data {startOffset, endOffset}\n BUFFER_FLUSHING: 'hlsBufferFlushing',\n // fired when the media has been flushed\n BUFFER_FLUSHED: 'hlsBufferFlushed',\n // fired to signal that a manifest loading starts - data: { url : manifestURL}\n MANIFEST_LOADING: 'hlsManifestLoading',\n // fired after manifest has been loaded - data: { levels : [available quality levels] , audioTracks : [ available audio tracks], url : manifestURL, stats : { trequest, tfirst, tload, mtime}}\n MANIFEST_LOADED: 'hlsManifestLoaded',\n // fired after manifest has been parsed - data: { levels : [available quality levels] , firstLevel : index of first quality level appearing in Manifest}\n MANIFEST_PARSED: 'hlsManifestParsed',\n // fired when a level playlist loading starts - data: { url : level URL level : id of level being loaded}\n LEVEL_LOADING: 'hlsLevelLoading',\n // fired when a level playlist loading finishes - data: { details : levelDetails object, level : id of loaded level, stats : { trequest, tfirst, tload, mtime} }\n LEVEL_LOADED: 'hlsLevelLoaded',\n // fired when a level's details have been updated based on previous details, after it has been loaded. - data: { details : levelDetails object, level : id of updated level }\n LEVEL_UPDATED: 'hlsLevelUpdated',\n // fired when a level's PTS information has been updated after parsing a fragment - data: { details : levelDetails object, level : id of updated level, drift: PTS drift observed when parsing last fragment }\n LEVEL_PTS_UPDATED: 'hlsLevelPtsUpdated',\n // fired when a level switch is requested - data: { level : id of new level }\n LEVEL_SWITCH: 'hlsLevelSwitch',\n // fired to notify that audio track lists has been updated data: { audioTracks : audioTracks}\n AUDIO_TRACKS_UPDATED: 'hlsAudioTracksUpdated',\n // fired when an audio track switch occurs - data: { id : audio track id} // deprecated\n AUDIO_TRACK_SWITCH: 'hlsAudioTrackSwitch',\n // fired when an audio track switching is requested - data: { id : audio track id}\n AUDIO_TRACK_SWITCHING: 'hlsAudioTrackSwitching',\n // fired when an audio track switch actually occurs - data: { id : audio track id}\n AUDIO_TRACK_SWITCHED: 'hlsAudioTrackSwitched',\n // fired when an audio track loading starts - data: { url : audio track URL id : audio track id}\n AUDIO_TRACK_LOADING: 'hlsAudioTrackLoading',\n // fired when an audio track loading finishes - data: { details : levelDetails object, id : audio track id, stats : { trequest, tfirst, tload, mtime} }\n AUDIO_TRACK_LOADED: 'hlsAudioTrackLoaded',\n // fired when the first timestamp is found. - data: { id : demuxer id, initPTS: initPTS }\n INIT_PTS_FOUND: 'hlsInitPtsFound',\n // fired when a fragment loading starts - data: { frag : fragment object}\n FRAG_LOADING: 'hlsFragLoading',\n // fired when a fragment loading is progressing - data: { frag : fragment object, { trequest, tfirst, loaded}}\n FRAG_LOAD_PROGRESS: 'hlsFragLoadProgress',\n // Identifier for fragment load aborting for emergency switch down - data: {frag : fragment object}\n FRAG_LOAD_EMERGENCY_ABORTED: 'hlsFragLoadEmergencyAborted',\n // fired when a fragment loading is completed - data: { frag : fragment object, payload : fragment payload, stats : { trequest, tfirst, tload, length}}\n FRAG_LOADED: 'hlsFragLoaded',\n // fired when a fragment has finished decrypting - data: { level : levelId, sn : sequence number }\n FRAG_DECRYPTED: 'hlsFragDecrypted',\n // fired when Init Segment has been extracted from fragment - data: { id : demuxer id, level : levelId, sn : sequence number, moov : moov MP4 box, codecs : codecs found while parsing fragment}\n FRAG_PARSING_INIT_SEGMENT: 'hlsFragParsingInitSegment',\n // fired when parsing sei text is completed - data: { id : demuxer id, , level : levelId, sn : sequence number, samples : [ sei samples pes ] }\n FRAG_PARSING_USERDATA: 'hlsFragParsingUserdata',\n // fired when parsing id3 is completed - data: { id : demuxer id, , level : levelId, sn : sequence number, samples : [ id3 samples pes ] }\n FRAG_PARSING_METADATA: 'hlsFragParsingMetadata',\n // fired when data have been extracted from fragment - data: { id : demuxer id, level : levelId, sn : sequence number, data1 : moof MP4 box or TS fragments, data2 : mdat MP4 box or null}\n FRAG_PARSING_DATA: 'hlsFragParsingData',\n // fired when fragment parsing is completed - data: { id : demuxer id; level : levelId, sn : sequence number, }\n FRAG_PARSED: 'hlsFragParsed',\n // fired when fragment remuxed MP4 boxes have all been appended into SourceBuffer - data: { id : demuxer id,frag : fragment object, stats : { trequest, tfirst, tload, tparsed, tbuffered, length} }\n FRAG_BUFFERED: 'hlsFragBuffered',\n // fired when fragment matching with current media position is changing - data : { id : demuxer id, frag : fragment object }\n FRAG_CHANGED: 'hlsFragChanged',\n // Identifier for a FPS drop event - data: {curentDropped, currentDecoded, totalDroppedFrames}\n FPS_DROP: 'hlsFpsDrop',\n //triggered when FPS drop triggers auto level capping - data: {level, droppedlevel}\n FPS_DROP_LEVEL_CAPPING: 'hlsFpsDropLevelCapping',\n // Identifier for an error event - data: { type : error type, details : error details, fatal : if true, hls.js cannot/will not try to recover, if false, hls.js will try to recover,other error specific data}\n ERROR: 'hlsError',\n // fired when hls.js instance starts destroying. Different from MEDIA_DETACHED as one could want to detach and reattach a media to the instance of hls.js to handle mid-rolls for example\n DESTROYING: 'hlsDestroying',\n // fired when a decrypt key loading starts - data: { frag : fragment object}\n KEY_LOADING: 'hlsKeyLoading',\n // fired when a decrypt key loading is completed - data: { frag : fragment object, payload : key payload, stats : { trequest, tfirst, tload, length}}\n KEY_LOADED: 'hlsKeyLoaded',\n // fired upon stream controller state transitions - data: {previousState, nextState}\n STREAM_STATE_TRANSITION: 'hlsStreamStateTransition'\n};\n",
"/**\n * AAC helper\n */\n\nclass AAC {\n static getSilentFrame(codec,channelCount) {\n switch(codec) {\n case 'mp4a.40.2':\n if (channelCount === 1) {\n return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x23, 0x80]);\n } else if (channelCount === 2) {\n return new Uint8Array([0x21, 0x00, 0x49, 0x90, 0x02, 0x19, 0x00, 0x23, 0x80]);\n } else if (channelCount === 3) {\n return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x8e]);\n } else if (channelCount === 4) {\n return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x80, 0x2c, 0x80, 0x08, 0x02, 0x38]);\n } else if (channelCount === 5) {\n return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x38]);\n } else if (channelCount === 6) {\n return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x00, 0xb2, 0x00, 0x20, 0x08, 0xe0]);\n }\n break;\n // handle HE-AAC below (mp4a.40.5 / mp4a.40.29)\n default:\n if (channelCount === 1) {\n // ffmpeg -y -f lavfi -i \"aevalsrc=0:d=0.05\" -c:a libfdk_aac -profile:a aac_he -b:a 4k output.aac && hexdump -v -e '16/1 \"0x%x,\" \"\\n\"' -v output.aac\n return new Uint8Array([0x1,0x40,0x22,0x80,0xa3,0x4e,0xe6,0x80,0xba,0x8,0x0,0x0,0x0,0x1c,0x6,0xf1,0xc1,0xa,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5e]);\n } else if (channelCount === 2) {\n // ffmpeg -y -f lavfi -i \"aevalsrc=0|0:d=0.05\" -c:a libfdk_aac -profile:a aac_he_v2 -b:a 4k output.aac && hexdump -v -e '16/1 \"0x%x,\" \"\\n\"' -v output.aac\n return new Uint8Array([0x1,0x40,0x22,0x80,0xa3,0x5e,0xe6,0x80,0xba,0x8,0x0,0x0,0x0,0x0,0x95,0x0,0x6,0xf1,0xa1,0xa,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5e]);\n } else if (channelCount === 3) {\n // ffmpeg -y -f lavfi -i \"aevalsrc=0|0|0:d=0.05\" -c:a libfdk_aac -profile:a aac_he_v2 -b:a 4k output.aac && hexdump -v -e '16/1 \"0x%x,\" \"\\n\"' -v output.aac\n return new Uint8Array([0x1,0x40,0x22,0x80,0xa3,0x5e,0xe6,0x80,0xba,0x8,0x0,0x0,0x0,0x0,0x95,0x0,0x6,0xf1,0xa1,0xa,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5e]);\n }\n break;\n }\n return null;\n }\n}\n\nexport default AAC;\n",
"/**\n * Buffer Helper class, providing methods dealing buffer length retrieval\n*/\n\n\nclass BufferHelper {\n\n\n static isBuffered(media,position) {\n if (media) {\n let buffered = media.buffered;\n for (let i = 0; i < buffered.length; i++) {\n if (position >= buffered.start(i) && position <= buffered.end(i)) {\n return true;\n }\n }\n }\n return false;\n }\n\n static bufferInfo(media, pos,maxHoleDuration) {\n if (media) {\n var vbuffered = media.buffered, buffered = [],i;\n for (i = 0; i < vbuffered.length; i++) {\n buffered.push({start: vbuffered.start(i), end: vbuffered.end(i)});\n }\n return this.bufferedInfo(buffered,pos,maxHoleDuration);\n } else {\n return {len: 0, start: 0, end: 0, nextStart : undefined} ;\n }\n }\n\n static bufferedInfo(buffered,pos,maxHoleDuration) {\n var buffered2 = [],\n // bufferStart and bufferEnd are buffer boundaries around current video position\n bufferLen,bufferStart, bufferEnd,bufferStartNext,i;\n // sort on buffer.start/smaller end (IE does not always return sorted buffered range)\n buffered.sort(function (a, b) {\n var diff = a.start - b.start;\n if (diff) {\n return diff;\n } else {\n return b.end - a.end;\n }\n });\n // there might be some small holes between buffer time range\n // consider that holes smaller than maxHoleDuration are irrelevant and build another\n // buffer time range representations that discards those holes\n for (i = 0; i < buffered.length; i++) {\n var buf2len = buffered2.length;\n if(buf2len) {\n var buf2end = buffered2[buf2len - 1].end;\n // if small hole (value between 0 or maxHoleDuration ) or overlapping (negative)\n if((buffered[i].start - buf2end) < maxHoleDuration) {\n // merge overlapping time ranges\n // update lastRange.end only if smaller than item.end\n // e.g. [ 1, 15] with [ 2,8] => [ 1,15] (no need to modify lastRange.end)\n // whereas [ 1, 8] with [ 2,15] => [ 1,15] ( lastRange should switch from [1,8] to [1,15])\n if(buffered[i].end > buf2end) {\n buffered2[buf2len - 1].end = buffered[i].end;\n }\n } else {\n // big hole\n buffered2.push(buffered[i]);\n }\n } else {\n // first value\n buffered2.push(buffered[i]);\n }\n }\n for (i = 0, bufferLen = 0, bufferStart = bufferEnd = pos; i < buffered2.length; i++) {\n var start = buffered2[i].start,\n end = buffered2[i].end;\n //logger.log('buf start/end:' + buffered.start(i) + '/' + buffered.end(i));\n if ((pos + maxHoleDuration) >= start && pos < end) {\n // play position is inside this buffer TimeRange, retrieve end of buffer position and buffer length\n bufferStart = start;\n bufferEnd = end;\n bufferLen = bufferEnd - pos;\n } else if ((pos + maxHoleDuration) < start) {\n bufferStartNext = start;\n break;\n }\n }\n return {len: bufferLen, start: bufferStart, end: bufferEnd, nextStart : bufferStartNext};\n }\n\n}\n\nexport default BufferHelper;\n",
"/**\n * Level Helper class, providing methods dealing with playlist sliding and drift\n*/\n\nimport {logger} from '../utils/logger';\n\nclass LevelHelper {\n\n static mergeDetails(oldDetails,newDetails) {\n var start = Math.max(oldDetails.startSN,newDetails.startSN)-newDetails.startSN,\n end = Math.min(oldDetails.endSN,newDetails.endSN)-newDetails.startSN,\n delta = newDetails.startSN - oldDetails.startSN,\n oldfragments = oldDetails.fragments,\n newfragments = newDetails.fragments,\n ccOffset =0,\n PTSFrag;\n\n // check if old/new playlists have fragments in common\n if ( end < start) {\n newDetails.PTSKnown = false;\n return;\n }\n // loop through overlapping SN and update startPTS , cc, and duration if any found\n for(var i = start ; i <= end ; i++) {\n var oldFrag = oldfragments[delta+i],\n newFrag = newfragments[i];\n if (newFrag && oldFrag) {\n ccOffset = oldFrag.cc - newFrag.cc;\n if (!isNaN(oldFrag.startPTS)) {\n newFrag.start = newFrag.startPTS = oldFrag.startPTS;\n newFrag.endPTS = oldFrag.endPTS;\n newFrag.duration = oldFrag.duration;\n PTSFrag = newFrag;\n }\n }\n }\n\n if(ccOffset) {\n logger.log(`discontinuity sliding from playlist, take drift into account`);\n for(i = 0 ; i < newfragments.length ; i++) {\n newfragments[i].cc += ccOffset;\n }\n }\n\n // if at least one fragment contains PTS info, recompute PTS information for all fragments\n if(PTSFrag) {\n LevelHelper.updateFragPTSDTS(newDetails,PTSFrag.sn,PTSFrag.startPTS,PTSFrag.endPTS,PTSFrag.startDTS,PTSFrag.endDTS);\n } else {\n // ensure that delta is within oldfragments range\n // also adjust sliding in case delta is 0 (we could have old=[50-60] and new=old=[50-61])\n // in that case we also need to adjust start offset of all fragments\n if (delta >= 0 && delta < oldfragments.length) {\n // adjust start by sliding offset\n var sliding = oldfragments[delta].start;\n for(i = 0 ; i < newfragments.length ; i++) {\n newfragments[i].start += sliding;\n }\n }\n }\n // if we are here, it means we have fragments overlapping between\n // old and new level. reliable PTS info is thus relying on old level\n newDetails.PTSKnown = oldDetails.PTSKnown;\n return;\n }\n\n static updateFragPTSDTS(details,sn,startPTS,endPTS,startDTS,endDTS) {\n var fragIdx, fragments, frag, i;\n // exit if sn out of range\n if (!details || sn < details.startSN || sn > details.endSN) {\n return 0;\n }\n fragIdx = sn - details.startSN;\n fragments = details.fragments;\n frag = fragments[fragIdx];\n if(!isNaN(frag.startPTS)) {\n // delta PTS between audio and video\n let deltaPTS = Math.abs(frag.startPTS-startPTS);\n if (isNaN(frag.deltaPTS)) {\n frag.deltaPTS = deltaPTS;\n } else {\n frag.deltaPTS = Math.max(deltaPTS,frag.deltaPTS);\n }\n startPTS = Math.min(startPTS,frag.startPTS);\n endPTS = Math.max(endPTS, frag.endPTS);\n startDTS = Math.min(startDTS,frag.startDTS);\n endDTS = Math.max(endDTS, frag.endDTS);\n }\n\n var drift = startPTS - frag.start;\n\n frag.start = frag.startPTS = startPTS;\n frag.endPTS = endPTS;\n frag.startDTS = startDTS;\n frag.endDTS = endDTS;\n frag.duration = endPTS - startPTS;\n // adjust fragment PTS/duration from seqnum-1 to frag 0\n for(i = fragIdx ; i > 0 ; i--) {\n LevelHelper.updatePTS(fragments,i,i-1);\n }\n\n // adjust fragment PTS/duration from seqnum to last frag\n for(i = fragIdx ; i < fragments.length - 1 ; i++) {\n LevelHelper.updatePTS(fragments,i,i+1);\n }\n details.PTSKnown = true;\n //logger.log(` frag start/end:${startPTS.toFixed(3)}/${endPTS.toFixed(3)}`);\n\n return drift;\n }\n\n static updatePTS(fragments,fromIdx, toIdx) {\n var fragFrom = fragments[fromIdx],fragTo = fragments[toIdx], fragToPTS = fragTo.startPTS;\n // if we know startPTS[toIdx]\n if(!isNaN(fragToPTS)) {\n // update fragment duration.\n // it helps to fix drifts between playlist reported duration and fragment real duration\n if (toIdx > fromIdx) {\n fragFrom.duration = fragToPTS-fragFrom.start;\n if(fragFrom.duration < 0) {\n logger.warn(`negative duration computed for frag ${fragFrom.sn},level ${fragFrom.level}, there should be some duration drift between playlist and fragment!`);\n }\n } else {\n fragTo.duration = fragFrom.start - fragToPTS;\n if(fragTo.duration < 0) {\n logger.warn(`negative duration computed for frag ${fragTo.sn},level ${fragTo.level}, there should be some duration drift between playlist and fragment!`);\n }\n }\n } else {\n // we dont know startPTS[toIdx]\n if (toIdx > fromIdx) {\n fragTo.start = fragFrom.start + fragFrom.duration;\n } else {\n fragTo.start = fragFrom.start - fragTo.duration;\n }\n }\n }\n}\n\nexport default LevelHelper;\n",
"/**\n * HLS interface\n */\n'use strict';\n\nimport Event from './events';\nimport {ErrorTypes, ErrorDetails} from './errors';\nimport PlaylistLoader from './loader/playlist-loader';\nimport FragmentLoader from './loader/fragment-loader';\nimport AbrController from './controller/abr-controller';\nimport BufferController from './controller/buffer-controller';\nimport CapLevelController from './controller/cap-level-controller';\nimport AudioStreamController from './controller/audio-stream-controller';\nimport StreamController from './controller/stream-controller';\nimport LevelController from './controller/level-controller';\nimport TimelineController from './controller/timeline-controller';\nimport FPSController from './controller/fps-controller';\nimport AudioTrackController from './controller/audio-track-controller';\nimport {logger, enableLogs} from './utils/logger';\n//import FetchLoader from './utils/fetch-loader';\nimport XhrLoader from './utils/xhr-loader';\nimport EventEmitter from 'events';\nimport KeyLoader from './loader/key-loader';\nimport Cues from './utils/cues';\n\nclass Hls {\n\n static get version() {\n // replaced with browserify-versionify transform\n return '0.6.17';\n }\n\n static isSupported() {\n window.MediaSource = window.MediaSource || window.WebKitMediaSource;\n return (window.MediaSource &&\n typeof window.MediaSource.isTypeSupported === 'function' &&\n window.MediaSource.isTypeSupported('video/mp4; codecs=\"avc1.42E01E,mp4a.40.2\"'));\n }\n\n static get Events() {\n return Event;\n }\n\n static get ErrorTypes() {\n return ErrorTypes;\n }\n\n static get ErrorDetails() {\n return ErrorDetails;\n }\n\n static get DefaultConfig() {\n if(!Hls.defaultConfig) {\n Hls.defaultConfig = {\n autoStartLoad: true,\n startPosition: -1,\n defaultAudioCodec: undefined,\n debug: false,\n capLevelOnFPSDrop: false,\n capLevelToPlayerSize: false,\n initialLiveManifestSize: 1,\n maxBufferLength: 30,\n maxBufferSize: 60 * 1000 * 1000,\n maxBufferHole: 0.5,\n maxSeekHole: 2,\n nudgeWatchdogPeriod: 1,\n nudgeOffset: 0.1,\n nudgeMaxRetry : 30,\n maxFragLookUpTolerance: 0.2,\n liveSyncDurationCount:3,\n liveMaxLatencyDurationCount: Infinity,\n liveSyncDuration: undefined,\n liveMaxLatencyDuration: undefined,\n maxMaxBufferLength: 600,\n enableWorker: true,\n enableSoftwareAES: true,\n manifestLoadingTimeOut: 10000,\n manifestLoadingMaxRetry: 1,\n manifestLoadingRetryDelay: 1000,\n manifestLoadingMaxRetryTimeout: 64000,\n startLevel: undefined,\n levelLoadingTimeOut: 10000,\n levelLoadingMaxRetry: 4,\n levelLoadingRetryDelay: 1000,\n levelLoadingMaxRetryTimeout: 64000,\n fragLoadingTimeOut: 20000,\n fragLoadingMaxRetry: 6,\n fragLoadingRetryDelay: 1000,\n fragLoadingMaxRetryTimeout: 64000,\n fragLoadingLoopThreshold: 3,\n startFragPrefetch: false,\n fpsDroppedMonitoringPeriod: 5000,\n fpsDroppedMonitoringThreshold: 0.2,\n appendErrorMaxRetry: 3,\n loader: XhrLoader,\n //loader: FetchLoader,\n fLoader: undefined,\n pLoader: undefined,\n xhrSetup: undefined,\n fetchSetup: undefined,\n abrController: AbrController,\n bufferController: BufferController,\n capLevelController: CapLevelController,\n fpsController: FPSController,\n streamController: StreamController,\n audioStreamController: AudioStreamController,\n timelineController: TimelineController,\n cueHandler: Cues,\n enableCEA708Captions: true,\n enableMP2TPassThrough: false,\n stretchShortVideoTrack: false,\n forceKeyFrameOnDiscontinuity: true,\n abrEwmaFastLive: 3,\n abrEwmaSlowLive: 9,\n abrEwmaFastVoD: 3,\n abrEwmaSlowVoD: 9,\n abrEwmaDefaultEstimate: 5e5, // 500 kbps\n abrBandWidthFactor : 0.95,\n abrBandWidthUpFactor : 0.7,\n maxStarvationDelay : 4,\n maxLoadingDelay : 4,\n minAutoBitrate: 0\n };\n }\n return Hls.defaultConfig;\n }\n\n static set DefaultConfig(defaultConfig) {\n Hls.defaultConfig = defaultConfig;\n }\n\n constructor(config = {}) {\n var defaultConfig = Hls.DefaultConfig;\n\n if ((config.liveSyncDurationCount || config.liveMaxLatencyDurationCount) && (config.liveSyncDuration || config.liveMaxLatencyDuration)) {\n throw new Error('Illegal hls.js config: don\\'t mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration');\n }\n\n for (var prop in defaultConfig) {\n if (prop in config) { continue; }\n config[prop] = defaultConfig[prop];\n }\n\n if (config.liveMaxLatencyDurationCount !== undefined && config.liveMaxLatencyDurationCount <= config.liveSyncDurationCount) {\n throw new Error('Illegal hls.js config: \"liveMaxLatencyDurationCount\" must be gt \"liveSyncDurationCount\"');\n }\n\n if (config.liveMaxLatencyDuration !== undefined && (config.liveMaxLatencyDuration <= config.liveSyncDuration || config.liveSyncDuration === undefined)) {\n throw new Error('Illegal hls.js config: \"liveMaxLatencyDuration\" must be gt \"liveSyncDuration\"');\n }\n\n enableLogs(config.debug);\n this.config = config;\n // observer setup\n var observer = this.observer = new EventEmitter();\n observer.trigger = function trigger (event, ...data) {\n observer.emit(event, event, ...data);\n };\n\n observer.off = function off (event, ...data) {\n observer.removeListener(event, ...data);\n };\n this.on = observer.on.bind(observer);\n this.off = observer.off.bind(observer);\n this.trigger = observer.trigger.bind(observer);\n this.playlistLoader = new PlaylistLoader(this);\n this.fragmentLoader = new FragmentLoader(this);\n this.levelController = new LevelController(this);\n this.abrController = new config.abrController(this);\n this.bufferController = new config.bufferController(this);\n this.capLevelController = new config.capLevelController(this);\n this.fpsController = new config.fpsController(this);\n this.streamController = new config.streamController(this);\n this.audioStreamController = new config.audioStreamController(this);\n this.timelineController = new config.timelineController(this);\n this.audioTrackController = new AudioTrackController(this);\n this.keyLoader = new KeyLoader(this);\n }\n\n destroy() {\n logger.log('destroy');\n this.trigger(Event.DESTROYING);\n this.detachMedia();\n this.playlistLoader.destroy();\n this.fragmentLoader.destroy();\n this.levelController.destroy();\n this.abrController.destroy();\n this.bufferController.destroy();\n this.capLevelController.destroy();\n this.fpsController.destroy();\n this.streamController.destroy();\n this.audioStreamController.destroy();\n this.timelineController.destroy();\n this.audioTrackController.destroy();\n this.keyLoader.destroy();\n this.url = null;\n this.observer.removeAllListeners();\n }\n\n attachMedia(media) {\n logger.log('attachMedia');\n this.media = media;\n this.trigger(Event.MEDIA_ATTACHING, {media: media});\n }\n\n detachMedia() {\n logger.log('detachMedia');\n this.trigger(Event.MEDIA_DETACHING);\n this.media = null;\n }\n\n loadSource(url) {\n logger.log(`loadSource:${url}`);\n this.url = url;\n // when attaching to a source URL, trigger a playlist load\n this.trigger(Event.MANIFEST_LOADING, {url: url});\n }\n\n startLoad(startPosition=-1) {\n logger.log(`startLoad(${startPosition})`);\n this.levelController.startLoad();\n this.streamController.startLoad(startPosition);\n this.audioStreamController.startLoad(startPosition);\n }\n\n stopLoad() {\n logger.log('stopLoad');\n this.levelController.stopLoad();\n this.streamController.stopLoad();\n this.audioStreamController.stopLoad();\n }\n\n swapAudioCodec() {\n logger.log('swapAudioCodec');\n this.streamController.swapAudioCodec();\n }\n\n recoverMediaError() {\n logger.log('recoverMediaError');\n var media = this.media;\n this.detachMedia();\n this.attachMedia(media);\n }\n\n /** Return all quality levels **/\n get levels() {\n return this.levelController.levels;\n }\n\n /** Return current playback quality level **/\n get currentLevel() {\n return this.streamController.currentLevel;\n }\n\n /* set quality level immediately (-1 for automatic level selection) */\n set currentLevel(newLevel) {\n logger.log(`set currentLevel:${newLevel}`);\n this.loadLevel = newLevel;\n this.streamController.immediateLevelSwitch();\n }\n\n /** Return next playback quality level (quality level of next fragment) **/\n get nextLevel() {\n return this.streamController.nextLevel;\n }\n\n /* set quality level for next fragment (-1 for automatic level selection) */\n set nextLevel(newLevel) {\n logger.log(`set nextLevel:${newLevel}`);\n this.levelController.manualLevel = newLevel;\n this.streamController.nextLevelSwitch();\n }\n\n /** Return the quality level of current/last loaded fragment **/\n get loadLevel() {\n return this.levelController.level;\n }\n\n /* set quality level for current/next loaded fragment (-1 for automatic level selection) */\n set loadLevel(newLevel) {\n logger.log(`set loadLevel:${newLevel}`);\n this.levelController.manualLevel = newLevel;\n }\n\n /** Return the quality level of next loaded fragment **/\n get nextLoadLevel() {\n return this.levelController.nextLoadLevel;\n }\n\n /** set quality level of next loaded fragment **/\n set nextLoadLevel(level) {\n this.levelController.nextLoadLevel = level;\n }\n\n /** Return first level (index of first level referenced in manifest)\n **/\n get firstLevel() {\n return Math.max(this.levelController.firstLevel, this.abrController.minAutoLevel);\n }\n\n /** set first level (index of first level referenced in manifest)\n **/\n set firstLevel(newLevel) {\n logger.log(`set firstLevel:${newLevel}`);\n this.levelController.firstLevel = newLevel;\n }\n\n /** Return start level (level of first fragment that will be played back)\n if not overrided by user, first level appearing in manifest will be used as start level\n if -1 : automatic start level selection, playback will start from level matching download bandwidth (determined from download of first segment)\n **/\n get startLevel() {\n return this.levelController.startLevel;\n }\n\n /** set start level (level of first fragment that will be played back)\n if not overrided by user, first level appearing in manifest will be used as start level\n if -1 : automatic start level selection, playback will start from level matching download bandwidth (determined from download of first segment)\n **/\n set startLevel(newLevel) {\n logger.log(`set startLevel:${newLevel}`);\n this.levelController.startLevel = newLevel;\n }\n\n /** Return the capping/max level value that could be used by automatic level selection algorithm **/\n get autoLevelCapping() {\n return this.abrController.autoLevelCapping;\n }\n\n /** set the capping/max level value that could be used by automatic level selection algorithm **/\n set autoLevelCapping(newLevel) {\n logger.log(`set autoLevelCapping:${newLevel}`);\n this.abrController.autoLevelCapping = newLevel;\n }\n\n /* check if we are in automatic level selection mode */\n get autoLevelEnabled() {\n return (this.levelController.manualLevel === -1);\n }\n\n /* return manual level */\n get manualLevel() {\n return this.levelController.manualLevel;\n }\n\n /** get alternate audio tracks list from playlist **/\n get audioTracks() {\n return this.audioTrackController.audioTracks;\n }\n\n /** get index of the selected audio track (index in audio track lists) **/\n get audioTrack() {\n return this.audioTrackController.audioTrack;\n }\n\n /** select an audio track, based on its index in audio track lists**/\n set audioTrack(audioTrackId) {\n this.audioTrackController.audioTrack = audioTrackId;\n }\n\n get liveSyncPosition() {\n return this.streamController.liveSyncPosition;\n }\n}\n\nexport default Hls;\n",
"// This is mostly for support of the es6 module export\n// syntax with the babel compiler, it looks like it doesnt support\n// function exports like we are used to in node/commonjs\nmodule.exports = require('./hls.js').default;\n",
"/*\n * Fragment Loader\n*/\n\nimport Event from '../events';\nimport EventHandler from '../event-handler';\nimport {ErrorTypes, ErrorDetails} from '../errors';\nimport {logger} from '../utils/logger';\n\nclass FragmentLoader extends EventHandler {\n\n constructor(hls) {\n super(hls, Event.FRAG_LOADING);\n this.loaders = {};\n }\n\n destroy() {\n let loaders = this.loaders;\n for (let loaderName in loaders) {\n let loader = loaders[loaderName];\n if (loader) {\n loader.destroy();\n }\n }\n this.loaders = {};\n EventHandler.prototype.destroy.call(this);\n }\n\n onFragLoading(data) {\n let frag = data.frag,\n type = frag.type,\n loader = this.loaders[type],\n config = this.hls.config;\n\n frag.loaded = 0;\n if (loader) {\n logger.warn(`abort previous fragment loader for type:${type}`);\n loader.abort();\n }\n loader = this.loaders[type] = frag.loader = typeof(config.fLoader) !== 'undefined' ? new config.fLoader(config) : new config.loader(config);\n\n let loaderContext, loaderConfig, loaderCallbacks;\n loaderContext = { url : frag.url, frag : frag, responseType : 'arraybuffer', progressData : false};\n let start = frag.byteRangeStartOffset, end = frag.byteRangeEndOffset;\n if (!isNaN(start) && !isNaN(end)) {\n loaderContext.rangeStart = start;\n loaderContext.rangeEnd = end;\n }\n loaderConfig = { timeout : config.fragLoadingTimeOut, maxRetry : 0 , retryDelay : 0, maxRetryDelay : config.fragLoadingMaxRetryTimeout};\n loaderCallbacks = { onSuccess : this.loadsuccess.bind(this), onError :this.loaderror.bind(this), onTimeout : this.loadtimeout.bind(this), onProgress: this.loadprogress.bind(this)};\n loader.load(loaderContext,loaderConfig,loaderCallbacks);\n }\n\n loadsuccess(response, stats, context) {\n let payload = response.data, frag = context.frag;\n // detach fragment loader on load success\n frag.loader = undefined;\n this.loaders[frag.type] = undefined;\n this.hls.trigger(Event.FRAG_LOADED, {payload: payload, frag: frag, stats: stats});\n }\n\n loaderror(response, context) {\n let loader = context.loader;\n if (loader) {\n loader.abort();\n }\n this.loaders[context.type] = undefined;\n this.hls.trigger(Event.ERROR, {type: ErrorTypes.NETWORK_ERROR, details: ErrorDetails.FRAG_LOAD_ERROR, fatal: false, frag: context.frag, response: response});\n }\n\n loadtimeout(stats, context) {\n let loader = context.loader;\n if (loader) {\n loader.abort();\n }\n this.loaders[context.type] = undefined;\n this.hls.trigger(Event.ERROR, {type: ErrorTypes.NETWORK_ERROR, details: ErrorDetails.FRAG_LOAD_TIMEOUT, fatal: false, frag: context.frag});\n }\n\n // data will be used for progressive parsing\n loadprogress(stats, context, data) { // jshint ignore:line\n let frag = context.frag;\n frag.loaded = stats.loaded;\n this.hls.trigger(Event.FRAG_LOAD_PROGRESS, {frag: frag, stats: stats});\n }\n}\n\nexport default FragmentLoader;\n",
"/*\n * Decrypt key Loader\n*/\n\nimport Event from '../events';\nimport EventHandler from '../event-handler';\nimport {ErrorTypes, ErrorDetails} from '../errors';\nimport {logger} from '../utils/logger';\n\nclass KeyLoader extends EventHandler {\n\n constructor(hls) {\n super(hls, Event.KEY_LOADING);\n this.loaders = {};\n this.decryptkey = null;\n this.decrypturl = null;\n }\n\n destroy() {\n for (let loaderName in this.loaders) {\n let loader = this.loaders[loaderName];\n if (loader) {\n loader.destroy();\n }\n }\n this.loaders = {};\n EventHandler.prototype.destroy.call(this);\n }\n\n onKeyLoading(data) {\n let frag = data.frag,\n type = frag.type,\n loader = this.loaders[type],\n decryptdata = frag.decryptdata,\n uri = decryptdata.uri;\n // if uri is different from previous one or if decrypt key not retrieved yet\n if (uri !== this.decrypturl || this.decryptkey === null) {\n let config = this.hls.config;\n\n if (loader) {\n logger.warn(`abort previous key loader for type:${type}`);\n loader.abort();\n }\n frag.loader = this.loaders[type] = new config.loader(config);\n this.decrypturl = uri;\n this.decryptkey = null;\n\n let loaderContext, loaderConfig, loaderCallbacks;\n loaderContext = { url : uri, frag : frag, responseType : 'arraybuffer'};\n loaderConfig = { timeout : config.fragLoadingTimeOut, maxRetry : config.fragLoadingMaxRetry , retryDelay : config.fragLoadingRetryDelay, maxRetryDelay : config.fragLoadingMaxRetryTimeout};\n loaderCallbacks = { onSuccess : this.loadsuccess.bind(this), onError :this.loaderror.bind(this), onTimeout : this.loadtimeout.bind(this)};\n frag.loader.load(loaderContext,loaderConfig,loaderCallbacks);\n } else if (this.decryptkey) {\n // we already loaded this key, return it\n decryptdata.key = this.decryptkey;\n this.hls.trigger(Event.KEY_LOADED, {frag: frag});\n }\n }\n\n loadsuccess(response, stats, context) {\n let frag = context.frag;\n this.decryptkey = frag.decryptdata.key = new Uint8Array(response.data);\n // detach fragment loader on load success\n frag.loader = undefined;\n this.loaders[frag.type] = undefined;\n this.hls.trigger(Event.KEY_LOADED, {frag: frag});\n }\n\n loaderror(response, context) {\n let frag = context.frag,\n loader = frag.loader;\n if (loader) {\n loader.abort();\n }\n this.loaders[context.type] = undefined;\n this.hls.trigger(Event.ERROR, {type: ErrorTypes.NETWORK_ERROR, details: ErrorDetails.KEY_LOAD_ERROR, fatal: false, frag: frag, response: response});\n }\n\n loadtimeout(stats, context) {\n let frag = context.frag,\n loader = frag.loader;\n if (loader) {\n loader.abort();\n }\n this.loaders[context.type] = undefined;\n this.hls.trigger(Event.ERROR, {type: ErrorTypes.NETWORK_ERROR, details: ErrorDetails.KEY_LOAD_TIMEOUT, fatal: false, frag: frag});\n }\n}\n\nexport default KeyLoader;\n",
"/**\n * Playlist Loader\n*/\n\nimport URLToolkit from 'url-toolkit';\nimport Event from '../events';\nimport EventHandler from '../event-handler';\nimport {ErrorTypes, ErrorDetails} from '../errors';\nimport AttrList from '../utils/attr-list';\nimport {logger} from '../utils/logger';\n\n// https://regex101.com is your friend\nconst MASTER_PLAYLIST_REGEX = /#EXT-X-STREAM-INF:([^\\n\\r]*)[\\r\\n]+([^\\r\\n]+)/g;\nconst MASTER_PLAYLIST_MEDIA_REGEX = /#EXT-X-MEDIA:(.*)/g;\nconst LEVEL_PLAYLIST_REGEX_FAST = /#EXTINF:(\\d*(?:\\.\\d+)?)(?:,(.*))?|(?!#)(\\S.+)|#EXT-X-BYTERANGE: *(.+)|#EXT-X-PROGRAM-DATE-TIME:(.+)|#.*/g;\nconst LEVEL_PLAYLIST_REGEX_SLOW = /(?:(?:#(EXTM3U))|(?:#EXT-X-(PLAYLIST-TYPE):(.+))|(?:#EXT-X-(MEDIA-SEQUENCE): *(\\d+))|(?:#EXT-X-(TARGETDURATION): *(\\d+))|(?:#EXT-X-(KEY):(.+))|(?:#EXT-X-(START):(.+))|(?:#EXT-X-(ENDLIST))|(?:#EXT-X-(DISCONTINUITY-SEQ)UENCE:(\\d+))|(?:#EXT-X-(DIS)CONTINUITY))|(?:#EXT-X-(VERSION):(\\d+))|(?:(#)(.*):(.*))|(?:(#)(.*))(?:.*)\\r?\\n?/;\n\nclass LevelKey {\n\n constructor() {\n this.method = null;\n this.key = null;\n this.iv = null;\n this._uri = null;\n }\n\n get uri() {\n if (!this._uri && this.reluri) {\n this._uri = URLToolkit.buildAbsoluteURL(this.baseuri, this.reluri);\n }\n return this._uri;\n }\n\n}\n\nclass Fragment {\n\n constructor() {\n this._url = null;\n this._byteRange = null;\n this._decryptdata = null;\n }\n\n get url() {\n if (!this._url && this.relurl) {\n this._url = URLToolkit.buildAbsoluteURL(this.baseurl, this.relurl);\n }\n return this._url;\n }\n\n set url(value) {\n this._url = value;\n }\n\n get programDateTime() {\n if (!this._programDateTime && this.rawProgramDateTime) {\n this._programDateTime = new Date(Date.parse(this.rawProgramDateTime));\n }\n return this._programDateTime;\n }\n\n get byteRange() {\n if (!this._byteRange) {\n this._byteRange = [];\n if (this.rawByteRange) {\n const params = this.rawByteRange.split('@', 2);\n if (params.length === 1) {\n this._byteRange[0] = this.prevFrag ? this.prevFrag.byteRangeEndOffset : 0;\n } else {\n this._byteRange[0] = parseInt(params[1]);\n }\n this._byteRange[1] = parseInt(params[0]) + this._byteRange[0];\n this.prevFrag = null;\n }\n }\n return this._byteRange;\n }\n\n get byteRangeStartOffset() {\n return this.byteRange[0];\n }\n\n get byteRangeEndOffset() {\n return this.byteRange[1];\n }\n\n get decryptdata() {\n if (!this._decryptdata) {\n this._decryptdata = this.fragmentDecryptdataFromLevelkey(this.levelkey, this.sn);\n }\n return this._decryptdata;\n }\n\n /**\n * Utility method for parseLevelPlaylist to create an initialization vector for a given segment\n * @returns {Uint8Array}\n */\n createInitializationVector(segmentNumber) {\n var uint8View = new Uint8Array(16);\n\n for (var i = 12; i < 16; i++) {\n uint8View[i] = (segmentNumber >> 8 * (15 - i)) & 0xff;\n }\n\n return uint8View;\n }\n\n /**\n * Utility method for parseLevelPlaylist to get a fragment's decryption data from the currently parsed encryption key data\n * @param levelkey - a playlist's encryption info\n * @param segmentNumber - the fragment's segment number\n * @returns {*} - an object to be applied as a fragment's decryptdata\n */\n fragmentDecryptdataFromLevelkey(levelkey, segmentNumber) {\n var decryptdata = levelkey;\n\n if (levelkey && levelkey.method && levelkey.uri && !levelkey.iv) {\n decryptdata = new LevelKey();\n decryptdata.method = levelkey.method;\n decryptdata.baseuri = levelkey.baseuri;\n decryptdata.reluri = levelkey.reluri;\n decryptdata.iv = this.createInitializationVector(segmentNumber);\n }\n\n return decryptdata;\n }\n\n cloneObj(obj) {\n return JSON.parse(JSON.stringify(obj));\n }\n}\n\nclass PlaylistLoader extends EventHandler {\n\n constructor(hls) {\n super(hls,\n Event.MANIFEST_LOADING,\n Event.LEVEL_LOADING,\n Event.AUDIO_TRACK_LOADING);\n this.loaders = {};\n }\n\n destroy() {\n for (let loaderName in this.loaders) {\n let loader = this.loaders[loaderName];\n if (loader) {\n loader.destroy();\n }\n }\n this.loaders = {};\n EventHandler.prototype.destroy.call(this);\n }\n\n onManifestLoading(data) {\n this.load(data.url, { type : 'manifest'});\n }\n\n onLevelLoading(data) {\n this.load(data.url, { type : 'level', level : data.level, id : data.id});\n }\n\n onAudioTrackLoading(data) {\n this.load(data.url, { type : 'audioTrack', id : data.id});\n }\n\n load(url, context) {\n let loader = this.loaders[context.type];\n if (loader) {\n let loaderContext = loader.context;\n if (loaderContext && loaderContext.url === url) {\n logger.trace(`playlist request ongoing`);\n return;\n } else {\n logger.warn(`abort previous loader for type:${context.type}`);\n loader.abort();\n }\n }\n let config = this.hls.config,\n retry,\n timeout,\n retryDelay,\n maxRetryDelay;\n if(context.type === 'manifest') {\n retry = config.manifestLoadingMaxRetry;\n timeout = config.manifestLoadingTimeOut;\n retryDelay = config.manifestLoadingRetryDelay;\n maxRetryDelay = config.manifestLoadingMaxRetryTimeout;\n } else {\n retry = config.levelLoadingMaxRetry;\n timeout = config.levelLoadingTimeOut;\n retryDelay = config.levelLoadingRetryDelay;\n maxRetryDelay = config.levelLoadingMaxRetryTimeout;\n logger.log(`loading playlist for ${context.type} ${context.level || context.id}`);\n }\n loader = this.loaders[context.type] = context.loader = typeof(config.pLoader) !== 'undefined' ? new config.pLoader(config) : new config.loader(config);\n context.url = url;\n context.responseType = '';\n\n let loaderConfig, loaderCallbacks;\n loaderConfig = { timeout : timeout, maxRetry : retry , retryDelay : retryDelay, maxRetryDelay : maxRetryDelay};\n loaderCallbacks = { onSuccess : this.loadsuccess.bind(this), onError :this.loaderror.bind(this), onTimeout : this.loadtimeout.bind(this)};\n loader.load(context,loaderConfig,loaderCallbacks);\n }\n\n resolve(url, baseUrl) {\n return URLToolkit.buildAbsoluteURL(baseUrl, url);\n }\n\n parseMasterPlaylist(string, baseurl) {\n let levels = [], result;\n MASTER_PLAYLIST_REGEX.lastIndex = 0;\n while ((result = MASTER_PLAYLIST_REGEX.exec(string)) != null){\n const level = {};\n\n var attrs = level.attrs = new AttrList(result[1]);\n level.url = this.resolve(result[2], baseurl);\n\n var resolution = attrs.decimalResolution('RESOLUTION');\n if(resolution) {\n level.width = resolution.width;\n level.height = resolution.height;\n }\n level.bitrate = attrs.decimalInteger('AVERAGE-BANDWIDTH') || attrs.decimalInteger('BANDWIDTH');\n level.name = attrs.NAME;\n\n var codecs = attrs.CODECS;\n if(codecs) {\n codecs = codecs.split(/[ ,]+/);\n for (let i = 0; i < codecs.length; i++) {\n const codec = codecs[i];\n if (codec.indexOf('avc1') !== -1) {\n level.videoCodec = this.avc1toavcoti(codec);\n } else {\n level.audioCodec = codec;\n }\n }\n }\n\n levels.push(level);\n }\n return levels;\n }\n\n parseMasterPlaylistMedia(string, baseurl, type) {\n let result, medias = [];\n MASTER_PLAYLIST_MEDIA_REGEX.lastIndex = 0;\n while ((result = MASTER_PLAYLIST_MEDIA_REGEX.exec(string)) != null){\n const media = {};\n var attrs = new AttrList(result[1]);\n if(attrs.TYPE === type) {\n media.groupId = attrs['GROUP-ID'];\n media.name = attrs.NAME;\n media.type = type;\n media.default = (attrs.DEFAULT === 'YES');\n media.autoselect = (attrs.AUTOSELECT === 'YES');\n media.forced = (attrs.FORCED === 'YES');\n if (attrs.URI) {\n media.url = this.resolve(attrs.URI, baseurl);\n }\n media.lang = attrs.LANGUAGE;\n if(!media.name) {\n media.name = media.lang;\n }\n medias.push(media);\n }\n }\n return medias;\n }\n\n avc1toavcoti(codec) {\n var result, avcdata = codec.split('.');\n if (avcdata.length > 2) {\n result = avcdata.shift() + '.';\n result += parseInt(avcdata.shift()).toString(16);\n result += ('000' + parseInt(avcdata.shift()).toString(16)).substr(-4);\n } else {\n result = codec;\n }\n return result;\n }\n\n parseLevelPlaylist(string, baseurl, id, type) {\n var currentSN = 0,\n totalduration = 0,\n level = {type: null, version: null, url: baseurl, fragments: [], live: true, startSN: 0},\n levelkey = new LevelKey(),\n cc = 0,\n prevFrag = null,\n frag = new Fragment(),\n result,\n i;\n\n frag.tagList = [];\n\n LEVEL_PLAYLIST_REGEX_FAST.lastIndex = 0;\n\n while ((result = LEVEL_PLAYLIST_REGEX_FAST.exec(string)) !== null) {\n const duration = result[1];\n if (duration) { // INF\n frag.duration = parseFloat(duration);\n const title = result[2];\n frag.title = title ? title : null;\n frag.tagList.push(title ? [ 'INF',duration,title ] : [ 'INF',duration ]);\n } else if (result[3]) { // url\n if (!isNaN(frag.duration)) {\n const sn = currentSN++;\n frag.type = type;\n frag.prevFrag = prevFrag;\n frag.start = totalduration;\n frag.levelkey = levelkey;\n frag.sn = sn;\n frag.level = id;\n frag.cc = cc;\n frag.baseurl = baseurl;\n frag.relurl = result[3];\n\n level.fragments.push(frag);\n prevFrag = frag;\n totalduration += frag.duration;\n\n frag = new Fragment();\n frag.tagList = [];\n }\n } else if (result[4]) { // X-BYTERANGE\n frag.rawByteRange = result[4];\n } else if (result[5]) { // PROGRAM-DATE-TIME\n frag.rawProgramDateTime = result[5];\n frag.tagList.push(['PROGRAM-DATE-TIME', result[5]]);\n } else {\n result = result[0].match(LEVEL_PLAYLIST_REGEX_SLOW);\n for (i = 1; i < result.length; i++) {\n if (result[i] !== undefined) {\n break;\n }\n }\n\n const value1 = result[i+1];\n const value2 = result[i+2];\n\n switch (result[i]) {\n case '#':\n frag.tagList.push(value2 ? [ value1,value2 ] : [ value1 ]);\n break;\n case 'PLAYLIST-TYPE':\n level.type = value1.toUpperCase();\n break;\n case 'MEDIA-SEQUENCE':\n currentSN = level.startSN = parseInt(value1);\n break;\n case 'TARGETDURATION':\n level.targetduration = parseFloat(value1);\n break;\n case 'VERSION':\n level.version = parseInt(value1);\n break;\n case 'EXTM3U':\n break;\n case 'ENDLIST':\n level.live = false;\n break;\n case 'DIS':\n cc++;\n frag.tagList.push(['DIS']);\n break;\n case 'DISCONTINUITY-SEQ':\n cc = parseInt(value1);\n break;\n case 'KEY':\n // https://tools.ietf.org/html/draft-pantos-http-live-streaming-08#section-3.4.4\n var decryptparams = value1;\n var keyAttrs = new AttrList(decryptparams);\n var decryptmethod = keyAttrs.enumeratedString('METHOD'),\n decrypturi = keyAttrs.URI,\n decryptiv = keyAttrs.hexadecimalInteger('IV');\n if (decryptmethod) {\n levelkey = new LevelKey();\n if ((decrypturi) && (decryptmethod === 'AES-128')) {\n levelkey.method = decryptmethod;\n // URI to get the key\n levelkey.baseuri = baseurl;\n levelkey.reluri = decrypturi;\n levelkey.key = null;\n // Initialization Vector (IV)\n levelkey.iv = decryptiv;\n }\n }\n break;\n case 'START':\n let startParams = value1;\n let startAttrs = new AttrList(startParams);\n let startTimeOffset = startAttrs.decimalFloatingPoint('TIME-OFFSET');\n //TIME-OFFSET can be 0\n if ( !isNaN(startTimeOffset) ) {\n level.startTimeOffset = startTimeOffset;\n }\n break;\n default:\n logger.warn(`line parsed but not handled: ${result}`);\n break;\n }\n }\n }\n frag = prevFrag;\n //logger.log('found ' + level.fragments.length + ' fragments');\n if(frag && !frag.relurl) {\n level.fragments.pop();\n totalduration-=frag.duration;\n }\n level.totalduration = totalduration;\n level.averagetargetduration = totalduration / level.fragments.length;\n level.endSN = currentSN - 1;\n return level;\n }\n\n loadsuccess(response, stats, context) {\n var string = response.data,\n url = response.url,\n type = context.type,\n id = context.id,\n level = context.level,\n hls = this.hls;\n\n this.loaders[type] = undefined;\n // responseURL not supported on some browsers (it is used to detect URL redirection)\n // data-uri mode also not supported (but no need to detect redirection)\n if (url === undefined || url.indexOf('data:') === 0) {\n // fallback to initial URL\n url = context.url;\n }\n stats.tload = performance.now();\n //stats.mtime = new Date(target.getResponseHeader('Last-Modified'));\n if (string.indexOf('#EXTM3U') === 0) {\n if (string.indexOf('#EXTINF:') > 0) {\n let isLevel = (type !== 'audioTrack'),\n levelDetails = this.parseLevelPlaylist(string, url, (isLevel ? level : id) || 0, isLevel ? 'main' : 'audio');\n if (type === 'manifest') {\n // first request, stream manifest (no master playlist), fire manifest loaded event with level details\n hls.trigger(Event.MANIFEST_LOADED, {levels: [{url: url, details : levelDetails}], audioTracks : [], url: url, stats: stats});\n }\n stats.tparsed = performance.now();\n if (levelDetails.targetduration) {\n if (isLevel) {\n hls.trigger(Event.LEVEL_LOADED, {details: levelDetails, level: level || 0, id: id || 0, stats: stats});\n } else {\n hls.trigger(Event.AUDIO_TRACK_LOADED, {details: levelDetails, id: id, stats: stats});\n }\n } else {\n hls.trigger(Event.ERROR, {type: ErrorTypes.NETWORK_ERROR, details: ErrorDetails.MANIFEST_PARSING_ERROR, fatal: true, url: url, reason: 'invalid targetduration'});\n }\n } else {\n let levels = this.parseMasterPlaylist(string, url);\n // multi level playlist, parse level info\n if (levels.length) {\n let audiotracks = this.parseMasterPlaylistMedia(string, url, 'AUDIO');\n if (audiotracks.length) {\n // check if we have found an audio track embedded in main playlist (audio track without URI attribute)\n let embeddedAudioFound = false;\n audiotracks.forEach(audioTrack => {\n if(!audioTrack.url) {\n embeddedAudioFound = true;\n }\n });\n // if no embedded audio track defined, but audio codec signaled in quality level, we need to signal this main audio track\n // this could happen with playlists with alt audio rendition in which quality levels (main) contains both audio+video. but with mixed audio track not signaled\n if (embeddedAudioFound === false && levels[0].audioCodec && !levels[0].attrs.AUDIO) {\n logger.log('audio codec signaled in quality level, but no embedded audio track signaled, create one');\n audiotracks.unshift({ type : 'main', name : 'main'});\n }\n }\n hls.trigger(Event.MANIFEST_LOADED, {levels: levels, audioTracks : audiotracks, url: url, stats: stats});\n } else {\n hls.trigger(Event.ERROR, {type: ErrorTypes.NETWORK_ERROR, details: ErrorDetails.MANIFEST_PARSING_ERROR, fatal: true, url: url, reason: 'no level found in manifest'});\n }\n }\n } else {\n hls.trigger(Event.ERROR, {type: ErrorTypes.NETWORK_ERROR, details: ErrorDetails.MANIFEST_PARSING_ERROR, fatal: true, url: url, reason: 'no EXTM3U delimiter'});\n }\n }\n\n loaderror(response, context) {\n var details, fatal,loader = context.loader;\n switch(context.type) {\n case 'manifest':\n details = ErrorDetails.MANIFEST_LOAD_ERROR;\n fatal = true;\n break;\n case 'level':\n details = ErrorDetails.LEVEL_LOAD_ERROR;\n fatal = false;\n break;\n case 'audioTrack':\n details = ErrorDetails.AUDIO_TRACK_LOAD_ERROR;\n fatal = false;\n break;\n }\n if (loader) {\n loader.abort();\n this.loaders[context.type] = undefined;\n }\n this.hls.trigger(Event.ERROR, {type: ErrorTypes.NETWORK_ERROR, details: details, fatal: fatal, url: loader.url, loader: loader, response: response, context : context});\n }\n\n loadtimeout(stats, context) {\n var details, fatal, loader = context.loader;\n switch(context.type) {\n case 'manifest':\n details = ErrorDetails.MANIFEST_LOAD_TIMEOUT;\n fatal = true;\n break;\n case 'level':\n details = ErrorDetails.LEVEL_LOAD_TIMEOUT;\n fatal = false;\n break;\n case 'audioTrack':\n details = ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT;\n fatal = false;\n break;\n }\n if (loader) {\n loader.abort();\n this.loaders[context.type] = undefined;\n }\n this.hls.trigger(Event.ERROR, {type: ErrorTypes.NETWORK_ERROR, details: details, fatal: fatal, url: loader.url, loader: loader, context : context});\n }\n}\n\nexport default PlaylistLoader;\n",
"/**\n * Generate MP4 Box\n*/\n\n//import Hex from '../utils/hex';\nclass MP4 {\n static init() {\n MP4.types = {\n avc1: [], // codingname\n avcC: [],\n btrt: [],\n dinf: [],\n dref: [],\n esds: [],\n ftyp: [],\n hdlr: [],\n mdat: [],\n mdhd: [],\n mdia: [],\n mfhd: [],\n minf: [],\n moof: [],\n moov: [],\n mp4a: [],\n '.mp3': [],\n mvex: [],\n mvhd: [],\n sdtp: [],\n stbl: [],\n stco: [],\n stsc: [],\n stsd: [],\n stsz: [],\n stts: [],\n tfdt: [],\n tfhd: [],\n traf: [],\n trak: [],\n trun: [],\n trex: [],\n tkhd: [],\n vmhd: [],\n smhd: []\n };\n\n var i;\n for (i in MP4.types) {\n if (MP4.types.hasOwnProperty(i)) {\n MP4.types[i] = [\n i.charCodeAt(0),\n i.charCodeAt(1),\n i.charCodeAt(2),\n i.charCodeAt(3)\n ];\n }\n }\n\n var videoHdlr = new Uint8Array([\n 0x00, // version 0\n 0x00, 0x00, 0x00, // flags\n 0x00, 0x00, 0x00, 0x00, // pre_defined\n 0x76, 0x69, 0x64, 0x65, // handler_type: 'vide'\n 0x00, 0x00, 0x00, 0x00, // reserved\n 0x00, 0x00, 0x00, 0x00, // reserved\n 0x00, 0x00, 0x00, 0x00, // reserved\n 0x56, 0x69, 0x64, 0x65,\n 0x6f, 0x48, 0x61, 0x6e,\n 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'VideoHandler'\n ]);\n\n var audioHdlr = new Uint8Array([\n 0x00, // version 0\n 0x00, 0x00, 0x00, // flags\n 0x00, 0x00, 0x00, 0x00, // pre_defined\n 0x73, 0x6f, 0x75, 0x6e, // handler_type: 'soun'\n 0x00, 0x00, 0x00, 0x00, // reserved\n 0x00, 0x00, 0x00, 0x00, // reserved\n 0x00, 0x00, 0x00, 0x00, // reserved\n 0x53, 0x6f, 0x75, 0x6e,\n 0x64, 0x48, 0x61, 0x6e,\n 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'SoundHandler'\n ]);\n\n MP4.HDLR_TYPES = {\n 'video': videoHdlr,\n 'audio': audioHdlr\n };\n\n var dref = new Uint8Array([\n 0x00, // version 0\n 0x00, 0x00, 0x00, // flags\n 0x00, 0x00, 0x00, 0x01, // entry_count\n 0x00, 0x00, 0x00, 0x0c, // entry_size\n 0x75, 0x72, 0x6c, 0x20, // 'url' type\n 0x00, // version 0\n 0x00, 0x00, 0x01 // entry_flags\n ]);\n\n var stco = new Uint8Array([\n 0x00, // version\n 0x00, 0x00, 0x00, // flags\n 0x00, 0x00, 0x00, 0x00 // entry_count\n ]);\n\n MP4.STTS = MP4.STSC = MP4.STCO = stco;\n\n MP4.STSZ = new Uint8Array([\n 0x00, // version\n 0x00, 0x00, 0x00, // flags\n 0x00, 0x00, 0x00, 0x00, // sample_size\n 0x00, 0x00, 0x00, 0x00, // sample_count\n ]);\n MP4.VMHD = new Uint8Array([\n 0x00, // version\n 0x00, 0x00, 0x01, // flags\n 0x00, 0x00, // graphicsmode\n 0x00, 0x00,\n 0x00, 0x00,\n 0x00, 0x00 // opcolor\n ]);\n MP4.SMHD = new Uint8Array([\n 0x00, // version\n 0x00, 0x00, 0x00, // flags\n 0x00, 0x00, // balance\n 0x00, 0x00 // reserved\n ]);\n\n MP4.STSD = new Uint8Array([\n 0x00, // version 0\n 0x00, 0x00, 0x00, // flags\n 0x00, 0x00, 0x00, 0x01]);// entry_count\n\n var majorBrand = new Uint8Array([105,115,111,109]); // isom\n var avc1Brand = new Uint8Array([97,118,99,49]); // avc1\n var minorVersion = new Uint8Array([0, 0, 0, 1]);\n\n MP4.FTYP = MP4.box(MP4.types.ftyp, majorBrand, minorVersion, majorBrand, avc1Brand);\n MP4.DINF = MP4.box(MP4.types.dinf, MP4.box(MP4.types.dref, dref));\n }\n\n static box(type) {\n var\n payload = Array.prototype.slice.call(arguments, 1),\n size = 8,\n i = payload.length,\n len = i,\n result;\n // calculate the total size we need to allocate\n while (i--) {\n size += payload[i].byteLength;\n }\n result = new Uint8Array(size);\n result[0] = (size >> 24) & 0xff;\n result[1] = (size >> 16) & 0xff;\n result[2] = (size >> 8) & 0xff;\n result[3] = size & 0xff;\n result.set(type, 4);\n // copy the payload into the result\n for (i = 0, size = 8; i < len; i++) {\n // copy payload[i] array @ offset size\n result.set(payload[i], size);\n size += payload[i].byteLength;\n }\n return result;\n }\n\n static hdlr(type) {\n return MP4.box(MP4.types.hdlr, MP4.HDLR_TYPES[type]);\n }\n\n static mdat(data) {\n return MP4.box(MP4.types.mdat, data);\n }\n\n static mdhd(timescale, duration) {\n duration *= timescale;\n return MP4.box(MP4.types.mdhd, new Uint8Array([\n 0x00, // version 0\n 0x00, 0x00, 0x00, // flags\n 0x00, 0x00, 0x00, 0x02, // creation_time\n 0x00, 0x00, 0x00, 0x03, // modification_time\n (timescale >> 24) & 0xFF,\n (timescale >> 16) & 0xFF,\n (timescale >> 8) & 0xFF,\n timescale & 0xFF, // timescale\n (duration >> 24),\n (duration >> 16) & 0xFF,\n (duration >> 8) & 0xFF,\n duration & 0xFF, // duration\n 0x55, 0xc4, // 'und' language (undetermined)\n 0x00, 0x00\n ]));\n }\n\n static mdia(track) {\n return MP4.box(MP4.types.mdia, MP4.mdhd(track.timescale, track.duration), MP4.hdlr(track.type), MP4.minf(track));\n }\n\n static mfhd(sequenceNumber) {\n return MP4.box(MP4.types.mfhd, new Uint8Array([\n 0x00,\n 0x00, 0x00, 0x00, // flags\n (sequenceNumber >> 24),\n (sequenceNumber >> 16) & 0xFF,\n (sequenceNumber >> 8) & 0xFF,\n sequenceNumber & 0xFF, // sequence_number\n ]));\n }\n\n static minf(track) {\n if (track.type === 'audio') {\n return MP4.box(MP4.types.minf, MP4.box(MP4.types.smhd, MP4.SMHD), MP4.DINF, MP4.stbl(track));\n } else {\n return MP4.box(MP4.types.minf, MP4.box(MP4.types.vmhd, MP4.VMHD), MP4.DINF, MP4.stbl(track));\n }\n }\n\n static moof(sn, baseMediaDecodeTime, track) {\n return MP4.box(MP4.types.moof, MP4.mfhd(sn), MP4.traf(track,baseMediaDecodeTime));\n }\n/**\n * @param tracks... (optional) {array} the tracks associated with this movie\n */\n static moov(tracks) {\n var\n i = tracks.length,\n boxes = [];\n\n while (i--) {\n boxes[i] = MP4.trak(tracks[i]);\n }\n\n return MP4.box.apply(null, [MP4.types.moov, MP4.mvhd(tracks[0].timescale, tracks[0].duration)].concat(boxes).concat(MP4.mvex(tracks)));\n }\n\n static mvex(tracks) {\n var\n i = tracks.length,\n boxes = [];\n\n while (i--) {\n boxes[i] = MP4.trex(tracks[i]);\n }\n return MP4.box.apply(null, [MP4.types.mvex].concat(boxes));\n }\n\n static mvhd(timescale,duration) {\n duration*=timescale;\n var\n bytes = new Uint8Array([\n 0x00, // version 0\n 0x00, 0x00, 0x00, // flags\n 0x00, 0x00, 0x00, 0x01, // creation_time\n 0x00, 0x00, 0x00, 0x02, // modification_time\n (timescale >> 24) & 0xFF,\n (timescale >> 16) & 0xFF,\n (timescale >> 8) & 0xFF,\n timescale & 0xFF, // timescale\n (duration >> 24) & 0xFF,\n (duration >> 16) & 0xFF,\n (duration >> 8) & 0xFF,\n duration & 0xFF, // duration\n 0x00, 0x01, 0x00, 0x00, // 1.0 rate\n 0x01, 0x00, // 1.0 volume\n 0x00, 0x00, // reserved\n 0x00, 0x00, 0x00, 0x00, // reserved\n 0x00, 0x00, 0x00, 0x00, // reserved\n 0x00, 0x01, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x01, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x40, 0x00, 0x00, 0x00, // transformation: unity matrix\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, // pre_defined\n 0xff, 0xff, 0xff, 0xff // next_track_ID\n ]);\n return MP4.box(MP4.types.mvhd, bytes);\n }\n\n static sdtp(track) {\n var\n samples = track.samples || [],\n bytes = new Uint8Array(4 + samples.length),\n flags,\n i;\n // leave the full box header (4 bytes) all zero\n // write the sample table\n for (i = 0; i < samples.length; i++) {\n flags = samples[i].flags;\n bytes[i + 4] = (flags.dependsOn << 4) |\n (flags.isDependedOn << 2) |\n (flags.hasRedundancy);\n }\n\n return MP4.box(MP4.types.sdtp, bytes);\n }\n\n static stbl(track) {\n return MP4.box(MP4.types.stbl, MP4.stsd(track), MP4.box(MP4.types.stts, MP4.STTS), MP4.box(MP4.types.stsc, MP4.STSC), MP4.box(MP4.types.stsz, MP4.STSZ), MP4.box(MP4.types.stco, MP4.STCO));\n }\n\n static avc1(track) {\n var sps = [], pps = [], i, data, len;\n // assemble the SPSs\n\n for (i = 0; i < track.sps.length; i++) {\n data = track.sps[i];\n len = data.byteLength;\n sps.push((len >>> 8) & 0xFF);\n sps.push((len & 0xFF));\n sps = sps.concat(Array.prototype.slice.call(data)); // SPS\n }\n\n // assemble the PPSs\n for (i = 0; i < track.pps.length; i++) {\n data = track.pps[i];\n len = data.byteLength;\n pps.push((len >>> 8) & 0xFF);\n pps.push((len & 0xFF));\n pps = pps.concat(Array.prototype.slice.call(data));\n }\n\n var avcc = MP4.box(MP4.types.avcC, new Uint8Array([\n 0x01, // version\n sps[3], // profile\n sps[4], // profile compat\n sps[5], // level\n 0xfc | 3, // lengthSizeMinusOne, hard-coded to 4 bytes\n 0xE0 | track.sps.length // 3bit reserved (111) + numOfSequenceParameterSets\n ].concat(sps).concat([\n track.pps.length // numOfPictureParameterSets\n ]).concat(pps))), // \"PPS\"\n width = track.width,\n height = track.height;\n //console.log('avcc:' + Hex.hexDump(avcc));\n return MP4.box(MP4.types.avc1, new Uint8Array([\n 0x00, 0x00, 0x00, // reserved\n 0x00, 0x00, 0x00, // reserved\n 0x00, 0x01, // data_reference_index\n 0x00, 0x00, // pre_defined\n 0x00, 0x00, // reserved\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, // pre_defined\n (width >> 8) & 0xFF,\n width & 0xff, // width\n (height >> 8) & 0xFF,\n height & 0xff, // height\n 0x00, 0x48, 0x00, 0x00, // horizresolution\n 0x00, 0x48, 0x00, 0x00, // vertresolution\n 0x00, 0x00, 0x00, 0x00, // reserved\n 0x00, 0x01, // frame_count\n 0x12,\n 0x64, 0x61, 0x69, 0x6C, //dailymotion/hls.js\n 0x79, 0x6D, 0x6F, 0x74,\n 0x69, 0x6F, 0x6E, 0x2F,\n 0x68, 0x6C, 0x73, 0x2E,\n 0x6A, 0x73, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, // compressorname\n 0x00, 0x18, // depth = 24\n 0x11, 0x11]), // pre_defined = -1\n avcc,\n MP4.box(MP4.types.btrt, new Uint8Array([\n 0x00, 0x1c, 0x9c, 0x80, // bufferSizeDB\n 0x00, 0x2d, 0xc6, 0xc0, // maxBitrate\n 0x00, 0x2d, 0xc6, 0xc0])) // avgBitrate\n );\n }\n\n static esds(track) {\n var configlen = track.config.length;\n return new Uint8Array([\n 0x00, // version 0\n 0x00, 0x00, 0x00, // flags\n\n 0x03, // descriptor_type\n 0x17+configlen, // length\n 0x00, 0x01, //es_id\n 0x00, // stream_priority\n\n 0x04, // descriptor_type\n 0x0f+configlen, // length\n 0x40, //codec : mpeg4_audio\n 0x15, // stream_type\n 0x00, 0x00, 0x00, // buffer_size\n 0x00, 0x00, 0x00, 0x00, // maxBitrate\n 0x00, 0x00, 0x00, 0x00, // avgBitrate\n\n 0x05 // descriptor_type\n ].concat([configlen]).concat(track.config).concat([0x06, 0x01, 0x02])); // GASpecificConfig)); // length + audio config descriptor\n }\n\n static mp4a(track) {\n var audiosamplerate = track.audiosamplerate;\n return MP4.box(MP4.types.mp4a, new Uint8Array([\n 0x00, 0x00, 0x00, // reserved\n 0x00, 0x00, 0x00, // reserved\n 0x00, 0x01, // data_reference_index\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, // reserved\n 0x00, track.channelCount, // channelcount\n 0x00, 0x10, // sampleSize:16bits\n 0x00, 0x00, 0x00, 0x00, // reserved2\n (audiosamplerate >> 8) & 0xFF,\n audiosamplerate & 0xff, //\n 0x00, 0x00]),\n MP4.box(MP4.types.esds, MP4.esds(track)));\n }\n\n static mp3(track) {\n var audiosamplerate = track.audiosamplerate;\n return MP4.box(MP4.types['.mp3'], new Uint8Array([\n 0x00, 0x00, 0x00, // reserved\n 0x00, 0x00, 0x00, // reserved\n 0x00, 0x01, // data_reference_index\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, // reserved\n 0x00, track.channelCount, // channelcount\n 0x00, 0x10, // sampleSize:16bits\n 0x00, 0x00, 0x00, 0x00, // reserved2\n (audiosamplerate >> 8) & 0xFF,\n audiosamplerate & 0xff, //\n 0x00, 0x00]));\n }\n\n static stsd(track) {\n if (track.type === 'audio') {\n if (!track.isAAC && track.codec === 'mp3') {\n return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp3(track));\n }\n return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp4a(track));\n } else {\n return MP4.box(MP4.types.stsd, MP4.STSD, MP4.avc1(track));\n }\n }\n\n static tkhd(track) {\n var id = track.id,\n duration = track.duration*track.timescale,\n width = track.width,\n height = track.height;\n return MP4.box(MP4.types.tkhd, new Uint8Array([\n 0x00, // version 0\n 0x00, 0x00, 0x07, // flags\n 0x00, 0x00, 0x00, 0x00, // creation_time\n 0x00, 0x00, 0x00, 0x00, // modification_time\n (id >> 24) & 0xFF,\n (id >> 16) & 0xFF,\n (id >> 8) & 0xFF,\n id & 0xFF, // track_ID\n 0x00, 0x00, 0x00, 0x00, // reserved\n (duration >> 24),\n (duration >> 16) & 0xFF,\n (duration >> 8) & 0xFF,\n duration & 0xFF, // duration\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, // reserved\n 0x00, 0x00, // layer\n 0x00, 0x00, // alternate_group\n 0x00, 0x00, // non-audio track volume\n 0x00, 0x00, // reserved\n 0x00, 0x01, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x01, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x40, 0x00, 0x00, 0x00, // transformation: unity matrix\n (width >> 8) & 0xFF,\n width & 0xFF,\n 0x00, 0x00, // width\n (height >> 8) & 0xFF,\n height & 0xFF,\n 0x00, 0x00 // height\n ]));\n }\n\n static traf(track,baseMediaDecodeTime) {\n var sampleDependencyTable = MP4.sdtp(track),\n id = track.id;\n return MP4.box(MP4.types.traf,\n MP4.box(MP4.types.tfhd, new Uint8Array([\n 0x00, // version 0\n 0x00, 0x00, 0x00, // flags\n (id >> 24),\n (id >> 16) & 0XFF,\n (id >> 8) & 0XFF,\n (id & 0xFF) // track_ID\n ])),\n MP4.box(MP4.types.tfdt, new Uint8Array([\n 0x00, // version 0\n 0x00, 0x00, 0x00, // flags\n (baseMediaDecodeTime >>24),\n (baseMediaDecodeTime >> 16) & 0XFF,\n (baseMediaDecodeTime >> 8) & 0XFF,\n (baseMediaDecodeTime & 0xFF) // baseMediaDecodeTime\n ])),\n MP4.trun(track,\n sampleDependencyTable.length +\n 16 + // tfhd\n 16 + // tfdt\n 8 + // traf header\n 16 + // mfhd\n 8 + // moof header\n 8), // mdat header\n sampleDependencyTable);\n }\n\n /**\n * Generate a track box.\n * @param track {object} a track definition\n * @return {Uint8Array} the track box\n */\n static trak(track) {\n track.duration = track.duration || 0xffffffff;\n return MP4.box(MP4.types.trak, MP4.tkhd(track), MP4.mdia(track));\n }\n\n static trex(track) {\n var id = track.id;\n return MP4.box(MP4.types.trex, new Uint8Array([\n 0x00, // version 0\n 0x00, 0x00, 0x00, // flags\n (id >> 24),\n (id >> 16) & 0XFF,\n (id >> 8) & 0XFF,\n (id & 0xFF), // track_ID\n 0x00, 0x00, 0x00, 0x01, // default_sample_description_index\n 0x00, 0x00, 0x00, 0x00, // default_sample_duration\n 0x00, 0x00, 0x00, 0x00, // default_sample_size\n 0x00, 0x01, 0x00, 0x01 // default_sample_flags\n ]));\n }\n\n static trun(track, offset) {\n var samples= track.samples || [],\n len = samples.length,\n arraylen = 12 + (16 * len),\n array = new Uint8Array(arraylen),\n i,sample,duration,size,flags,cts;\n offset += 8 + arraylen;\n array.set([\n 0x00, // version 0\n 0x00, 0x0f, 0x01, // flags\n (len >>> 24) & 0xFF,\n (len >>> 16) & 0xFF,\n (len >>> 8) & 0xFF,\n len & 0xFF, // sample_count\n (offset >>> 24) & 0xFF,\n (offset >>> 16) & 0xFF,\n (offset >>> 8) & 0xFF,\n offset & 0xFF // data_offset\n ],0);\n for (i = 0; i < len; i++) {\n sample = samples[i];\n duration = sample.duration;\n size = sample.size;\n flags = sample.flags;\n cts = sample.cts;\n array.set([\n (duration >>> 24) & 0xFF,\n (duration >>> 16) & 0xFF,\n (duration >>> 8) & 0xFF,\n duration & 0xFF, // sample_duration\n (size >>> 24) & 0xFF,\n (size >>> 16) & 0xFF,\n (size >>> 8) & 0xFF,\n size & 0xFF, // sample_size\n (flags.isLeading << 2) | flags.dependsOn,\n (flags.isDependedOn << 6) |\n (flags.hasRedundancy << 4) |\n (flags.paddingValue << 1) |\n flags.isNonSync,\n flags.degradPrio & 0xF0 << 8,\n flags.degradPrio & 0x0F, // sample_flags\n (cts >>> 24) & 0xFF,\n (cts >>> 16) & 0xFF,\n (cts >>> 8) & 0xFF,\n cts & 0xFF // sample_composition_time_offset\n ],12+16*i);\n }\n return MP4.box(MP4.types.trun, array);\n }\n\n static initSegment(tracks) {\n if (!MP4.types) {\n MP4.init();\n }\n var movie = MP4.moov(tracks), result;\n result = new Uint8Array(MP4.FTYP.byteLength + movie.byteLength);\n result.set(MP4.FTYP);\n result.set(movie, MP4.FTYP.byteLength);\n return result;\n }\n}\n\nexport default MP4;\n",
"/**\n * fMP4 remuxer\n*/\n\n\nimport AAC from '../helper/aac';\nimport Event from '../events';\nimport {logger} from '../utils/logger';\nimport MP4 from '../remux/mp4-generator';\nimport {ErrorTypes, ErrorDetails} from '../errors';\n\nclass MP4Remuxer {\n constructor(observer, id, config, typeSupported) {\n this.observer = observer;\n this.id = id;\n this.config = config;\n this.typeSupported = typeSupported;\n this.ISGenerated = false;\n this.PES2MP4SCALEFACTOR = 4;\n this.PES_TIMESCALE = 90000;\n this.MP4_TIMESCALE = this.PES_TIMESCALE / this.PES2MP4SCALEFACTOR;\n }\n\n get passthrough() {\n return false;\n }\n\n destroy() {\n }\n\n insertDiscontinuity() {\n this._initPTS = this._initDTS = undefined;\n }\n\n switchLevel() {\n this.ISGenerated = false;\n }\n\n remux(level,sn,cc,audioTrack,videoTrack,id3Track,textTrack,timeOffset, contiguous,accurateTimeOffset,defaultInitPTS) {\n this.level = level;\n this.sn = sn;\n // generate Init Segment if needed\n if (!this.ISGenerated) {\n this.generateIS(audioTrack,videoTrack,timeOffset,cc);\n }\n\n if((defaultInitPTS!==null)){\n this._initPTS=this._initDTS= defaultInitPTS;\n }\n\n if (this.ISGenerated) {\n // Purposefully remuxing audio before video, so that remuxVideo can use nextAudioPts, which is\n // calculated in remuxAudio.\n //logger.log('nb AAC samples:' + audioTrack.samples.length);\n if (audioTrack.samples.length) {\n let audioData = this.remuxAudio(audioTrack,timeOffset,contiguous,accurateTimeOffset);\n //logger.log('nb AVC samples:' + videoTrack.samples.length);\n if (videoTrack.samples.length) {\n let audioTrackLength;\n if (audioData) {\n audioTrackLength = audioData.endPTS - audioData.startPTS;\n }\n this.remuxVideo(videoTrack,timeOffset,contiguous,audioTrackLength);\n }\n } else {\n let videoData;\n //logger.log('nb AVC samples:' + videoTrack.samples.length);\n if (videoTrack.samples.length) {\n videoData = this.remuxVideo(videoTrack,timeOffset,contiguous);\n }\n if (videoData && audioTrack.codec) {\n this.remuxEmptyAudio(audioTrack, timeOffset, contiguous, videoData);\n }\n }\n }\n //logger.log('nb ID3 samples:' + audioTrack.samples.length);\n if (id3Track.samples.length) {\n this.remuxID3(id3Track,timeOffset);\n }\n //logger.log('nb ID3 samples:' + audioTrack.samples.length);\n if (textTrack.samples.length) {\n this.remuxText(textTrack,timeOffset);\n }\n //notify end of parsing\n this.observer.trigger(Event.FRAG_PARSED, { id : this.id , level : this.level, sn : this.sn});\n }\n\n generateIS(audioTrack,videoTrack,timeOffset,cc) {\n var observer = this.observer,\n audioSamples = audioTrack.samples,\n videoSamples = videoTrack.samples,\n pesTimeScale = this.PES_TIMESCALE,\n typeSupported = this.typeSupported,\n container = 'audio/mp4',\n tracks = {},\n data = { id : this.id, level : this.level, sn : this.sn, tracks : tracks, unique : false },\n computePTSDTS = (this._initPTS === undefined),\n initPTS, initDTS;\n\n if (computePTSDTS) {\n initPTS = initDTS = Infinity;\n }\n if (audioTrack.config && audioSamples.length) {\n audioTrack.timescale = audioTrack.audiosamplerate;\n // MP4 duration (track duration in seconds multiplied by timescale) is coded on 32 bits\n // we know that each AAC sample contains 1024 frames....\n // in order to avoid overflowing the 32 bit counter for large duration, we use smaller timescale (timescale/gcd)\n // we just need to ensure that AAC sample duration will still be an integer (will be 1024/gcd)\n if (audioTrack.timescale * audioTrack.duration > Math.pow(2, 32)) {\n let greatestCommonDivisor = function(a, b) {\n if ( ! b) {\n return a;\n }\n return greatestCommonDivisor(b, a % b);\n };\n audioTrack.timescale = audioTrack.audiosamplerate / greatestCommonDivisor(audioTrack.audiosamplerate,(audioTrack.isAAC ? 1024 : 1152));\n }\n logger.log ('audio mp4 timescale :'+ audioTrack.timescale);\n if (!audioTrack.isAAC) {\n if (typeSupported.mpeg) { // Chrome and Safari\n container = 'audio/mpeg';\n audioTrack.codec = '';\n } else if (typeSupported.mp3) { // Firefox\n audioTrack.codec = 'mp3';\n }\n }\n tracks.audio = {\n container : container,\n codec : audioTrack.codec,\n initSegment : !audioTrack.isAAC && typeSupported.mpeg ? new Uint8Array() : MP4.initSegment([audioTrack]),\n metadata : {\n channelCount : audioTrack.channelCount\n }\n };\n if (computePTSDTS) {\n // remember first PTS of this demuxing context. for audio, PTS = DTS\n initPTS = initDTS = audioSamples[0].pts - pesTimeScale * timeOffset;\n }\n }\n\n if (videoTrack.sps && videoTrack.pps && videoSamples.length) {\n videoTrack.timescale = this.MP4_TIMESCALE;\n tracks.video = {\n container : 'video/mp4',\n codec : videoTrack.codec,\n initSegment : MP4.initSegment([videoTrack]),\n metadata : {\n width : videoTrack.width,\n height : videoTrack.height\n }\n };\n if (computePTSDTS) {\n initPTS = Math.min(initPTS,videoSamples[0].pts - pesTimeScale * timeOffset);\n initDTS = Math.min(initDTS,videoSamples[0].dts - pesTimeScale * timeOffset);\n this.observer.trigger(Event.INIT_PTS_FOUND, { id: this.id, initPTS: initPTS, cc: cc});\n }\n }\n\n if(Object.keys(tracks).length) {\n observer.trigger(Event.FRAG_PARSING_INIT_SEGMENT,data);\n this.ISGenerated = true;\n if (computePTSDTS) {\n this._initPTS = initPTS;\n this._initDTS = initDTS;\n }\n } else {\n observer.trigger(Event.ERROR, {type : ErrorTypes.MEDIA_ERROR, id : this.id, details: ErrorDetails.FRAG_PARSING_ERROR, fatal: false, reason: 'no audio/video samples found'});\n }\n }\n\n remuxVideo(track, timeOffset, contiguous, audioTrackLength) {\n var offset = 8,\n pesTimeScale = this.PES_TIMESCALE,\n pes2mp4ScaleFactor = this.PES2MP4SCALEFACTOR,\n mp4SampleDuration,\n mdat, moof,\n firstPTS, firstDTS,\n nextDTS,\n lastPTS, lastDTS,\n inputSamples = track.samples,\n outputSamples = [],\n nbSamples = inputSamples.length,\n ptsNormalize = this._PTSNormalize,\n initDTS = this._initDTS;\n\n // for (let i = 0; i < track.samples.length; i++) {\n // let avcSample = track.samples[i];\n // let units = avcSample.units.units;\n // let unitsString = '';\n // for (let j = 0; j < units.length ; j++) {\n // unitsString += units[j].type + ',';\n // if (units[j].data.length < 500) {\n // unitsString += Hex.hexDump(units[j].data);\n // }\n // }\n // logger.log(avcSample.pts + '/' + avcSample.dts + ',' + unitsString + avcSample.units.length);\n // }\n\n // sort video samples by DTS then PTS order\n inputSamples.sort(function(a, b) {\n const deltadts = a.dts - b.dts;\n return deltadts ? deltadts : (a.pts - b.pts);\n });\n\n // handle broken streams with PTS < DTS, tolerance up 200ms (18000 in 90kHz timescale)\n let PTSDTSshift = inputSamples.reduce( (prev, curr) => Math.max(Math.min(prev,curr.pts-curr.dts),-18000),0);\n if (PTSDTSshift < 0) {\n logger.warn(`PTS < DTS detected in video samples, shifting DTS by ${Math.round(PTSDTSshift/90)} ms to overcome this issue`);\n for (let i = 0; i < inputSamples.length; i++) {\n inputSamples[i].dts += PTSDTSshift;\n }\n }\n\n // PTS is coded on 33bits, and can loop from -2^32 to 2^32\n // ptsNormalize will make PTS/DTS value monotonic, we use last known DTS value as reference value\n let nextAvcDts;\n // contiguous fragments are consecutive fragments from same quality level (same level, new SN = old SN + 1)\n if (contiguous) {\n // if parsed fragment is contiguous with last one, let's use last DTS value as reference\n nextAvcDts = this.nextAvcDts;\n } else {\n // if not contiguous, let's use target timeOffset\n nextAvcDts = timeOffset*pesTimeScale;\n }\n\n // compute first DTS and last DTS, normalize them against reference value\n let sample = inputSamples[0];\n firstDTS = Math.max(ptsNormalize(sample.dts - initDTS,nextAvcDts),0);\n firstPTS = Math.max(ptsNormalize(sample.pts - initDTS,nextAvcDts),0);\n\n // check timestamp continuity accross consecutive fragments (this is to remove inter-fragment gap/hole)\n let delta = Math.round((firstDTS - nextAvcDts) / 90);\n // if fragment are contiguous, detect hole/overlapping between fragments\n if (contiguous) {\n if (delta) {\n if (delta > 1) {\n logger.log(`AVC:${delta} ms hole between fragments detected,filling it`);\n } else if (delta < -1) {\n logger.log(`AVC:${(-delta)} ms overlapping between fragments detected`);\n }\n // remove hole/gap : set DTS to next expected DTS\n firstDTS = nextAvcDts;\n inputSamples[0].dts = firstDTS + initDTS;\n // offset PTS as well, ensure that PTS is smaller or equal than new DTS\n firstPTS = Math.max(firstPTS - delta, nextAvcDts);\n inputSamples[0].pts = firstPTS + initDTS;\n logger.log(`Video/PTS/DTS adjusted: ${Math.round(firstPTS/90)}/${Math.round(firstDTS/90)},delta:${delta} ms`);\n }\n }\n nextDTS = firstDTS;\n\n // compute lastPTS/lastDTS\n sample = inputSamples[inputSamples.length-1];\n lastDTS = Math.max(ptsNormalize(sample.dts - initDTS,nextAvcDts) ,0);\n lastPTS = Math.max(ptsNormalize(sample.pts - initDTS,nextAvcDts) ,0);\n lastPTS = Math.max(lastPTS, lastDTS);\n\n let vendor = navigator.vendor, userAgent = navigator.userAgent,\n isSafari = vendor && vendor.indexOf('Apple') > -1 && userAgent && !userAgent.match('CriOS');\n\n // on Safari let's signal the same sample duration for all samples\n // sample duration (as expected by trun MP4 boxes), should be the delta between sample DTS\n // set this constant duration as being the avg delta between consecutive DTS.\n if (isSafari) {\n mp4SampleDuration = Math.round((lastDTS-firstDTS)/(pes2mp4ScaleFactor*(inputSamples.length-1)));\n }\n\n // normalize all PTS/DTS now ...\n for (let i = 0 ; i < nbSamples; i++) {\n let sample = inputSamples[i];\n if (isSafari) {\n // sample DTS is computed using a constant decoding offset (mp4SampleDuration) between samples\n sample.dts = firstDTS + i*pes2mp4ScaleFactor*mp4SampleDuration;\n } else {\n // ensure sample monotonic DTS\n sample.dts = Math.max(ptsNormalize(sample.dts - initDTS, nextAvcDts),firstDTS);\n // ensure dts is a multiple of scale factor to avoid rounding issues\n sample.dts = Math.round(sample.dts/pes2mp4ScaleFactor)*pes2mp4ScaleFactor;\n }\n // we normalize PTS against nextAvcDts, we also substract initDTS (some streams don't start @ PTS O)\n // and we ensure that computed value is greater or equal than sample DTS\n sample.pts = Math.max(ptsNormalize(sample.pts - initDTS,nextAvcDts) , sample.dts);\n // ensure pts is a multiple of scale factor to avoid rounding issues\n sample.pts = Math.round(sample.pts/pes2mp4ScaleFactor)*pes2mp4ScaleFactor;\n }\n\n /* concatenate the video data and construct the mdat in place\n (need 8 more bytes to fill length and mpdat type) */\n let mdatSize = track.len + (4 * track.nbNalu) + 8;\n try {\n mdat = new Uint8Array(mdatSize);\n } catch(err) {\n this.observer.trigger(Event.ERROR, {type : ErrorTypes.MUX_ERROR, level: this.level, id : this.id, details: ErrorDetails.REMUX_ALLOC_ERROR, fatal: false, bytes : mdatSize, reason: `fail allocating video mdat ${mdatSize}`});\n return;\n }\n let view = new DataView(mdat.buffer);\n view.setUint32(0, mdatSize);\n mdat.set(MP4.types.mdat, 4);\n\n for (let i = 0 ; i < nbSamples; i++) {\n let avcSample = inputSamples[i],\n avcSampleUnits = avcSample.units.units,\n mp4SampleLength = 0,\n compositionTimeOffset;\n // convert NALU bitstream to MP4 format (prepend NALU with size field)\n for(let j = 0, nbUnits = avcSampleUnits.length; j < nbUnits ; j++) {\n let unit = avcSampleUnits[j],\n unitData = unit.data,\n unitDataLen = unit.data.byteLength;\n view.setUint32(offset, unitDataLen);\n offset += 4;\n mdat.set(unitData, offset);\n offset += unitDataLen;\n mp4SampleLength += 4 + unitDataLen;\n }\n\n if(!isSafari) {\n // expected sample duration is the Decoding Timestamp diff of consecutive samples\n if (i < nbSamples - 1) {\n mp4SampleDuration = inputSamples[i+1].dts - avcSample.dts;\n } else {\n let config = this.config,\n lastFrameDuration = avcSample.dts - inputSamples[i > 0 ? i-1 : i].dts;\n if (config.stretchShortVideoTrack) {\n // In some cases, a segment's audio track duration may exceed the video track duration.\n // Since we've already remuxed audio, and we know how long the audio track is, we look to\n // see if the delta to the next segment is longer than the minimum of maxBufferHole and\n // maxSeekHole. If so, playback would potentially get stuck, so we artificially inflate\n // the duration of the last frame to minimize any potential gap between segments.\n let maxBufferHole = config.maxBufferHole,\n maxSeekHole = config.maxSeekHole,\n gapTolerance = Math.floor(Math.min(maxBufferHole, maxSeekHole) * pesTimeScale),\n deltaToFrameEnd = (audioTrackLength ? firstPTS + audioTrackLength * pesTimeScale : this.nextAudioPts) - avcSample.pts;\n if (deltaToFrameEnd > gapTolerance) {\n // We subtract lastFrameDuration from deltaToFrameEnd to try to prevent any video\n // frame overlap. maxBufferHole/maxSeekHole should be >> lastFrameDuration anyway.\n mp4SampleDuration = deltaToFrameEnd - lastFrameDuration;\n if (mp4SampleDuration < 0) {\n mp4SampleDuration = lastFrameDuration;\n }\n logger.log(`It is approximately ${deltaToFrameEnd/90} ms to the next segment; using duration ${mp4SampleDuration/90} ms for the last video frame.`);\n } else {\n mp4SampleDuration = lastFrameDuration;\n }\n } else {\n mp4SampleDuration = lastFrameDuration;\n }\n }\n mp4SampleDuration /= pes2mp4ScaleFactor;\n compositionTimeOffset = Math.round((avcSample.pts - avcSample.dts) / pes2mp4ScaleFactor);\n } else {\n compositionTimeOffset = Math.max(0,mp4SampleDuration*Math.round((avcSample.pts - avcSample.dts)/(pes2mp4ScaleFactor*mp4SampleDuration)));\n }\n\n\n //console.log('PTS/DTS/initDTS/normPTS/normDTS/relative PTS : ${avcSample.pts}/${avcSample.dts}/${initDTS}/${ptsnorm}/${dtsnorm}/${(avcSample.pts/4294967296).toFixed(3)}');\n outputSamples.push({\n size: mp4SampleLength,\n // constant duration\n duration: mp4SampleDuration,\n cts: compositionTimeOffset,\n flags: {\n isLeading: 0,\n isDependedOn: 0,\n hasRedundancy: 0,\n degradPrio: 0,\n dependsOn : avcSample.key ? 2 : 1,\n isNonSync : avcSample.key ? 0 : 1\n }\n });\n }\n // next AVC sample DTS should be equal to last sample DTS + last sample duration (in PES timescale)\n this.nextAvcDts = lastDTS + mp4SampleDuration*pes2mp4ScaleFactor;\n let dropped = track.dropped;\n track.len = 0;\n track.nbNalu = 0;\n track.dropped = 0;\n if(outputSamples.length && navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {\n let flags = outputSamples[0].flags;\n // chrome workaround, mark first sample as being a Random Access Point to avoid sourcebuffer append issue\n // https://code.google.com/p/chromium/issues/detail?id=229412\n flags.dependsOn = 2;\n flags.isNonSync = 0;\n }\n track.samples = outputSamples;\n moof = MP4.moof(track.sequenceNumber++, firstDTS / pes2mp4ScaleFactor, track);\n track.samples = [];\n\n let data = {\n id : this.id,\n level : this.level,\n sn : this.sn,\n data1: moof,\n data2: mdat,\n startPTS: firstPTS / pesTimeScale,\n endPTS: (lastPTS + pes2mp4ScaleFactor * mp4SampleDuration) / pesTimeScale,\n startDTS: firstDTS / pesTimeScale,\n endDTS: this.nextAvcDts / pesTimeScale,\n type: 'video',\n nb: outputSamples.length,\n dropped : dropped\n };\n this.observer.trigger(Event.FRAG_PARSING_DATA, data);\n return data;\n }\n\n remuxAudio(track, timeOffset, contiguous,accurateTimeOffset) {\n const pesTimeScale = this.PES_TIMESCALE,\n mp4timeScale = track.timescale,\n pes2mp4ScaleFactor = pesTimeScale/mp4timeScale,\n expectedSampleDuration = track.timescale * (track.isAAC ? 1024 : 1152) / track.audiosamplerate,\n pesFrameDuration = expectedSampleDuration * pes2mp4ScaleFactor,\n ptsNormalize = this._PTSNormalize,\n initDTS = this._initDTS,\n rawMPEG = !track.isAAC && this.typeSupported.mpeg;\n\n var view,\n offset = rawMPEG ? 0 : 8,\n audioSample, mp4Sample,\n unit,\n mdat, moof,\n firstPTS, firstDTS, lastDTS,\n pts, dts, ptsnorm, dtsnorm,\n outputSamples = [],\n inputSamples = [],\n fillFrame, newStamp,\n nextAudioPts;\n\n track.samples.sort(function(a, b) {\n return (a.pts-b.pts);\n });\n inputSamples = track.samples;\n\n // for audio samples, also consider consecutive fragments as being contiguous (even if a level switch occurs),\n // for sake of clarity:\n // consecutive fragments are frags with\n // - less than 100ms gaps between new time offset and next expected PTS OR\n // - less than 20 audio frames distance\n // contiguous fragments are consecutive fragments from same quality level (same level, new SN = old SN + 1)\n // this helps ensuring audio continuity\n // and this also avoids audio glitches/cut when switching quality, or reporting wrong duration on first audio frame\n\n nextAudioPts = this.nextAudioPts;\n contiguous |= (inputSamples.length && nextAudioPts &&\n (Math.abs(timeOffset-nextAudioPts/pesTimeScale) < 0.1 ||\n Math.abs((inputSamples[0].pts-nextAudioPts-this._initDTS)) < 20*pesFrameDuration)\n );\n\n if (!contiguous) {\n // if fragments are not contiguous, let's use timeOffset to compute next Audio PTS\n nextAudioPts = timeOffset*pesTimeScale;\n }\n // If the audio track is missing samples, the frames seem to get \"left-shifted\" within the\n // resulting mp4 segment, causing sync issues and leaving gaps at the end of the audio segment.\n // In an effort to prevent this from happening, we inject frames here where there are gaps.\n // When possible, we inject a silent frame; when that's not possible, we duplicate the last\n // frame.\n\n // only inject/drop audio frames in case time offset is accurate\n if (accurateTimeOffset && track.isAAC) {\n for (let i = 0, nextPtsNorm = nextAudioPts; i < inputSamples.length; ) {\n // First, let's see how far off this frame is from where we expect it to be\n var sample = inputSamples[i],\n ptsNorm = ptsNormalize(sample.pts - initDTS, nextAudioPts),\n delta = ptsNorm - nextPtsNorm;\n\n // If we're overlapping by more than a duration, drop this sample\n if (delta <= -pesFrameDuration) {\n logger.warn(`Dropping 1 audio frame @ ${Math.round(nextPtsNorm/90)/1000}s due to ${Math.round(Math.abs(delta / 90))} ms overlap.`);\n inputSamples.splice(i, 1);\n track.len -= sample.unit.length;\n // Don't touch nextPtsNorm or i\n }\n // Otherwise, if we're more than a frame away from where we should be, insert missing frames\n else if (delta >= pesFrameDuration) {\n var missing = Math.round(delta / pesFrameDuration);\n logger.warn(`Injecting ${missing} audio frame @ ${Math.round(nextPtsNorm/90)/1000}s due to ${Math.round(delta / 90)} ms gap.`);\n for (var j = 0; j < missing; j++) {\n newStamp = nextPtsNorm + initDTS;\n newStamp = Math.max(newStamp, initDTS);\n fillFrame = AAC.getSilentFrame(track.manifestCodec || track.codec,track.channelCount);\n if (!fillFrame) {\n logger.log('Unable to get silent frame for given audio codec; duplicating last frame instead.');\n fillFrame = sample.unit.subarray();\n }\n inputSamples.splice(i, 0, {unit: fillFrame, pts: newStamp, dts: newStamp});\n track.len += fillFrame.length;\n nextPtsNorm += pesFrameDuration;\n i += 1;\n }\n\n // Adjust sample to next expected pts\n sample.pts = sample.dts = nextPtsNorm + initDTS;\n nextPtsNorm += pesFrameDuration;\n i += 1;\n }\n // Otherwise, we're within half a frame duration, so just adjust pts\n else {\n if (Math.abs(delta) > (0.1 * pesFrameDuration)) {\n //logger.log(`Invalid frame delta ${Math.round(ptsNorm - nextPtsNorm + pesFrameDuration)} at PTS ${Math.round(ptsNorm / 90)} (should be ${Math.round(pesFrameDuration)}).`);\n }\n nextPtsNorm += pesFrameDuration;\n if (i === 0) {\n sample.pts = sample.dts = initDTS + nextAudioPts;\n } else {\n sample.pts = sample.dts = inputSamples[i - 1].pts + pesFrameDuration;\n }\n i += 1;\n }\n }\n }\n\n\n for (let j =0 , nbSamples = inputSamples.length; j < nbSamples ; j++) {\n audioSample = inputSamples[j];\n unit = audioSample.unit;\n pts = audioSample.pts - initDTS;\n dts = audioSample.dts - initDTS;\n //logger.log(`Audio/PTS:${Math.round(pts/90)}`);\n // if not first sample\n if (lastDTS !== undefined) {\n ptsnorm = ptsNormalize(pts, lastDTS);\n dtsnorm = ptsNormalize(dts, lastDTS);\n mp4Sample.duration = Math.round((dtsnorm - lastDTS) / pes2mp4ScaleFactor);\n } else {\n ptsnorm = ptsNormalize(pts, nextAudioPts);\n dtsnorm = ptsNormalize(dts, nextAudioPts);\n let delta = Math.round(1000 * (ptsnorm - nextAudioPts) / pesTimeScale),\n numMissingFrames = 0;\n // if fragment are contiguous, detect hole/overlapping between fragments\n // contiguous fragments are consecutive fragments from same quality level (same level, new SN = old SN + 1)\n if (contiguous && track.isAAC) {\n // log delta\n if (delta) {\n if (delta > 0) {\n numMissingFrames = Math.round((ptsnorm - nextAudioPts) / pesFrameDuration);\n logger.log(`${delta} ms hole between AAC samples detected,filling it`);\n if (numMissingFrames > 0) {\n fillFrame = AAC.getSilentFrame(track.manifestCodec || track.codec,track.channelCount);\n if (!fillFrame) {\n fillFrame = unit.subarray();\n }\n track.len += numMissingFrames * fillFrame.length;\n }\n // if we have frame overlap, overlapping for more than half a frame duraion\n } else if (delta < -12) {\n // drop overlapping audio frames... browser will deal with it\n logger.log(`${(-delta)} ms overlapping between AAC samples detected, drop frame`);\n track.len -= unit.byteLength;\n continue;\n }\n // set PTS/DTS to expected PTS/DTS\n ptsnorm = dtsnorm = nextAudioPts;\n }\n }\n // remember first PTS of our audioSamples, ensure value is positive\n firstPTS = Math.max(0, ptsnorm);\n firstDTS = Math.max(0, dtsnorm);\n if(track.len > 0) {\n /* concatenate the audio data and construct the mdat in place\n (need 8 more bytes to fill length and mdat type) */\n\n\n let mdatSize = rawMPEG ? track.len : track.len + 8;\n try {\n mdat = new Uint8Array(mdatSize);\n } catch(err) {\n this.observer.trigger(Event.ERROR, {type : ErrorTypes.MUX_ERROR, level: this.level, id : this.id, details: ErrorDetails.REMUX_ALLOC_ERROR, fatal: false, bytes : mdatSize, reason: `fail allocating audio mdat ${mdatSize}`});\n return;\n }\n if (!rawMPEG) {\n view = new DataView(mdat.buffer);\n view.setUint32(0, mdatSize);\n mdat.set(MP4.types.mdat, 4);\n }\n } else {\n // no audio samples\n return;\n }\n for (let i = 0; i < numMissingFrames; i++) {\n newStamp = ptsnorm - (numMissingFrames - i) * pesFrameDuration;\n fillFrame = AAC.getSilentFrame(track.manifestCodec || track.codec,track.channelCount);\n if (!fillFrame) {\n logger.log('Unable to get silent frame for given audio codec; duplicating this frame instead.');\n fillFrame = unit.subarray();\n }\n mdat.set(fillFrame, offset);\n offset += fillFrame.byteLength;\n mp4Sample = {\n size: fillFrame.byteLength,\n cts: 0,\n duration: 1024,\n flags: {\n isLeading: 0,\n isDependedOn: 0,\n hasRedundancy: 0,\n degradPrio: 0,\n dependsOn: 1,\n }\n };\n outputSamples.push(mp4Sample);\n }\n }\n mdat.set(unit, offset);\n let unitLen = unit.byteLength;\n offset += unitLen;\n //console.log('PTS/DTS/initDTS/normPTS/normDTS/relative PTS : ${audioSample.pts}/${audioSample.dts}/${initDTS}/${ptsnorm}/${dtsnorm}/${(audioSample.pts/4294967296).toFixed(3)}');\n mp4Sample = {\n size: unitLen,\n cts: 0,\n duration: 0,\n flags: {\n isLeading: 0,\n isDependedOn: 0,\n hasRedundancy: 0,\n degradPrio: 0,\n dependsOn: 1,\n }\n };\n outputSamples.push(mp4Sample);\n lastDTS = dtsnorm;\n }\n var lastSampleDuration = 0;\n var nbSamples = outputSamples.length;\n //set last sample duration as being identical to previous sample\n if (nbSamples >= 2) {\n lastSampleDuration = outputSamples[nbSamples - 2].duration;\n mp4Sample.duration = lastSampleDuration;\n }\n if (nbSamples) {\n // next audio sample PTS should be equal to last sample PTS + duration\n this.nextAudioPts = ptsnorm + pes2mp4ScaleFactor * lastSampleDuration;\n //logger.log('Audio/PTS/PTSend:' + audioSample.pts.toFixed(0) + '/' + this.nextAacDts.toFixed(0));\n track.len = 0;\n track.samples = outputSamples;\n if (rawMPEG) {\n moof = new Uint8Array();\n } else {\n moof = MP4.moof(track.sequenceNumber++, firstDTS / pes2mp4ScaleFactor, track);\n }\n track.samples = [];\n let audioData = {\n id : this.id,\n level : this.level,\n sn : this.sn,\n data1: moof,\n data2: mdat,\n startPTS: firstPTS / pesTimeScale,\n endPTS: this.nextAudioPts / pesTimeScale,\n startDTS: firstDTS / pesTimeScale,\n endDTS: (dtsnorm + pes2mp4ScaleFactor * lastSampleDuration) / pesTimeScale,\n type: 'audio',\n nb: nbSamples\n };\n this.observer.trigger(Event.FRAG_PARSING_DATA, audioData);\n return audioData;\n }\n return null;\n }\n\n remuxEmptyAudio(track, timeOffset, contiguous, videoData) {\n let pesTimeScale = this.PES_TIMESCALE,\n mp4timeScale = track.timescale ? track.timescale : track.audiosamplerate,\n pes2mp4ScaleFactor = pesTimeScale/mp4timeScale,\n nextAudioPts = this.nextAudioPts,\n\n // sync with video's timestamp\n startDTS = (nextAudioPts !== undefined ? nextAudioPts : videoData.startDTS * pesTimeScale) + this._initDTS,\n endDTS = videoData.endDTS * pesTimeScale + this._initDTS,\n // one sample's duration value\n sampleDuration = 1024,\n frameDuration = pes2mp4ScaleFactor * sampleDuration,\n\n // samples count of this segment's duration\n nbSamples = Math.ceil((endDTS - startDTS) / frameDuration),\n\n // silent frame\n silentFrame = AAC.getSilentFrame(track.manifestCodec || track.codec,track.channelCount);\n\n logger.warn('remux empty Audio');\n // Can't remux if we can't generate a silent frame...\n if (!silentFrame) {\n logger.trace('Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec!');\n return;\n }\n\n let samples = [];\n for(var i = 0; i < nbSamples; i++) {\n var stamp = startDTS + i * frameDuration;\n samples.push({unit: silentFrame, pts: stamp, dts: stamp});\n track.len += silentFrame.length;\n }\n track.samples = samples;\n\n this.remuxAudio(track, timeOffset, contiguous);\n }\n\n remuxID3(track,timeOffset) {\n var length = track.samples.length, sample;\n // consume samples\n if(length) {\n for(var index = 0; index < length; index++) {\n sample = track.samples[index];\n // setting id3 pts, dts to relative time\n // using this._initPTS and this._initDTS to calculate relative time\n sample.pts = ((sample.pts - this._initPTS) / this.PES_TIMESCALE);\n sample.dts = ((sample.dts - this._initDTS) / this.PES_TIMESCALE);\n }\n this.observer.trigger(Event.FRAG_PARSING_METADATA, {\n id : this.id,\n level : this.level,\n sn : this.sn,\n samples:track.samples\n });\n }\n\n track.samples = [];\n timeOffset = timeOffset;\n }\n\n remuxText(track,timeOffset) {\n track.samples.sort(function(a, b) {\n return (a.pts-b.pts);\n });\n\n var length = track.samples.length, sample;\n // consume samples\n if(length) {\n for(var index = 0; index < length; index++) {\n sample = track.samples[index];\n // setting text pts, dts to relative time\n // using this._initPTS and this._initDTS to calculate relative time\n sample.pts = ((sample.pts - this._initPTS) / this.PES_TIMESCALE);\n }\n this.observer.trigger(Event.FRAG_PARSING_USERDATA, {\n id : this.id,\n level : this.level,\n sn : this.sn,\n samples:track.samples\n });\n }\n\n track.samples = [];\n timeOffset = timeOffset;\n }\n\n _PTSNormalize(value, reference) {\n var offset;\n if (reference === undefined) {\n return value;\n }\n if (reference < value) {\n // - 2^33\n offset = -8589934592;\n } else {\n // + 2^33\n offset = 8589934592;\n }\n /* PTS is 33bit (from 0 to 2^33 -1)\n if diff between value and reference is bigger than half of the amplitude (2^32) then it means that\n PTS looping occured. fill the gap */\n while (Math.abs(value - reference) > 4294967296) {\n value += offset;\n }\n return value;\n }\n\n}\n\nexport default MP4Remuxer;\n",
"/**\n * passthrough remuxer\n*/\nimport Event from '../events';\n\nclass PassThroughRemuxer {\n constructor(observer,id) {\n this.observer = observer;\n this.id = id;\n this.ISGenerated = false;\n }\n\n get passthrough() {\n return true;\n }\n\n destroy() {\n }\n\n insertDiscontinuity() {\n }\n\n switchLevel() {\n this.ISGenerated = false;\n }\n\n remux(audioTrack,videoTrack,id3Track,textTrack,timeOffset,rawData) {\n var observer = this.observer;\n // generate Init Segment if needed\n if (!this.ISGenerated) {\n var tracks = {},\n data = { id : this.id, tracks : tracks, unique : true },\n track = videoTrack,\n codec = track.codec;\n\n if (codec) {\n data.tracks.video = {\n container : track.container,\n codec : codec,\n metadata : {\n width : track.width,\n height : track.height\n }\n };\n }\n\n track = audioTrack;\n codec = track.codec;\n if (codec) {\n data.tracks.audio = {\n container : track.container,\n codec : codec,\n metadata : {\n channelCount : track.channelCount\n }\n };\n }\n this.ISGenerated = true;\n observer.trigger(Event.FRAG_PARSING_INIT_SEGMENT,data);\n }\n observer.trigger(Event.FRAG_PARSING_DATA, {\n id : this.id,\n data1: rawData,\n startPTS: timeOffset,\n startDTS: timeOffset,\n type: 'audiovideo',\n nb: 1,\n dropped : 0\n });\n }\n}\n\nexport default PassThroughRemuxer;\n",
"const DECIMAL_RESOLUTION_REGEX = /^(\\d+)x(\\d+)$/;\nconst ATTR_LIST_REGEX = /\\s*(.+?)\\s*=((?:\\\".*?\\\")|.*?)(?:,|$)/g;\n\n// adapted from https://github.com/kanongil/node-m3u8parse/blob/master/attrlist.js\nclass AttrList {\n\n constructor(attrs) {\n if (typeof attrs === 'string') {\n attrs = AttrList.parseAttrList(attrs);\n }\n for(var attr in attrs){\n if(attrs.hasOwnProperty(attr)) {\n this[attr] = attrs[attr];\n }\n }\n }\n\n decimalInteger(attrName) {\n const intValue = parseInt(this[attrName], 10);\n if (intValue > Number.MAX_SAFE_INTEGER) {\n return Infinity;\n }\n return intValue;\n }\n\n hexadecimalInteger(attrName) {\n if(this[attrName]) {\n let stringValue = (this[attrName] || '0x').slice(2);\n stringValue = ((stringValue.length & 1) ? '0' : '') + stringValue;\n\n const value = new Uint8Array(stringValue.length / 2);\n for (let i = 0; i < stringValue.length / 2; i++) {\n value[i] = parseInt(stringValue.slice(i * 2, i * 2 + 2), 16);\n }\n return value;\n } else {\n return null;\n }\n }\n\n hexadecimalIntegerAsNumber(attrName) {\n const intValue = parseInt(this[attrName], 16);\n if (intValue > Number.MAX_SAFE_INTEGER) {\n return Infinity;\n }\n return intValue;\n }\n\n decimalFloatingPoint(attrName) {\n return parseFloat(this[attrName]);\n }\n\n enumeratedString(attrName) {\n return this[attrName];\n }\n\n decimalResolution(attrName) {\n const res = DECIMAL_RESOLUTION_REGEX.exec(this[attrName]);\n if (res === null) {\n return undefined;\n }\n return {\n width: parseInt(res[1], 10),\n height: parseInt(res[2], 10)\n };\n }\n\n static parseAttrList(input) {\n var match, attrs = {};\n ATTR_LIST_REGEX.lastIndex = 0;\n while ((match = ATTR_LIST_REGEX.exec(input)) !== null) {\n var value = match[2], quote = '\"';\n\n if (value.indexOf(quote) === 0 &&\n value.lastIndexOf(quote) === (value.length-1)) {\n value = value.slice(1, -1);\n }\n attrs[match[1]] = value;\n }\n return attrs;\n }\n\n}\n\nexport default AttrList;\n",
"var BinarySearch = {\n /**\n * Searches for an item in an array which matches a certain condition.\n * This requires the condition to only match one item in the array,\n * and for the array to be ordered.\n *\n * @param {Array} list The array to search.\n * @param {Function} comparisonFunction\n * Called and provided a candidate item as the first argument.\n * Should return:\n * > -1 if the item should be located at a lower index than the provided item.\n * > 1 if the item should be located at a higher index than the provided item.\n * > 0 if the item is the item you're looking for.\n *\n * @return {*} The object if it is found or null otherwise.\n */\n search: function(list, comparisonFunction) {\n var minIndex = 0;\n var maxIndex = list.length - 1;\n var currentIndex = null;\n var currentElement = null;\n \n while (minIndex <= maxIndex) {\n currentIndex = (minIndex + maxIndex) / 2 | 0;\n currentElement = list[currentIndex];\n \n var comparisonResult = comparisonFunction(currentElement);\n if (comparisonResult > 0) {\n minIndex = currentIndex + 1;\n }\n else if (comparisonResult < 0) {\n maxIndex = currentIndex - 1;\n }\n else {\n return currentElement;\n }\n }\n \n return null;\n }\n};\n\nmodule.exports = BinarySearch;\n",
"/**\n *\n * This code was ported from the dash.js project at:\n * https://github.com/Dash-Industry-Forum/dash.js/blob/development/externals/cea608-parser.js\n * https://github.com/Dash-Industry-Forum/dash.js/commit/8269b26a761e0853bb21d78780ed945144ecdd4d#diff-71bc295a2d6b6b7093a1d3290d53a4b2\n *\n * The original copyright appears below:\n *\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2015-2016, DASH Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * 2. Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n /**\n * Exceptions from regular ASCII. CodePoints are mapped to UTF-16 codes\n */\n\nvar specialCea608CharsCodes = {\n 0x2a : 0xe1, // lowercase a, acute accent\n 0x5c : 0xe9, // lowercase e, acute accent\n 0x5e : 0xed, // lowercase i, acute accent\n 0x5f : 0xf3, // lowercase o, acute accent\n 0x60 : 0xfa, // lowercase u, acute accent\n 0x7b : 0xe7, // lowercase c with cedilla\n 0x7c : 0xf7, // division symbol\n 0x7d : 0xd1, // uppercase N tilde\n 0x7e : 0xf1, // lowercase n tilde\n 0x7f : 0x2588, // Full block\n // THIS BLOCK INCLUDES THE 16 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS\n // THAT COME FROM HI BYTE=0x11 AND LOW BETWEEN 0x30 AND 0x3F\n // THIS MEANS THAT \\x50 MUST BE ADDED TO THE VALUES\n 0x80 : 0xae, // Registered symbol (R)\n 0x81 : 0xb0, // degree sign\n 0x82 : 0xbd, // 1/2 symbol\n 0x83 : 0xbf, // Inverted (open) question mark\n 0x84 : 0x2122, // Trademark symbol (TM)\n 0x85 : 0xa2, // Cents symbol\n 0x86 : 0xa3, // Pounds sterling\n 0x87 : 0x266a, // Music 8'th note\n 0x88 : 0xe0, // lowercase a, grave accent\n 0x89 : 0x20, // transparent space (regular)\n 0x8a : 0xe8, // lowercase e, grave accent\n 0x8b : 0xe2, // lowercase a, circumflex accent\n 0x8c : 0xea, // lowercase e, circumflex accent\n 0x8d : 0xee, // lowercase i, circumflex accent\n 0x8e : 0xf4, // lowercase o, circumflex accent\n 0x8f : 0xfb, // lowercase u, circumflex accent\n // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS\n // THAT COME FROM HI BYTE=0x12 AND LOW BETWEEN 0x20 AND 0x3F\n 0x90 : 0xc1, // capital letter A with acute\n 0x91 : 0xc9, // capital letter E with acute\n 0x92 : 0xd3, // capital letter O with acute\n 0x93 : 0xda, // capital letter U with acute\n 0x94 : 0xdc, // capital letter U with diaresis\n 0x95 : 0xfc, // lowercase letter U with diaeresis\n 0x96 : 0x2018, // opening single quote\n 0x97 : 0xa1, // inverted exclamation mark\n 0x98 : 0x2a, // asterisk\n 0x99 : 0x2019, // closing single quote\n 0x9a : 0x2501, // box drawings heavy horizontal\n 0x9b : 0xa9, // copyright sign\n 0x9c : 0x2120, // Service mark\n 0x9d : 0x2022, // (round) bullet\n 0x9e : 0x201c, // Left double quotation mark\n 0x9f : 0x201d, // Right double quotation mark\n 0xa0 : 0xc0, // uppercase A, grave accent\n 0xa1 : 0xc2, // uppercase A, circumflex\n 0xa2 : 0xc7, // uppercase C with cedilla\n 0xa3 : 0xc8, // uppercase E, grave accent\n 0xa4 : 0xca, // uppercase E, circumflex\n 0xa5 : 0xcb, // capital letter E with diaresis\n 0xa6 : 0xeb, // lowercase letter e with diaresis\n 0xa7 : 0xce, // uppercase I, circumflex\n 0xa8 : 0xcf, // uppercase I, with diaresis\n 0xa9 : 0xef, // lowercase i, with diaresis\n 0xaa : 0xd4, // uppercase O, circumflex\n 0xab : 0xd9, // uppercase U, grave accent\n 0xac : 0xf9, // lowercase u, grave accent\n 0xad : 0xdb, // uppercase U, circumflex\n 0xae : 0xab, // left-pointing double angle quotation mark\n 0xaf : 0xbb, // right-pointing double angle quotation mark\n // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS\n // THAT COME FROM HI BYTE=0x13 AND LOW BETWEEN 0x20 AND 0x3F\n 0xb0 : 0xc3, // Uppercase A, tilde\n 0xb1 : 0xe3, // Lowercase a, tilde\n 0xb2 : 0xcd, // Uppercase I, acute accent\n 0xb3 : 0xcc, // Uppercase I, grave accent\n 0xb4 : 0xec, // Lowercase i, grave accent\n 0xb5 : 0xd2, // Uppercase O, grave accent\n 0xb6 : 0xf2, // Lowercase o, grave accent\n 0xb7 : 0xd5, // Uppercase O, tilde\n 0xb8 : 0xf5, // Lowercase o, tilde\n 0xb9 : 0x7b, // Open curly brace\n 0xba : 0x7d, // Closing curly brace\n 0xbb : 0x5c, // Backslash\n 0xbc : 0x5e, // Caret\n 0xbd : 0x5f, // Underscore\n 0xbe : 0x7c, // Pipe (vertical line)\n 0xbf : 0x223c, // Tilde operator\n 0xc0 : 0xc4, // Uppercase A, umlaut\n 0xc1 : 0xe4, // Lowercase A, umlaut\n 0xc2 : 0xd6, // Uppercase O, umlaut\n 0xc3 : 0xf6, // Lowercase o, umlaut\n 0xc4 : 0xdf, // Esszett (sharp S)\n 0xc5 : 0xa5, // Yen symbol\n 0xc6 : 0xa4, // Generic currency sign\n 0xc7 : 0x2503, // Box drawings heavy vertical\n 0xc8 : 0xc5, // Uppercase A, ring\n 0xc9 : 0xe5, // Lowercase A, ring\n 0xca : 0xd8, // Uppercase O, stroke\n 0xcb : 0xf8, // Lowercase o, strok\n 0xcc : 0x250f, // Box drawings heavy down and right\n 0xcd : 0x2513, // Box drawings heavy down and left\n 0xce : 0x2517, // Box drawings heavy up and right\n 0xcf : 0x251b // Box drawings heavy up and left\n};\n\n/**\n * Utils\n */\nvar getCharForByte = function(byte) {\n var charCode = byte;\n if (specialCea608CharsCodes.hasOwnProperty(byte)) {\n charCode = specialCea608CharsCodes[byte];\n }\n return String.fromCharCode(charCode);\n};\n\nvar NR_ROWS = 15,\n NR_COLS = 32;\n// Tables to look up row from PAC data\nvar rowsLowCh1 = {0x11 : 1, 0x12 : 3, 0x15 : 5, 0x16 : 7, 0x17 : 9, 0x10 : 11, 0x13 : 12, 0x14 : 14};\nvar rowsHighCh1 = {0x11 : 2, 0x12 : 4, 0x15 : 6, 0x16 : 8, 0x17 : 10, 0x13 : 13, 0x14 : 15};\nvar rowsLowCh2 = {0x19 : 1, 0x1A : 3, 0x1D : 5, 0x1E : 7, 0x1F : 9, 0x18 : 11, 0x1B : 12, 0x1C : 14};\nvar rowsHighCh2 = {0x19 : 2, 0x1A : 4, 0x1D : 6, 0x1E : 8, 0x1F : 10, 0x1B : 13, 0x1C : 15};\n\nvar backgroundColors = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta', 'black', 'transparent'];\n\n/**\n * Simple logger class to be able to write with time-stamps and filter on level.\n */\nvar logger = {\n verboseFilter : {'DATA' : 3, 'DEBUG' : 3, 'INFO' : 2, 'WARNING' : 2, 'TEXT' : 1, 'ERROR' : 0},\n time : null,\n verboseLevel : 0, // Only write errors\n setTime : function(newTime) {\n this.time = newTime;\n },\n log : function(severity, msg) {\n var minLevel = this.verboseFilter[severity];\n if (this.verboseLevel >= minLevel) {\n console.log(this.time + ' [' + severity + '] ' + msg);\n }\n }\n};\n\nvar numArrayToHexArray = function(numArray) {\n var hexArray = [];\n for (var j = 0; j < numArray.length; j++) {\n hexArray.push(numArray[j].toString(16));\n }\n return hexArray;\n};\n\nclass PenState {\n\n constructor(foreground, underline, italics, background, flash) {\n this.foreground = foreground || 'white';\n this.underline = underline || false;\n this.italics = italics || false;\n this.background = background || 'black';\n this.flash = flash || false;\n }\n\n reset() {\n this.foreground = 'white';\n this.underline = false;\n this.italics = false;\n this.background = 'black';\n this.flash = false;\n }\n\n setStyles(styles) {\n var attribs = ['foreground', 'underline', 'italics', 'background', 'flash'];\n for (var i = 0 ; i < attribs.length; i++) {\n var style = attribs[i];\n if (styles.hasOwnProperty(style)) {\n this[style] = styles[style];\n }\n }\n }\n\n isDefault() {\n return (this.foreground === 'white' && !this.underline && !this.italics &&\n this.background === 'black' && !this.flash);\n }\n\n equals(other) {\n return ( (this.foreground === other.foreground) &&\n (this.underline === other.underline) &&\n (this.italics === other.italics) &&\n (this.background === other.background) &&\n (this.flash === other.flash) );\n }\n\n copy(newPenState) {\n this.foreground = newPenState.foreground;\n this.underline = newPenState.underline;\n this.italics = newPenState.italics;\n this.background = newPenState.background;\n this.flash = newPenState.flash;\n }\n\n toString() {\n return ('color=' + this.foreground + ', underline=' + this.underline + ', italics=' + this.italics +\n ', background=' + this.background + ', flash=' + this.flash);\n }\n}\n\n/**\n * Unicode character with styling and background.\n * @constructor\n */\nclass StyledUnicodeChar\n{\n\n constructor(uchar, foreground, underline, italics, background, flash) {\n this.uchar = uchar || ' '; // unicode character\n this.penState = new PenState(foreground, underline,italics, background, flash);\n }\n\n reset() {\n this.uchar = ' ';\n this.penState.reset();\n }\n\n setChar(uchar, newPenState) {\n this.uchar = uchar;\n this.penState.copy(newPenState);\n }\n\n setPenState(newPenState) {\n this.penState.copy(newPenState);\n }\n\n equals(other) {\n return this.uchar === other.uchar && this.penState.equals(other.penState);\n }\n\n copy(newChar) {\n this.uchar = newChar.uchar;\n this.penState.copy(newChar.penState);\n }\n\n isEmpty() {\n return this.uchar === ' ' && this.penState.isDefault();\n }\n}\n\n/**\n * CEA-608 row consisting of NR_COLS instances of StyledUnicodeChar.\n * @constructor\n */\nclass Row {\n constructor() {\n this.chars = [];\n for (var i = 0 ; i < NR_COLS ; i++) {\n this.chars.push(new StyledUnicodeChar());\n }\n this.pos = 0;\n this.currPenState = new PenState();\n }\n\n equals(other) {\n var equal = true;\n for (var i = 0 ; i < NR_COLS; i ++) {\n if (!this.chars[i].equals(other.chars[i])) {\n equal = false;\n break;\n }\n }\n return equal;\n }\n\n copy(other) {\n for (var i = 0 ; i < NR_COLS; i ++) {\n this.chars[i].copy(other.chars[i]);\n }\n }\n\n isEmpty() {\n var empty = true;\n for (var i = 0 ; i < NR_COLS; i ++) {\n if (!this.chars[i].isEmpty()) {\n empty = false;\n break;\n }\n }\n return empty;\n }\n\n /**\n * Set the cursor to a valid column.\n */\n setCursor(absPos) {\n if (this.pos !== absPos) {\n this.pos = absPos;\n }\n if (this.pos < 0) {\n logger.log('ERROR', 'Negative cursor position ' + this.pos);\n this.pos = 0;\n } else if (this.pos > NR_COLS) {\n logger.log('ERROR', 'Too large cursor position ' + this.pos);\n this.pos = NR_COLS;\n }\n }\n\n /**\n * Move the cursor relative to current position.\n */\n moveCursor(relPos) {\n var newPos = this.pos + relPos;\n if (relPos > 1) {\n for (var i = this.pos+1; i < newPos+1 ; i++) {\n this.chars[i].setPenState(this.currPenState);\n }\n }\n this.setCursor(newPos);\n }\n\n /**\n * Backspace, move one step back and clear character.\n */\n backSpace() {\n this.moveCursor(-1);\n this.chars[this.pos].setChar(' ', this.currPenState);\n }\n\n insertChar(byte) {\n if (byte >= 0x90) { //Extended char\n this.backSpace();\n }\n var char = getCharForByte(byte);\n if (this.pos >= NR_COLS) {\n logger.log('ERROR', 'Cannot insert ' + byte.toString(16) +\n ' (' + char + ') at position ' + this.pos + '. Skipping it!');\n return;\n }\n this.chars[this.pos].setChar(char, this.currPenState);\n this.moveCursor(1);\n }\n\n clearFromPos(startPos) {\n var i;\n for (i = startPos ; i < NR_COLS ; i++) {\n this.chars[i].reset();\n }\n }\n\n clear() {\n this.clearFromPos(0);\n this.pos = 0;\n this.currPenState.reset();\n }\n\n clearToEndOfRow() {\n this.clearFromPos(this.pos);\n }\n\n getTextString() {\n var chars = [];\n var empty = true;\n for (var i = 0 ; i < NR_COLS ; i++) {\n var char = this.chars[i].uchar;\n if (char !== ' ') {\n empty = false;\n }\n chars.push(char);\n }\n if (empty) {\n return '';\n } else {\n return chars.join('');\n }\n }\n\n setPenStyles(styles) {\n this.currPenState.setStyles(styles);\n var currChar = this.chars[this.pos];\n currChar.setPenState(this.currPenState);\n }\n}\n\n/**\n * Keep a CEA-608 screen of 32x15 styled characters\n * @constructor\n*/\nclass CaptionScreen {\n\n constructor() {\n this.rows = [];\n for (var i = 0 ; i < NR_ROWS; i++) {\n this.rows.push(new Row()); // Note that we use zero-based numbering (0-14)\n }\n this.currRow = NR_ROWS - 1;\n this.nrRollUpRows = null;\n this.reset();\n }\n\n reset() {\n for (var i = 0 ; i < NR_ROWS ; i++) {\n this.rows[i].clear();\n }\n this.currRow = NR_ROWS - 1;\n }\n\n equals(other) {\n var equal = true;\n for (var i = 0 ; i < NR_ROWS ; i++) {\n if (!this.rows[i].equals(other.rows[i])) {\n equal = false;\n break;\n }\n }\n return equal;\n }\n\n copy(other) {\n for (var i = 0 ; i < NR_ROWS ; i++) {\n this.rows[i].copy(other.rows[i]);\n }\n }\n\n isEmpty() {\n var empty = true;\n for (var i = 0 ; i < NR_ROWS ; i++) {\n if (!this.rows[i].isEmpty()) {\n empty = false;\n break;\n }\n }\n return empty;\n }\n\n backSpace() {\n var row = this.rows[this.currRow];\n row.backSpace();\n }\n\n clearToEndOfRow() {\n var row = this.rows[this.currRow];\n row.clearToEndOfRow();\n }\n\n /**\n * Insert a character (without styling) in the current row.\n */\n insertChar(char) {\n var row = this.rows[this.currRow];\n row.insertChar(char);\n }\n\n setPen(styles) {\n var row = this.rows[this.currRow];\n row.setPenStyles(styles);\n }\n\n moveCursor(relPos) {\n var row = this.rows[this.currRow];\n row.moveCursor(relPos);\n }\n\n setCursor(absPos) {\n logger.log('INFO', 'setCursor: ' + absPos);\n var row = this.rows[this.currRow];\n row.setCursor(absPos);\n }\n\n setPAC(pacData, lastOutputScreen) {\n logger.log('INFO', 'pacData = ' + JSON.stringify(pacData));\n var newRow = pacData.row - 1;\n if (this.nrRollUpRows && newRow < this.nrRollUpRows - 1) {\n newRow = this.nrRollUpRows-1;\n }\n\n //Make sure this only affects Roll-up Captions by checking this.nrRollUpRows\n if (this.nrRollUpRows && this.currRow !== newRow) {\n //clear all rows first\n for (var i = 0; i < NR_ROWS; i++) {\n this.rows[i].clear();\n }\n\n //Copy this.nrRollUpRows rows from lastOutputScreen and place it in the newRow location\n //topRowIndex - the start of rows to copy (inclusive index)\n var topRowIndex = this.currRow + 1 - (this.nrRollUpRows);\n //We only copy if the last position was already shown.\n //We use the cueStartTime value to check this.\n var prevLineTime = lastOutputScreen.rows[topRowIndex].cueStartTime;\n if(prevLineTime && prevLineTime < logger.time) {\n for (i = 0; i < this.nrRollUpRows; i++) {\n this.rows[newRow-this.nrRollUpRows+i+1].copy(lastOutputScreen.rows[topRowIndex+i]);\n }\n }\n }\n\n this.currRow = newRow;\n var row = this.rows[this.currRow];\n if (pacData.indent !== null) {\n var indent = pacData.indent;\n var prevPos = Math.max(indent-1, 0);\n row.setCursor(pacData.indent);\n pacData.color = row.chars[prevPos].penState.foreground;\n }\n var styles = {foreground : pacData.color, underline : pacData.underline, italics : pacData.italics, background : 'black', flash : false};\n this.setPen(styles);\n }\n\n /**\n * Set background/extra foreground, but first do back_space, and then insert space (backwards compatibility).\n */\n setBkgData(bkgData) {\n\n logger.log('INFO', 'bkgData = ' + JSON.stringify(bkgData));\n this.backSpace();\n this.setPen(bkgData);\n this.insertChar(0x20); //Space\n }\n\n setRollUpRows(nrRows) {\n this.nrRollUpRows = nrRows;\n }\n\n rollUp() {\n if (this.nrRollUpRows === null) {\n logger.log('DEBUG', 'roll_up but nrRollUpRows not set yet');\n return; //Not properly setup\n }\n logger.log('TEXT', this.getDisplayText());\n var topRowIndex = this.currRow + 1 - this.nrRollUpRows;\n var topRow = this.rows.splice(topRowIndex, 1)[0];\n topRow.clear();\n this.rows.splice(this.currRow, 0, topRow);\n logger.log('INFO', 'Rolling up');\n //logger.log('TEXT', this.get_display_text())\n }\n\n /**\n * Get all non-empty rows with as unicode text.\n */\n getDisplayText(asOneRow) {\n asOneRow = asOneRow || false;\n var displayText = [];\n var text = '';\n var rowNr = -1;\n for (var i = 0 ; i < NR_ROWS ; i++) {\n var rowText = this.rows[i].getTextString();\n if (rowText) {\n rowNr = i+1;\n if (asOneRow) {\n displayText.push('Row ' + rowNr + ': \\'' + rowText + '\\'');\n } else {\n displayText.push(rowText.trim());\n }\n }\n }\n if (displayText.length > 0) {\n if (asOneRow) {\n text = '[' + displayText.join(' | ') + ']';\n } else {\n text = displayText.join('\\n');\n }\n }\n return text;\n }\n\n getTextAndFormat() {\n return this.rows;\n }\n}\n\n//var modes = ['MODE_ROLL-UP', 'MODE_POP-ON', 'MODE_PAINT-ON', 'MODE_TEXT'];\n\nclass Cea608Channel\n{\n constructor(channelNumber, outputFilter) {\n\n this.chNr = channelNumber;\n this.outputFilter = outputFilter;\n this.mode = null;\n this.verbose = 0;\n this.displayedMemory = new CaptionScreen();\n this.nonDisplayedMemory = new CaptionScreen();\n this.lastOutputScreen = new CaptionScreen();\n this.currRollUpRow = this.displayedMemory.rows[NR_ROWS-1];\n this.writeScreen = this.displayedMemory;\n this.mode = null;\n this.cueStartTime = null; // Keeps track of where a cue started.\n }\n\n reset() {\n this.mode = null;\n this.displayedMemory.reset();\n this.nonDisplayedMemory.reset();\n this.lastOutputScreen.reset();\n this.currRollUpRow = this.displayedMemory.rows[NR_ROWS-1];\n this.writeScreen = this.displayedMemory;\n this.mode = null;\n this.cueStartTime = null;\n this.lastCueEndTime = null;\n }\n\n getHandler() {\n return this.outputFilter;\n }\n\n setHandler(newHandler) {\n this.outputFilter = newHandler;\n }\n\n setPAC(pacData) {\n this.writeScreen.setPAC(pacData, this.lastOutputScreen);\n }\n\n setBkgData(bkgData) {\n this.writeScreen.setBkgData(bkgData);\n }\n\n setMode(newMode) {\n if (newMode === this.mode) {\n return;\n }\n this.mode = newMode;\n logger.log('INFO', 'MODE=' + newMode);\n if (this.mode === 'MODE_POP-ON') {\n this.writeScreen = this.nonDisplayedMemory;\n } else {\n this.writeScreen = this.displayedMemory;\n this.writeScreen.reset();\n this.lastOutputScreen.reset();\n }\n if (this.mode !== 'MODE_ROLL-UP') {\n this.displayedMemory.nrRollUpRows = null;\n this.nonDisplayedMemory.nrRollUpRows = null;\n }\n this.mode = newMode;\n }\n\n insertChars(chars) {\n for (var i = 0 ; i < chars.length ; i++) {\n this.writeScreen.insertChar(chars[i]);\n }\n var screen = this.writeScreen === this.displayedMemory ? 'DISP' : 'NON_DISP';\n logger.log('INFO', screen + ': ' + this.writeScreen.getDisplayText(true));\n if (this.mode === 'MODE_PAINT-ON' || this.mode === 'MODE_ROLL-UP') {\n logger.log('TEXT', 'DISPLAYED: ' + this.displayedMemory.getDisplayText(true));\n this.outputDataUpdate();\n }\n }\n\n ccRCL() { // Resume Caption Loading (switch mode to Pop On)\n logger.log('INFO', 'RCL - Resume Caption Loading');\n this.setMode('MODE_POP-ON');\n }\n\n ccBS() { // BackSpace\n logger.log('INFO', 'BS - BackSpace');\n if (this.mode === 'MODE_TEXT') {\n return;\n }\n this.writeScreen.backSpace();\n if (this.writeScreen === this.displayedMemory) {\n this.outputDataUpdate();\n }\n }\n\n ccAOF() { // Reserved (formerly Alarm Off)\n return;\n }\n\n ccAON() { // Reserved (formerly Alarm On)\n return;\n }\n\n ccDER() { // Delete to End of Row\n logger.log('INFO', 'DER- Delete to End of Row');\n this.writeScreen.clearToEndOfRow();\n this.outputDataUpdate();\n }\n\n ccRU(nrRows) { //Roll-Up Captions-2,3,or 4 Rows\n logger.log('INFO', 'RU(' + nrRows +') - Roll Up');\n this.writeScreen = this.displayedMemory;\n this.setMode('MODE_ROLL-UP');\n this.writeScreen.setRollUpRows(nrRows);\n }\n\n ccFON() { //Flash On\n logger.log('INFO', 'FON - Flash On');\n this.writeScreen.setPen({flash : true});\n }\n\n ccRDC() { // Resume Direct Captioning (switch mode to PaintOn)\n logger.log('INFO', 'RDC - Resume Direct Captioning');\n this.setMode('MODE_PAINT-ON');\n }\n\n ccTR() { // Text Restart in text mode (not supported, however)\n logger.log('INFO', 'TR');\n this.setMode('MODE_TEXT');\n }\n\n ccRTD() { // Resume Text Display in Text mode (not supported, however)\n logger.log('INFO', 'RTD');\n this.setMode('MODE_TEXT');\n }\n\n ccEDM() { // Erase Displayed Memory\n logger.log('INFO', 'EDM - Erase Displayed Memory');\n this.displayedMemory.reset();\n this.outputDataUpdate();\n }\n\n ccCR() { // Carriage Return\n logger.log('CR - Carriage Return');\n this.writeScreen.rollUp();\n this.outputDataUpdate();\n }\n\n ccENM() { //Erase Non-Displayed Memory\n logger.log('INFO', 'ENM - Erase Non-displayed Memory');\n this.nonDisplayedMemory.reset();\n }\n\n ccEOC() { //End of Caption (Flip Memories)\n logger.log('INFO', 'EOC - End Of Caption');\n if (this.mode === 'MODE_POP-ON') {\n var tmp = this.displayedMemory;\n this.displayedMemory = this.nonDisplayedMemory;\n this.nonDisplayedMemory = tmp;\n this.writeScreen = this.nonDisplayedMemory;\n logger.log('TEXT', 'DISP: ' + this.displayedMemory.getDisplayText());\n }\n this.outputDataUpdate();\n }\n\n ccTO(nrCols) { // Tab Offset 1,2, or 3 columns\n logger.log('INFO', 'TO(' + nrCols + ') - Tab Offset');\n this.writeScreen.moveCursor(nrCols);\n }\n\n ccMIDROW(secondByte) { // Parse MIDROW command\n var styles = {flash : false};\n styles.underline = secondByte % 2 === 1;\n styles.italics = secondByte >= 0x2e;\n if (!styles.italics) {\n var colorIndex = Math.floor(secondByte/2) - 0x10;\n var colors = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta'];\n styles.foreground = colors[colorIndex];\n } else {\n styles.foreground = 'white';\n }\n logger.log('INFO', 'MIDROW: ' + JSON.stringify(styles));\n this.writeScreen.setPen(styles);\n }\n\n outputDataUpdate() {\n var t = logger.time;\n if (t === null) {\n return;\n }\n if (this.outputFilter) {\n if (this.outputFilter.updateData) {\n this.outputFilter.updateData(t, this.displayedMemory);\n }\n if (this.cueStartTime === null && !this.displayedMemory.isEmpty()) { // Start of a new cue\n this.cueStartTime = t;\n } else {\n if (!this.displayedMemory.equals(this.lastOutputScreen)) {\n if (this.outputFilter.newCue) {\n this.outputFilter.newCue(this.cueStartTime, t, this.lastOutputScreen);\n }\n this.cueStartTime = this.displayedMemory.isEmpty() ? null : t;\n }\n }\n this.lastOutputScreen.copy(this.displayedMemory);\n }\n }\n\n cueSplitAtTime(t) {\n if (this.outputFilter) {\n if (!this.displayedMemory.isEmpty()) {\n if (this.outputFilter.newCue) {\n this.outputFilter.newCue(this.cueStartTime, t, this.displayedMemory);\n }\n this.cueStartTime = t;\n }\n }\n }\n}\n\nclass Cea608Parser {\n\n constructor(field, out1, out2) {\n this.field = field || 1;\n this.outputs = [out1, out2];\n this.channels = [new Cea608Channel(1, out1), new Cea608Channel(2, out2)];\n this.currChNr = -1; // Will be 1 or 2\n this.lastCmdA = null; // First byte of last command\n this.lastCmdB = null; // Second byte of last command\n this.bufferedData = [];\n this.startTime = null;\n this.lastTime = null;\n this.dataCounters = {'padding' : 0, 'char' : 0, 'cmd' : 0, 'other' : 0};\n }\n\n getHandler(index) {\n return this.channels[index].getHandler();\n }\n\n setHandler(index, newHandler) {\n this.channels[index].setHandler(newHandler);\n }\n\n /**\n * Add data for time t in forms of list of bytes (unsigned ints). The bytes are treated as pairs.\n */\n addData(t, byteList) {\n var cmdFound, a, b,\n charsFound = false;\n\n this.lastTime = t;\n logger.setTime(t);\n\n for (var i = 0 ; i < byteList.length ; i+=2) {\n a = byteList[i] & 0x7f;\n b = byteList[i+1] & 0x7f;\n if (a === 0 && b === 0) {\n this.dataCounters.padding += 2;\n continue;\n } else {\n logger.log('DATA', '[' + numArrayToHexArray([byteList[i], byteList[i+1]]) +'] -> (' + numArrayToHexArray([a, b]) + ')');\n }\n cmdFound = this.parseCmd(a, b);\n if (!cmdFound) {\n cmdFound = this.parseMidrow(a, b);\n }\n if (!cmdFound) {\n cmdFound = this.parsePAC(a, b);\n }\n if (!cmdFound) {\n cmdFound = this.parseBackgroundAttributes(a, b);\n }\n if (!cmdFound) {\n charsFound = this.parseChars(a, b);\n if (charsFound) {\n if (this.currChNr && this.currChNr >=0) {\n var channel = this.channels[this.currChNr-1];\n channel.insertChars(charsFound);\n } else {\n logger.log('WARNING', 'No channel found yet. TEXT-MODE?');\n }\n }\n }\n if (cmdFound) {\n this.dataCounters.cmd += 2;\n } else if (charsFound) {\n this.dataCounters.char += 2;\n } else {\n this.dataCounters.other += 2;\n logger.log('WARNING', 'Couldn\\'t parse cleaned data ' + numArrayToHexArray([a, b]) +\n ' orig: ' + numArrayToHexArray([byteList[i], byteList[i+1]]));\n }\n }\n }\n\n /**\n * Parse Command.\n * @returns {Boolean} Tells if a command was found\n */\n parseCmd(a, b) {\n var chNr = null;\n\n var cond1 = (a === 0x14 || a === 0x1C) && (0x20 <= b && b <= 0x2F);\n var cond2 = (a === 0x17 || a === 0x1F) && (0x21 <= b && b <= 0x23);\n if (!(cond1 || cond2)) {\n return false;\n }\n\n if (a === this.lastCmdA && b === this.lastCmdB) {\n this.lastCmdA = null;\n this.lastCmdB = null; // Repeated commands are dropped (once)\n logger.log('DEBUG', 'Repeated command (' + numArrayToHexArray([a, b]) + ') is dropped');\n return true;\n }\n\n if (a === 0x14 || a === 0x17) {\n chNr = 1;\n } else {\n chNr = 2; // (a === 0x1C || a=== 0x1f)\n }\n\n var channel = this.channels[chNr - 1];\n\n if (a === 0x14 || a === 0x1C) {\n if (b === 0x20) {\n channel.ccRCL();\n } else if (b === 0x21) {\n channel.ccBS();\n } else if (b === 0x22) {\n channel.ccAOF();\n } else if (b === 0x23) {\n channel.ccAON();\n } else if (b === 0x24) {\n channel.ccDER();\n } else if (b === 0x25) {\n channel.ccRU(2);\n } else if (b === 0x26) {\n channel.ccRU(3);\n } else if (b === 0x27) {\n channel.ccRU(4);\n } else if (b === 0x28) {\n channel.ccFON();\n } else if (b === 0x29) {\n channel.ccRDC();\n } else if (b === 0x2A) {\n channel.ccTR();\n } else if (b === 0x2B) {\n channel.ccRTD();\n } else if (b === 0x2C) {\n channel.ccEDM();\n } else if (b === 0x2D) {\n channel.ccCR();\n } else if (b === 0x2E) {\n channel.ccENM();\n } else if (b === 0x2F) {\n channel.ccEOC();\n }\n } else { //a == 0x17 || a == 0x1F\n channel.ccTO(b - 0x20);\n }\n this.lastCmdA = a;\n this.lastCmdB = b;\n this.currChNr = chNr;\n return true;\n }\n\n /**\n * Parse midrow styling command\n * @returns {Boolean}\n */\n parseMidrow(a, b) {\n var chNr = null;\n\n if ( ((a === 0x11) || (a === 0x19)) && 0x20 <= b && b <= 0x2f) {\n if (a === 0x11) {\n chNr = 1;\n } else {\n chNr = 2;\n }\n if (chNr !== this.currChNr) {\n logger.log('ERROR', 'Mismatch channel in midrow parsing');\n return false;\n }\n var channel = this.channels[chNr-1];\n channel.ccMIDROW(b);\n logger.log('DEBUG', 'MIDROW (' + numArrayToHexArray([a, b]) + ')');\n return true;\n }\n return false;\n }\n /**\n * Parse Preable Access Codes (Table 53).\n * @returns {Boolean} Tells if PAC found\n */\n parsePAC(a, b) {\n\n var chNr = null;\n var row = null;\n\n var case1 = ((0x11 <= a && a <= 0x17) || (0x19 <= a && a <= 0x1F)) && (0x40 <= b && b <= 0x7F);\n var case2 = (a === 0x10 || a === 0x18) && (0x40 <= b && b <= 0x5F);\n if (! (case1 || case2)) {\n return false;\n }\n\n if (a === this.lastCmdA && b === this.lastCmdB) {\n this.lastCmdA = null;\n this.lastCmdB = null;\n return true; // Repeated commands are dropped (once)\n }\n\n chNr = (a <= 0x17) ? 1 : 2;\n\n if (0x40 <= b && b <= 0x5F) {\n row = (chNr === 1) ? rowsLowCh1[a] : rowsLowCh2[a];\n } else { // 0x60 <= b <= 0x7F\n row = (chNr === 1) ? rowsHighCh1[a] : rowsHighCh2[a];\n }\n var pacData = this.interpretPAC(row, b);\n var channel = this.channels[chNr-1];\n channel.setPAC(pacData);\n this.lastCmdA = a;\n this.lastCmdB = b;\n this.currChNr = chNr;\n return true;\n }\n\n /**\n * Interpret the second byte of the pac, and return the information.\n * @returns {Object} pacData with style parameters.\n */\n interpretPAC(row, byte) {\n var pacIndex = byte;\n var pacData = {color : null, italics : false, indent : null, underline : false, row : row};\n\n if (byte > 0x5F) {\n pacIndex = byte - 0x60;\n } else {\n pacIndex = byte - 0x40;\n }\n pacData.underline = (pacIndex & 1) === 1;\n if (pacIndex <= 0xd) {\n pacData.color = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta', 'white'][Math.floor(pacIndex/2)];\n } else if (pacIndex <= 0xf) {\n pacData.italics = true;\n pacData.color = 'white';\n } else {\n pacData.indent = (Math.floor((pacIndex-0x10)/2))*4;\n }\n return pacData; // Note that row has zero offset. The spec uses 1.\n }\n\n /**\n * Parse characters.\n * @returns An array with 1 to 2 codes corresponding to chars, if found. null otherwise.\n */\n parseChars(a, b) {\n\n var channelNr = null,\n charCodes = null,\n charCode1 = null;\n\n if (a >= 0x19) {\n channelNr = 2;\n charCode1 = a - 8;\n } else {\n channelNr = 1;\n charCode1 = a;\n }\n if (0x11 <= charCode1 && charCode1 <= 0x13) {\n // Special character\n var oneCode = b;\n if (charCode1 === 0x11) {\n oneCode = b + 0x50;\n } else if (charCode1 === 0x12) {\n oneCode = b + 0x70;\n } else {\n oneCode = b + 0x90;\n }\n logger.log('INFO', 'Special char \\'' + getCharForByte(oneCode) + '\\' in channel ' + channelNr);\n charCodes = [oneCode];\n } else if (0x20 <= a && a <= 0x7f) {\n charCodes = (b === 0) ? [a] : [a, b];\n }\n if (charCodes) {\n var hexCodes = numArrayToHexArray(charCodes);\n logger.log('DEBUG', 'Char codes = ' + hexCodes.join(','));\n this.lastCmdA = null;\n this.lastCmdB = null;\n }\n return charCodes;\n }\n\n /**\n * Parse extended background attributes as well as new foreground color black.\n * @returns{Boolean} Tells if background attributes are found\n */\n parseBackgroundAttributes(a, b) {\n var bkgData,\n index,\n chNr,\n channel;\n\n var case1 = (a === 0x10 || a === 0x18) && (0x20 <= b && b <= 0x2f);\n var case2 = (a === 0x17 || a === 0x1f) && (0x2d <=b && b <= 0x2f);\n if (!(case1 || case2)) {\n return false;\n }\n bkgData = {};\n if (a === 0x10 || a === 0x18) {\n index = Math.floor((b-0x20)/2);\n bkgData.background = backgroundColors[index];\n if (b % 2 === 1) {\n bkgData.background = bkgData.background + '_semi';\n }\n } else if (b === 0x2d) {\n bkgData.background = 'transparent';\n } else {\n bkgData.foreground = 'black';\n if (b === 0x2f) {\n bkgData.underline = true;\n }\n }\n chNr = (a < 0x18) ? 1 : 2;\n channel = this.channels[chNr-1];\n channel.setBkgData(bkgData);\n this.lastCmdA = null;\n this.lastCmdB = null;\n return true;\n }\n\n /**\n * Reset state of parser and its channels.\n */\n reset() {\n for (var i=0 ; i < this.channels.length ; i++) {\n if (this.channels[i]) {\n this.channels[i].reset();\n }\n }\n this.lastCmdA = null;\n this.lastCmdB = null;\n }\n\n /**\n * Trigger the generation of a cue, and the start of a new one if displayScreens are not empty.\n */\n cueSplitAtTime(t) {\n for (var i=0 ; i < this.channels.length ; i++) {\n if (this.channels[i]) {\n this.channels[i].cueSplitAtTime(t);\n }\n }\n }\n}\n\nexport default Cea608Parser;\n",
"var Cues = {\n\n newCue: function(track, startTime, endTime, captionScreen) {\n var row;\n var cue;\n var indenting;\n var indent;\n var text;\n var VTTCue = window.VTTCue || window.TextTrackCue;\n\n for (var r=0; r<captionScreen.rows.length; r++)\n {\n row = captionScreen.rows[r];\n indenting = true;\n indent = 0;\n text = '';\n\n if (!row.isEmpty())\n {\n for (var c=0; c<row.chars.length; c++)\n {\n if (row.chars[c].uchar.match(/\\s/) && indenting)\n {\n indent++;\n }\n else\n {\n text += row.chars[c].uchar;\n indenting = false;\n }\n }\n //To be used for cleaning-up orphaned roll-up captions\n row.cueStartTime = startTime;\n cue = new VTTCue(startTime, endTime, text.trim());\n\n if (indent >= 16)\n {\n indent--;\n }\n else\n {\n indent++;\n }\n\n // VTTCue.line get's flakey when using controls, so let's now include line 13&14\n // also, drop line 1 since it's to close to the top\n if (navigator.userAgent.match(/Firefox\\//))\n {\n cue.line = r + 1;\n }\n else\n {\n cue.line = (r > 7 ? r - 2 : r + 1);\n }\n cue.align = 'left';\n // Clamp the position between 0 and 100 - if out of these bounds, Firefox throws an exception and captions break\n cue.position = Math.max(0, Math.min(100, 100 * (indent / 32) + (navigator.userAgent.match(/Firefox\\//) ? 50 : 0)));\n track.addCue(cue);\n }\n }\n }\n\n};\n\nmodule.exports = Cues;\n",
"/*\n * compute an Exponential Weighted moving average\n * - https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average\n * - heavily inspired from shaka-player\n */\n\nclass EWMA {\n\n // About half of the estimated value will be from the last |halfLife| samples by weight.\n constructor(halfLife) {\n // Larger values of alpha expire historical data more slowly.\n this.alpha_ = halfLife ? Math.exp(Math.log(0.5) / halfLife) : 0;\n this.estimate_ = 0;\n this.totalWeight_ = 0;\n }\n\n sample(weight,value) {\n var adjAlpha = Math.pow(this.alpha_, weight);\n this.estimate_ = value * (1 - adjAlpha) + adjAlpha * this.estimate_;\n this.totalWeight_ += weight;\n }\n\n getTotalWeight() {\n return this.totalWeight_;\n }\n\n getEstimate() {\n if (this.alpha_) {\n var zeroFactor = 1 - Math.pow(this.alpha_, this.totalWeight_);\n return this.estimate_ / zeroFactor;\n } else {\n return this.estimate_;\n }\n }\n}\n\nexport default EWMA;\n",
"'use strict';\n\nfunction noop() {}\n\nconst fakeLogger = {\n trace: noop,\n debug: noop,\n log: noop,\n warn: noop,\n info: noop,\n error: noop\n};\n\nlet exportedLogger = fakeLogger;\n\n/*globals self: false */\n\n//let lastCallTime;\n// function formatMsgWithTimeInfo(type, msg) {\n// const now = Date.now();\n// const diff = lastCallTime ? '+' + (now - lastCallTime) : '0';\n// lastCallTime = now;\n// msg = (new Date(now)).toISOString() + ' | [' + type + '] > ' + msg + ' ( ' + diff + ' ms )';\n// return msg;\n// }\n\nfunction formatMsg(type, msg) {\n msg = '[' + type + '] > ' + msg;\n return msg;\n}\n\nfunction consolePrintFn(type) {\n const func = self.console[type];\n if (func) {\n return function(...args) {\n if(args[0]) {\n args[0] = formatMsg(type, args[0]);\n }\n func.apply(self.console, args);\n };\n }\n return noop;\n}\n\nfunction exportLoggerFunctions(debugConfig, ...functions) {\n functions.forEach(function(type) {\n exportedLogger[type] = debugConfig[type] ? debugConfig[type].bind(debugConfig) : consolePrintFn(type);\n });\n}\n\nexport var enableLogs = function(debugConfig) {\n if (debugConfig === true || typeof debugConfig === 'object') {\n exportLoggerFunctions(debugConfig,\n // Remove out from list here to hard-disable a log-level\n //'trace',\n 'debug',\n 'log',\n 'info',\n 'warn',\n 'error'\n );\n // Some browsers don't allow to use bind on console object anyway\n // fallback to default if needed\n try {\n exportedLogger.log();\n } catch (e) {\n exportedLogger = fakeLogger;\n }\n }\n else {\n exportedLogger = fakeLogger;\n }\n};\n\nexport var logger = exportedLogger;\n",
"/**\n * TimeRanges to string helper\n */\n\nclass TimeRanges {\n static toString(r) {\n var log = '', len = r.length;\n for (var i=0; i<len; i++) {\n log += '[' + r.start(i).toFixed(3) + ',' + r.end(i).toFixed(3) + ']';\n }\n return log;\n }\n}\n\nexport default TimeRanges;\n",
"/**\n * XHR based logger\n*/\n\nimport {logger} from '../utils/logger';\n\nclass XhrLoader {\n\n constructor(config) {\n if (config && config.xhrSetup) {\n this.xhrSetup = config.xhrSetup;\n }\n }\n\n destroy() {\n this.abort();\n this.loader = null;\n }\n\n abort() {\n var loader = this.loader;\n if (loader && loader.readyState !== 4) {\n this.stats.aborted = true;\n loader.abort();\n }\n\n window.clearTimeout(this.requestTimeout);\n this.requestTimeout = null;\n window.clearTimeout(this.retryTimeout);\n this.retryTimeout = null;\n }\n\n load(context, config, callbacks) {\n this.context = context;\n this.config = config;\n this.callbacks = callbacks;\n this.stats = {trequest: performance.now(), retry: 0};\n this.retryDelay = config.retryDelay;\n this.loadInternal();\n }\n\n loadInternal() {\n var xhr, context = this.context;\n\n if (typeof XDomainRequest !== 'undefined') {\n xhr = this.loader = new XDomainRequest();\n } else {\n xhr = this.loader = new XMLHttpRequest();\n }\n\n xhr.onreadystatechange = this.readystatechange.bind(this);\n xhr.onprogress = this.loadprogress.bind(this);\n\n xhr.open('GET', context.url, true);\n\n if (context.rangeEnd) {\n xhr.setRequestHeader('Range','bytes=' + context.rangeStart + '-' + (context.rangeEnd-1));\n }\n xhr.responseType = context.responseType;\n let stats = this.stats;\n stats.tfirst = 0;\n stats.loaded = 0;\n if (this.xhrSetup) {\n this.xhrSetup(xhr, context.url);\n }\n // setup timeout before we perform request\n this.requestTimeout = window.setTimeout(this.loadtimeout.bind(this), this.config.timeout);\n xhr.send();\n }\n\n readystatechange(event) {\n var xhr = event.currentTarget,\n readyState = xhr.readyState,\n stats = this.stats,\n context = this.context,\n config = this.config;\n\n // don't proceed if xhr has been aborted\n if (stats.aborted) {\n return;\n }\n\n // in any case clear the current xhrs timeout\n window.clearTimeout(this.requestTimeout);\n\n // HEADERS_RECEIVED\n if (readyState >=2) {\n if (stats.tfirst === 0) {\n stats.tfirst = Math.max(performance.now(), stats.trequest);\n // reset timeout to total timeout duration minus the time it took to receive headers\n this.requestTimeout = window.setTimeout(this.loadtimeout.bind(this), config.timeout - (stats.tfirst-stats.trequest));\n }\n if (readyState === 4) {\n let status = xhr.status;\n // http status between 200 to 299 are all successful\n if (status >= 200 && status < 300) {\n stats.tload = Math.max(stats.tfirst,performance.now());\n let data,len;\n if (context.responseType === 'arraybuffer') {\n data = xhr.response;\n len = data.byteLength;\n } else {\n data = xhr.responseText;\n len = data.length;\n }\n stats.loaded = stats.total = len;\n let response = { url : xhr.responseURL, data : data };\n this.callbacks.onSuccess(response, stats, context);\n } else {\n // if max nb of retries reached or if http status between 400 and 499 (such error cannot be recovered, retrying is useless), return error\n if (stats.retry >= config.maxRetry || (status >= 400 && status < 499)) {\n logger.error(`${status} while loading ${context.url}` );\n this.callbacks.onError({ code : status, text : xhr.statusText}, context);\n } else {\n // retry\n logger.warn(`${status} while loading ${context.url}, retrying in ${this.retryDelay}...`);\n // aborts and resets internal state\n this.destroy();\n // schedule retry\n this.retryTimeout = window.setTimeout(this.loadInternal.bind(this), this.retryDelay);\n // set exponential backoff\n this.retryDelay = Math.min(2 * this.retryDelay, config.maxRetryDelay);\n stats.retry++;\n }\n }\n }\n }\n }\n\n loadtimeout() {\n logger.warn(`timeout while loading ${this.context.url}` );\n this.callbacks.onTimeout(this.stats, this.context);\n }\n\n loadprogress(event) {\n var stats = this.stats;\n stats.loaded = event.loaded;\n if (event.lengthComputable) {\n stats.total = event.total;\n }\n let onProgress = this.callbacks.onProgress;\n if (onProgress) {\n // last args is to provide on progress data\n onProgress(stats, this.context, null);\n }\n }\n}\n\nexport default XhrLoader;\n"
]
}