forked from video-dev/hls.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hls.js.map
131 lines (131 loc) · 837 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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
{
"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/config.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/fps-controller.js",
"src/controller/id3-track-controller.js",
"src/controller/level-controller.js",
"src/controller/stream-controller.js",
"src/controller/subtitle-stream-controller.js",
"src/controller/subtitle-track-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/mp3demuxer.js",
"src/demux/mp4demuxer.js",
"src/demux/mpegaudio.js",
"src/demux/sample-aes.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/discontinuities.js",
"src/utils/ewma-bandwidth-estimator.js",
"src/utils/ewma.js",
"src/utils/logger.js",
"src/utils/timeRanges.js",
"src/utils/vttcue.js",
"src/utils/vttparser.js",
"src/utils/webvtt-parser.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;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACnKA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjFA;;;AAGA;;;;;;;AAEA;;;;AACA;;;;AACA;;;;AACA;;;;AACA;;;;AAGA;;;;AACA;;;;AAIA;;;;AACA;;;;AACA;;;;AACA;;;;;;AACA;;AAPA;;AAEA;;AANA;AACA;AAYO,IAAI,8CAAmB;AACxB,qBAAe,IADS,EACgB;AACxC,qBAAe,CAAC,CAFQ,EAEgB;AACxC,yBAAmB,SAHK,EAGgB;AACxC,aAAO,KAJiB,EAIgB;AACxC,yBAAmB,KALK,EAKgB;AACxC,4BAAsB,KANE,EAMgB;AACxC,+BAAyB,CAPD,EAOgB;AACxC,uBAAiB,EARO,EAQgB;AACxC,qBAAe,KAAK,IAAL,GAAY,IATH,EASgB;AACxC,qBAAe,GAVS,EAUgB;AACxC,mBAAa,CAXW,EAWgB;AACxC,+BAAyB,GAZD,EAYgB;AACxC,gCAA0B,CAbF,EAagB;AACxC,mBAAa,GAdW,EAcgB;AACxC,qBAAgB,CAfQ,EAegB;AACxC,8BAAwB,IAhBA,EAgBgB;AACxC,6BAAsB,CAjBE,EAiBgB;AACxC,mCAA6B,QAlBL,EAkBgB;AACxC,wBAAkB,SAnBM,EAmBgB;AACxC,8BAAw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AN;AACD;AACF;AACF,SAjCD,MAiCO;AACL;AACA,eAAK,cAAL,GAAsB,OAAO,UAAP,CAAkB,KAAK,WAAL,CAAiB,IAAjB,CAAsB,IAAtB,CAAlB,EAA+C,OAAO,OAAtD,CAAtB;AACD;AACF;AACF;;;kCAEa;AACZ,qBAAO,IAAP,4BAAqC,KAAK,OAAL,CAAa,GAAlD;AACA,WAAK,SAAL,CAAe,SAAf,CAAyB,KAAK,KAA9B,EAAqC,KAAK,OAA1C,EAAmD,IAAnD;AACD;;;iCAEY,K,EAAO;AAClB,UAAI,MAAM,MAAM,aAAhB;AAAA,UACI,QAAQ,KAAK,KADjB;;AAGA,YAAM,MAAN,GAAe,MAAM,MAArB;AACA,UAAI,MAAM,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,EAAsC,GAAtC;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",
"// see https://tools.ietf.org/html/rfc1808\r\n\r\n/* jshint ignore:start */\r\n(function(root) { \r\n/* jshint ignore:end */\r\n\r\n var URL_REGEX = /^((?:[^\\/;?#]+:)?)(\\/\\/[^\\/\\;?#]*)?(.*?)??(;.*?)?(\\?.*?)?(#.*?)?$/;\r\n var FIRST_SEGMENT_REGEX = /^([^\\/;?#]*)(.*)$/;\r\n var SLASH_DOT_REGEX = /(?:\\/|^)\\.(?=\\/)/g;\r\n var SLASH_DOT_DOT_REGEX = /(?:\\/|^)\\.\\.\\/(?!\\.\\.\\/).*?(?=\\/)/g;\r\n\r\n var URLToolkit = { // jshint ignore:line\r\n // If opts.alwaysNormalize is true then the path will always be normalized even when it starts with / or //\r\n // E.g\r\n // With opts.alwaysNormalize = false (default, spec compliant)\r\n // http://a.com/b/cd + /e/f/../g => http://a.com/e/f/../g\r\n // With opts.alwaysNormalize = true (default, not spec compliant)\r\n // http://a.com/b/cd + /e/f/../g => http://a.com/e/g\r\n buildAbsoluteURL: function(baseURL, relativeURL, opts) {\r\n opts = opts || {};\r\n // remove any remaining space and CRLF\r\n baseURL = baseURL.trim();\r\n relativeURL = relativeURL.trim();\r\n if (!relativeURL) {\r\n // 2a) If the embedded URL is entirely empty, it inherits the\r\n // entire base URL (i.e., is set equal to the base URL)\r\n // and we are done.\r\n if (!opts.alwaysNormalize) {\r\n return baseURL;\r\n }\r\n var basePartsForNormalise = this.parseURL(baseURL);\r\n if (!baseParts) {\r\n throw new Error('Error trying to parse base URL.');\r\n }\r\n basePartsForNormalise.path = URLToolkit.normalizePath(basePartsForNormalise.path);\r\n return URLToolkit.buildURLFromParts(basePartsForNormalise);\r\n }\r\n var relativeParts = this.parseURL(relativeURL);\r\n if (!relativeParts) {\r\n throw new Error('Error trying to parse relative URL.');\r\n }\r\n if (relativeParts.scheme) {\r\n // 2b) If the embedded URL starts with a scheme name, it is\r\n // interpreted as an absolute URL and we are done.\r\n if (!opts.alwaysNormalize) {\r\n return relativeURL;\r\n }\r\n relativeParts.path = URLToolkit.normalizePath(relativeParts.path);\r\n return URLToolkit.buildURLFromParts(relativeParts);\r\n }\r\n var baseParts = this.parseURL(baseURL);\r\n if (!baseParts) {\r\n throw new Error('Error trying to parse base URL.');\r\n }\r\n if (!baseParts.netLoc && baseParts.path && baseParts.path[0] !== '/') {\r\n // If netLoc missing and path doesn't start with '/', assume everthing before the first '/' is the netLoc\r\n // This causes 'example.com/a' to be handled as '//example.com/a' instead of '/example.com/a'\r\n var pathParts = FIRST_SEGMENT_REGEX.exec(baseParts.path);\r\n baseParts.netLoc = pathParts[1];\r\n baseParts.path = pathParts[2];\r\n }\r\n if (baseParts.netLoc && !baseParts.path) {\r\n baseParts.path = '/';\r\n }\r\n var builtParts = {\r\n // 2c) Otherwise, the embedded URL inherits the scheme of\r\n // the base URL.\r\n scheme: baseParts.scheme,\r\n netLoc: relativeParts.netLoc,\r\n path: null,\r\n params: relativeParts.params,\r\n query: relativeParts.query,\r\n fragment: relativeParts.fragment\r\n };\r\n if (!relativeParts.netLoc) {\r\n // 3) If the embedded URL's <net_loc> is non-empty, we skip to\r\n // Step 7. Otherwise, the embedded URL inherits the <net_loc>\r\n // (if any) of the base URL.\r\n builtParts.netLoc = baseParts.netLoc;\r\n // 4) If the embedded URL path is preceded by a slash \"/\", the\r\n // path is not relative and we skip to Step 7.\r\n if (relativeParts.path[0] !== '/') {\r\n if (!relativeParts.path) {\r\n // 5) If the embedded URL path is empty (and not preceded by a\r\n // slash), then the embedded URL inherits the base URL path\r\n builtParts.path = baseParts.path;\r\n // 5a) if the embedded URL's <params> is non-empty, we skip to\r\n // step 7; otherwise, it inherits the <params> of the base\r\n // URL (if any) and\r\n if (!relativeParts.params) {\r\n builtParts.params = baseParts.params;\r\n // 5b) if the embedded URL's <query> is non-empty, we skip to\r\n // step 7; otherwise, it inherits the <query> of the base\r\n // URL (if any) and we skip to step 7.\r\n if (!relativeParts.query) {\r\n builtParts.query = baseParts.query;\r\n }\r\n }\r\n } else {\r\n // 6) The last segment of the base URL's path (anything\r\n // following the rightmost slash \"/\", or the entire path if no\r\n // slash is present) is removed and the embedded URL's path is\r\n // appended in its place.\r\n var baseURLPath = baseParts.path;\r\n var newPath = baseURLPath.substring(0, baseURLPath.lastIndexOf('/') + 1) + relativeParts.path;\r\n builtParts.path = URLToolkit.normalizePath(newPath);\r\n }\r\n }\r\n }\r\n if (builtParts.path === null) {\r\n builtParts.path = opts.alwaysNormalize ? URLToolkit.normalizePath(relativeParts.path) : relativeParts.path;\r\n }\r\n return URLToolkit.buildURLFromParts(builtParts);\r\n },\r\n parseURL: function(url) {\r\n var parts = URL_REGEX.exec(url);\r\n if (!parts) {\r\n return null;\r\n }\r\n return {\r\n scheme: parts[1] || '',\r\n netLoc: parts[2] || '',\r\n path: parts[3] || '',\r\n params: parts[4] || '',\r\n query: parts[5] || '',\r\n fragment: parts[6] || ''\r\n };\r\n },\r\n normalizePath: function(path) {\r\n // The following operations are\r\n // then applied, in order, to the new path:\r\n // 6a) All occurrences of \"./\", where \".\" is a complete path\r\n // segment, are removed.\r\n // 6b) If the path ends with \".\" as a complete path segment,\r\n // that \".\" is removed.\r\n path = path.split('').reverse().join('').replace(SLASH_DOT_REGEX, '');\r\n // 6c) All occurrences of \"<segment>/../\", where <segment> is a\r\n // complete path segment not equal to \"..\", are removed.\r\n // Removal of these path segments is performed iteratively,\r\n // removing the leftmost matching pattern on each iteration,\r\n // until no matching pattern remains.\r\n // 6d) If the path ends with \"<segment>/..\", where <segment> is a\r\n // complete path segment not equal to \"..\", that\r\n // \"<segment>/..\" is removed.\r\n while (path.length !== (path = path.replace(SLASH_DOT_DOT_REGEX, '')).length) {} // jshint ignore:line\r\n return path.split('').reverse().join('');\r\n },\r\n buildURLFromParts: function(parts) {\r\n return parts.scheme + parts.netLoc + parts.path + parts.params + parts.query + parts.fragment;\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 * HLS config\n */\n'use strict';\n\nimport AbrController from './controller/abr-controller';\nimport BufferController from './controller/buffer-controller';\nimport CapLevelController from './controller/cap-level-controller';\nimport FPSController from './controller/fps-controller';\nimport XhrLoader from './utils/xhr-loader';\n//import FetchLoader from './utils/fetch-loader';\n//#if altaudio\nimport AudioTrackController from './controller/audio-track-controller';\nimport AudioStreamController from './controller/audio-stream-controller';\n//#endif\n\n//#if subtitle\nimport Cues from './utils/cues';\nimport TimelineController from './controller/timeline-controller';\nimport SubtitleTrackController from './controller/subtitle-track-controller';\nimport SubtitleStreamController from './controller/subtitle-stream-controller';\n//#endif\n\nexport var hlsDefaultConfig = {\n autoStartLoad: true, // used by stream-controller\n startPosition: -1, // used by stream-controller\n defaultAudioCodec: undefined, // used by stream-controller\n debug: false, // used by logger\n capLevelOnFPSDrop: false, // used by fps-controller\n capLevelToPlayerSize: false, // used by cap-level-controller\n initialLiveManifestSize: 1, // used by stream-controller\n maxBufferLength: 30, // used by stream-controller\n maxBufferSize: 60 * 1000 * 1000, // used by stream-controller\n maxBufferHole: 0.5, // used by stream-controller\n maxSeekHole: 2, // used by stream-controller\n lowBufferWatchdogPeriod: 0.5, // used by stream-controller\n highBufferWatchdogPeriod: 3, // used by stream-controller\n nudgeOffset: 0.1, // used by stream-controller\n nudgeMaxRetry : 3, // used by stream-controller\n maxFragLookUpTolerance: 0.25, // used by stream-controller\n liveSyncDurationCount:3, // used by stream-controller\n liveMaxLatencyDurationCount: Infinity, // used by stream-controller\n liveSyncDuration: undefined, // used by stream-controller\n liveMaxLatencyDuration: undefined, // used by stream-controller\n maxMaxBufferLength: 600, // used by stream-controller\n enableWorker: true, // used by demuxer\n enableSoftwareAES: true, // used by decrypter\n manifestLoadingTimeOut: 10000, // used by playlist-loader\n manifestLoadingMaxRetry: 1, // used by playlist-loader\n manifestLoadingRetryDelay: 1000, // used by playlist-loader\n manifestLoadingMaxRetryTimeout: 64000, // used by playlist-loader\n startLevel: undefined, // used by level-controller\n levelLoadingTimeOut: 10000, // used by playlist-loader\n levelLoadingMaxRetry: 4, // used by playlist-loader\n levelLoadingRetryDelay: 1000, // used by playlist-loader\n levelLoadingMaxRetryTimeout: 64000, // used by playlist-loader\n fragLoadingTimeOut: 20000, // used by fragment-loader\n fragLoadingMaxRetry: 6, // used by fragment-loader\n fragLoadingRetryDelay: 1000, // used by fragment-loader\n fragLoadingMaxRetryTimeout: 64000, // used by fragment-loader\n fragLoadingLoopThreshold: 3, // used by stream-controller\n startFragPrefetch: false, // used by stream-controller\n fpsDroppedMonitoringPeriod: 5000, // used by fps-controller\n fpsDroppedMonitoringThreshold: 0.2, // used by fps-controller\n appendErrorMaxRetry: 3, // used by buffer-controller\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//#if altaudio\n audioStreamController: AudioStreamController,\n audioTrackController : AudioTrackController,\n//#endif\n//#if subtitle\n subtitleStreamController: SubtitleStreamController,\n subtitleTrackController: SubtitleTrackController,\n timelineController: TimelineController,\n cueHandler: Cues,\n enableCEA708Captions: true, // used by timeline-controller\n enableWebVTT: true, // used by timeline-controller\n captionsTextTrack1Label: 'English', // used by timeline-controller\n captionsTextTrack1LanguageCode: 'en', // used by timeline-controller\n captionsTextTrack2Label: 'Spanish', // used by timeline-controller\n captionsTextTrack2LanguageCode: 'es', // used by timeline-controller\n//#endif\n stretchShortVideoTrack: false, // used by mp4-remuxer\n forceKeyFrameOnDiscontinuity: true, // used by ts-demuxer\n abrEwmaFastLive: 3, // used by abr-controller\n abrEwmaSlowLive: 9, // used by abr-controller\n abrEwmaFastVoD: 3, // used by abr-controller\n abrEwmaSlowVoD: 9, // used by abr-controller\n abrEwmaDefaultEstimate: 5e5, // 500 kbps // used by abr-controller\n abrBandWidthFactor : 0.95, // used by abr-controller\n abrBandWidthUpFactor : 0.7, // used by abr-controller\n abrMaxWithRealBitrate : false, // used by abr-controller\n maxStarvationDelay : 4, // used by abr-controller\n maxLoadingDelay : 4, // used by abr-controller\n minAutoBitrate: 0 // used by hls\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 '../utils/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._nextAutoLevel = -1;\n this.hls = hls;\n this.timer = null;\n this._bwEstimator = null;\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 = hls.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 && stats && ((!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 level = levels[frag.level],\n levelBitrate = level.realBitrate ? Math.max(level.realBitrate,level.bitrate) : level.bitrate,\n expectedLen = stats.total ? stats.total : Math.max(stats.loaded, Math.round(frag.duration * levelBitrate / 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 let levelNextBitrate = levels[nextLoadLevel].realBitrate ? Math.max(levels[nextLoadLevel].realBitrate,levels[nextLoadLevel].bitrate) : levels[nextLoadLevel].bitrate;\n fragLevelNextLoadedDelay = frag.duration * levelNextBitrate / (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' && !isNaN(frag.sn)) {\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\n // compute level average bitrate\n if (this.hls.config.abrMaxWithRealBitrate) {\n const level = this.hls.levels[frag.level];\n let loadedBytes = (level.loaded ? level.loaded.bytes : 0) + data.stats.loaded;\n let loadedDuration = (level.loaded ? level.loaded.duration : 0) + data.frag.duration;\n level.loaded = { bytes : loadedBytes, duration : loadedDuration };\n level.realBitrate = Math.round(8*loadedBytes/loadedDuration);\n }\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' && !isNaN(frag.sn) && ((!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 stats.bwEstimate = this._bwEstimator.getEstimate();\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 clearInterval(this.timer);\n this.timer = null;\n }\n\n // return next auto level\n get nextAutoLevel() {\n const forcedAutoLevel = this._nextAutoLevel;\n const bwEstimator = this._bwEstimator;\n // in case next auto level has been forced, and bw not available or not reliable, return forced value\n if (forcedAutoLevel !== -1 && (!bwEstimator || !bwEstimator.canEstimate())) {\n return forcedAutoLevel;\n }\n // compute next level using ABR logic\n let nextABRAutoLevel = this._nextABRAutoLevel;\n // if forced auto level has been defined, use it to cap ABR computed quality level\n if (forcedAutoLevel !== -1) {\n nextABRAutoLevel = Math.min(forcedAutoLevel,nextABRAutoLevel);\n }\n return nextABRAutoLevel;\n }\n get _nextABRAutoLevel() {\n var hls = this.hls, maxAutoLevel = hls.maxAutoLevel, levels = hls.levels, config = hls.config, minAutoLevel = hls.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 = currentFragDuration ? Math.min(currentFragDuration,config.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 // cap maxLoadingDelay and ensure it is not bigger 'than bitrate test' frag duration\n const maxLoadingDelay = currentFragDuration ? Math.min(currentFragDuration,config.maxLoadingDelay) : config.maxLoadingDelay;\n maxStarvationDelay = 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].realBitrate ? Math.max(levels[i].realBitrate,levels[i].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 // special case to support startLevel = -1 (bitrateTest) on live streams : in that case we should not exit loop so that _findBestLevel will return -1\n (!fetchDuration || (live && !this.bitrateTestDelay) || fetchDuration < maxFetchDuration) ) {\n // as we are looping from highest to lowest, this will return the best achievable quality level\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';\nimport { findFragWithCC } from '../utils/discontinuities';\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 BUFFER_FLUSHING : 'BUFFER_FLUSHING',\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._state = State.STOPPED;\n this.ontick = this.tick.bind(this);\n this.initPTS=[];\n this.waitingFragment=null;\n this.videoTrackCC = 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.frag.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 this.videoTrackCC = cc;\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 this.tick();\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 set state(nextState) {\n if (this.state !== nextState) {\n const previousState = this.state;\n this._state = nextState;\n logger.log(`audio stream:${previousState}->${nextState}`);\n }\n }\n\n get state() {\n return this._state;\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 case State.BUFFER_FLUSHING:\n break;\n case State.STARTING:\n this.state = State.WAITING_TRACK;\n this.loadedmetadata = false;\n break;\n case State.IDLE:\n const tracks = this.tracks;\n // audio tracks not received => exit loop\n if (!tracks) {\n break;\n }\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 if (pos === undefined) {\n break;\n }\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 trackId = this.trackId;\n\n // if buffer length is less than maxBufLen try to load a new fragment\n if ((bufferLen < maxBufLen || audioSwitch) && trackId < tracks.length) {\n trackDetails = tracks[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 or if audio buffer upfront, let's seek to start\n if (bufferInfo.end > start || bufferInfo.nextStart) {\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 if (trackDetails.initSegment && !trackDetails.initSegment.data) {\n frag = trackDetails.initSegment;\n }\n // if bufferEnd before start of playlist, load first fragment\n else if (bufferEnd <= start) {\n frag = fragments[0];\n if (this.videoTrackCC !== null && frag.cc !== this.videoTrackCC) {\n // Ensure we find a fragment which matches the continuity of the video track\n frag = findFragWithCC(fragments, this.videoTrackCC);\n }\n if (trackDetails.live && frag.loadIdx && frag.loadIdx === this.fragLoadIdx) {\n // we just loaded this first fragment, and we are still lagging behind the start of the live playlist\n // let's force seek to start\n const nextBuffered = bufferInfo.nextStart ? bufferInfo.nextStart : start;\n logger.log(`no alt audio available @currentTime:${this.media.currentTime}, seeking @${nextBuffered + 0.05}`);\n this.media.currentTime = nextBuffered + 0.05;\n return;\n }\n } else {\n let foundFrag;\n let maxFragLookUpTolerance = config.maxFragLookUpTolerance;\n const fragNext = fragPrevious ? fragments[fragPrevious.sn - fragments[0].sn + 1] : undefined;\n let fragmentWithinToleranceTest = (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 // Set the lookup tolerance to be small enough to detect the current segment - ensures we don't skip over very small segments\n let candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration);\n if ((candidate.start + candidate.duration - candidateLookupTolerance) <= bufferEnd) {\n return 1;\n }// if maxFragLookUpTolerance will have negative value then don't return -1 for first element\n else if (candidate.start - candidateLookupTolerance > bufferEnd && candidate.start) {\n return -1;\n }\n return 0;\n };\n\n if (bufferEnd < end) {\n if (bufferEnd > end - maxFragLookUpTolerance) {\n maxFragLookUpTolerance = 0;\n }\n // Prefer the next fragment if it's within tolerance\n if (fragNext && !fragmentWithinToleranceTest(fragNext)) {\n foundFrag = fragNext;\n } else {\n foundFrag = BinarySearch.search(fragments, fragmentWithinToleranceTest);\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 && (frag.decryptdata.uri != null) && (frag.decryptdata.key == null)) {\n logger.log(`Loading key for ${frag.sn} of [${trackDetails.startSN} ,${trackDetails.endSN}],track ${trackId}`);\n this.state = State.KEY_LOADING;\n hls.trigger(Event.KEY_LOADING, {frag: frag});\n } else {\n logger.log(`Loading ${frag.sn}, cc: ${frag.cc} of [${trackDetails.startSN} ,${trackDetails.endSN}],track ${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 if (!isNaN(frag.sn)) {\n this.nextLoadPosition = frag.start + frag.duration;\n }\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 const videoTrackCC = this.videoTrackCC;\n if (this.initPTS[videoTrackCC] === undefined) {\n break;\n }\n\n // Ensure we don't get stuck in the WAITING_INIT_PTS state if the waiting frag CC doesn't match any initPTS\n const waitingFrag = this.waitingFragment;\n if (waitingFrag) {\n const waitingFragCC = waitingFrag.frag.cc;\n if (videoTrackCC !== waitingFragCC) {\n track = this.tracks[this.trackId];\n if (track.details && track.details.live) {\n logger.warn(`Waiting fragment CC (${waitingFragCC}) does not match video track CC (${videoTrackCC})`);\n this.waitingFragment = null;\n this.state = State.IDLE;\n }\n } else {\n this.state = State.FRAG_LOADING;\n this.onFragLoaded(this.waitingFragment);\n this.waitingFragment = null;\n }\n } else {\n this.state = State.IDLE;\n }\n\n break;\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\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 if (this.fragLoadIdx !== undefined) {\n this.fragLoadIdx += 2 * this.config.fragLoadingLoopThreshold;\n }\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 fragLoaded = data.frag;\n if (this.state === State.FRAG_LOADING &&\n fragCurrent &&\n fragLoaded.type === 'audio' &&\n fragLoaded.level === fragCurrent.level &&\n fragLoaded.sn === fragCurrent.sn) {\n var track = this.tracks[this.trackId],\n details = track.details,\n duration = details.totalduration,\n trackId = fragCurrent.level,\n sn = fragCurrent.sn,\n cc = fragCurrent.cc,\n audioCodec = this.config.defaultAudioCodec || track.audioCodec || 'mp4a.40.2',\n stats = this.stats = data.stats;\n if (sn === 'initSegment') {\n this.state = State.IDLE;\n\n stats.tparsed = stats.tbuffered = performance.now();\n details.initSegment.data = data.payload;\n this.hls.trigger(Event.FRAG_BUFFERED, {stats: stats, frag: fragCurrent, id : 'audio'});\n this.tick();\n } else {\n this.state = State.PARSING;\n // transmux the MPEG-TS data to ISO-BMFF segments\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 let initSegmentData = details.initSegment ? details.initSegment.data : [];\n if (details.initSegment || 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, initSegmentData, audioCodec, null, fragCurrent, duration, 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 }\n this.fragLoadError = 0;\n }\n\n onFragParsingInitSegment(data) {\n const fragCurrent = this.fragCurrent;\n const fragNew = data.frag;\n if (fragCurrent &&\n data.id === 'audio' &&\n fragNew.sn === fragCurrent.sn &&\n fragNew.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 = track.codec;\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 const fragCurrent = this.fragCurrent;\n const fragNew = data.frag;\n if (fragCurrent &&\n data.id === 'audio' &&\n data.type === 'audio' &&\n fragNew.sn === fragCurrent.sn &&\n fragNew.level === fragCurrent.level &&\n this.state === State.PARSING) {\n let trackId= this.trackId,\n track = this.tracks[trackId],\n hls = this.hls;\n\n if (isNaN(data.endPTS)) {\n data.endPTS = data.startPTS + fragCurrent.duration;\n data.endDTS = data.startDTS + fragCurrent.duration;\n }\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,fragCurrent,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 this.state = State.BUFFER_FLUSHING;\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 && buffer.length) {\n pendingData.push({type: data.type, data: buffer, parent : 'audio',content : 'data'});\n }\n });\n if (!appendOnBufferFlush && pendingData.length) {\n pendingData.forEach(appendObj => {\n // only append in PARSING state (rationale is that an appending error could happen synchronously on first segment appending)\n // in that case it is useless to append following segments\n if (this.state === State.PARSING) {\n // arm pending Buffering flag before appending a segment\n this.pendingBuffering = true;\n this.hls.trigger(Event.BUFFER_APPENDING, appendObj);\n }\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 const fragCurrent = this.fragCurrent;\n const fragNew = data.frag;\n if (fragCurrent &&\n data.id === 'audio' &&\n fragNew.sn === fragCurrent.sn &&\n fragNew.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 // switch error to fatal\n data.fatal = true;\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 case ErrorDetails.BUFFER_FULL_ERROR:\n // if in appending state\n if (data.parent === 'audio' && (this.state === State.PARSING || this.state === State.PARSED)) {\n const media = this.mediaBuffer,\n currentTime = this.media.currentTime,\n mediaBuffered = media && BufferHelper.isBuffered(media,currentTime) && BufferHelper.isBuffered(media,currentTime+0.5);\n // reduce max buf len if current position is buffered\n if (mediaBuffered) {\n const config = this.config;\n if(config.maxMaxBufferLength >= config.maxBufferLength) {\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(`audio:reduce max buffer length to ${config.maxMaxBufferLength}s`);\n // increase fragment load Index to avoid frag loop loading error after buffer flush\n this.fragLoadIdx += 2 * config.fragLoadingLoopThreshold;\n }\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/video-dev/hls.js/pull/708\n // in that case flush the whole audio buffer to recover\n logger.warn('buffer full error also media.currentTime is not buffered, flush audio buffer');\n this.fragCurrent = null;\n // flush everything\n this.state = State.BUFFER_FLUSHING;\n this.hls.trigger(Event.BUFFER_FLUSHING, {startOffset: 0 , endOffset: Number.POSITIVE_INFINITY, type : 'audio'});\n }\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';\nimport {ErrorTypes} from '../errors';\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 Event.ERROR);\n this.ticks = 0;\n this.ontick = this.tick.bind(this);\n }\n\n destroy() {\n this.cleanTimer();\n EventHandler.prototype.destroy.call(this);\n }\n\n cleanTimer() {\n if (this.timer) {\n clearTimeout(this.timer);\n this.timer = null;\n }\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 this.updateTrack(this.trackId);\n }\n\n onError(data) {\n if(data.fatal && data.type === ErrorTypes.NETWORK_ERROR) {\n this.cleanTimer();\n }\n }\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 && !defaultFound) {\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 this.cleanTimer();\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 this.cleanTimer();\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 this.cleanTimer();\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/video-dev/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 || (data.levels.length && data.audio),\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});\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/video-dev/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, parent : segment.parent};\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 /* 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\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\n onFpsDropLevelCapping(data) {\n\t // Don't add a restricted level more than once\n if (CapLevelController.isLevelAllowed(data.droppedLevel, this.restrictedLevels)) {\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 const hls = this.hls;\n this.restrictedLevels = [];\n if (hls.config.capLevelToPlayerSize) {\n this.autoLevelCapping = Number.POSITIVE_INFINITY;\n this.levels = data.levels;\n 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 const hls = this.hls;\n hls.autoLevelCapping = this.getMaxLevel(levelsLength - 1);\n if (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 hls.streamController.nextLevelSwitch();\n }\n this.autoLevelCapping = 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 if (!this.levels) {\n return -1;\n }\n\n const validLevels = this.levels.filter((level, index) =>\n CapLevelController.isLevelAllowed(index, this.restrictedLevels) && index <= capLevelIndex\n );\n\n return CapLevelController.getMaxLevelByMediaSize(validLevels, this.mediaWidth, this.mediaHeight);\n }\n\n get mediaWidth() {\n let width;\n const media = this.media;\n if (media) {\n width = media.width || media.clientWidth || media.offsetWidth;\n width *= CapLevelController.contentScaleFactor;\n }\n return width;\n }\n\n get mediaHeight() {\n let height;\n const media = this.media;\n if (media) {\n height = media.height || media.clientHeight || media.offsetHeight;\n height *= CapLevelController.contentScaleFactor;\n }\n return height;\n }\n\n static get contentScaleFactor() {\n let pixelRatio = 1;\n try {\n pixelRatio = window.devicePixelRatio;\n } catch(e) {}\n return pixelRatio;\n }\n\n static isLevelAllowed(level, restrictedLevels = []) {\n return restrictedLevels.indexOf(level) === -1;\n }\n\n static getMaxLevelByMediaSize(levels, width, height) {\n if (!levels || (levels && !levels.length)) {\n return -1;\n }\n\n // Levels can have the same dimensions but differing bandwidths - since levels are ordered, we can look to the next\n // to determine whether we've chosen the greatest bandwidth for the media's dimensions\n const atGreatestBandiwdth = (curLevel, nextLevel) => {\n if (!nextLevel) {\n return true;\n }\n return curLevel.width !== nextLevel.width || curLevel.height !== nextLevel.height;\n };\n\n // If we run through the loop without breaking, the media's dimensions are greater than every level, so default to\n // the max level\n let maxLevelIndex = levels.length - 1;\n\n for (let i = 0; i < levels.length; i+= 1) {\n const level = levels[i];\n if ((level.width >= width || level.height >= height) && atGreatestBandiwdth(level, levels[i + 1])) {\n maxLevelIndex = i;\n break;\n }\n }\n\n return maxLevelIndex;\n }\n}\n\nexport default CapLevelController;\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 const config = this.hls.config;\n if (config.capLevelOnFPSDrop) {\n const video = this.video = data.media instanceof HTMLVideoElement ? data.media : null;\n if (typeof video.getVideoPlaybackQuality === 'function') {\n this.isVideoPlaybackQualityAvailable = true;\n }\n clearInterval(this.timer);\n this.timer = setInterval(this.checkFPSInterval.bind(this), 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 hls = this.hls;\n 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 > hls.config.fpsDroppedMonitoringThreshold * currentDecoded) {\n let currentLevel = hls.currentLevel;\n logger.warn('drop FPS ratio greater than max allowed value for currentLevel: ' + currentLevel);\n if (currentLevel > 0 && (hls.autoLevelCapping === -1 || hls.autoLevelCapping >= currentLevel)) {\n currentLevel = currentLevel - 1;\n hls.trigger(Event.FPS_DROP_LEVEL_CAPPING, {level: currentLevel, droppedLevel: hls.currentLevel});\n hls.autoLevelCapping = currentLevel;\n 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 const video = this.video;\n if (video) {\n if (this.isVideoPlaybackQualityAvailable) {\n let videoPlaybackQuality = video.getVideoPlaybackQuality();\n this.checkFPS(video, videoPlaybackQuality.totalVideoFrames, videoPlaybackQuality.droppedVideoFrames);\n } else {\n this.checkFPS(video, video.webkitDecodedFrameCount, video.webkitDroppedFrameCount);\n }\n }\n }\n}\n\nexport default FPSController;\n\n",
"/*\n * id3 metadata track controller\n*/\n\nimport Event from '../events';\nimport EventHandler from '../event-handler';\nimport ID3 from '../demux/id3';\n\nclass ID3TrackController extends EventHandler {\n\n constructor(hls) {\n super(hls,\n Event.MEDIA_ATTACHED,\n Event.MEDIA_DETACHING,\n Event.FRAG_PARSING_METADATA);\n this.id3Track = undefined;\n this.media = undefined;\n }\n\n destroy() {\n EventHandler.prototype.destroy.call(this);\n }\n\n // Add ID3 metatadata text track.\n onMediaAttached(data) {\n this.media = data.media;\n if (!this.media) {\n return;\n }\n\n this.id3Track = this.media.addTextTrack('metadata', 'id3');\n this.id3Track.mode = 'hidden';\n }\n\n onMediaDetaching() {\n this.media = undefined;\n }\n\n onFragParsingMetadata(data) {\n const fragment = data.frag;\n const samples = data.samples;\n\n // Attempt to recreate Safari functionality by creating\n // WebKitDataCue objects when available and store the decoded\n // ID3 data in the value property of the cue\n let Cue = window.WebKitDataCue || window.VTTCue || window.TextTrackCue;\n\n for (let i = 0; i < samples.length; i++) {\n const frames = ID3.getID3Frames(samples[i].data);\n if (frames) {\n const startTime = samples[i].pts;\n let endTime = i < samples.length - 1 ? samples[i+1].pts : fragment.endPTS;\n\n // Give a slight bump to the endTime if it's equal to startTime to avoid a SyntaxError in IE\n if (startTime === endTime) {\n endTime += 0.0001;\n }\n\n for(let j = 0; j < frames.length; j++) {\n const frame = frames[j];\n // Safari doesn't put the timestamp frame in the TextTrack\n if (!ID3.isTimeStampFrame(frame)) {\n const cue = new Cue(startTime, endTime, '');\n cue.value = frame;\n this.id3Track.addCue(cue);\n }\n }\n }\n }\n }\n}\n\nexport default ID3TrackController;\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 = -1;\n }\n\n destroy() {\n this.cleanTimer();\n this._manualLevel = -1;\n }\n\n cleanTimer() {\n if (this.timer) {\n clearTimeout(this.timer);\n this.timer = null;\n }\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 const levels = this._levels;\n const hls = this.hls;\n // check if level idx is valid\n if (newLevel >= 0 && newLevel < levels.length) {\n // stopping live reloading timer if any\n this.cleanTimer();\n if (this._level !== newLevel) {\n logger.log(`switching to level ${newLevel}`);\n this._level = newLevel;\n var levelProperties = levels[newLevel];\n levelProperties.level = newLevel;\n // LEVEL_SWITCH to be deprecated in next major release\n hls.trigger(Event.LEVEL_SWITCH, levelProperties);\n hls.trigger(Event.LEVEL_SWITCHING, levelProperties);\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 hls.trigger(Event.LEVEL_LOADING, {url: level.url[urlId], level: newLevel, id: urlId});\n }\n } else {\n // invalid level id given, trigger error\n 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 this._startLevel = newLevel;\n }\n\n onError(data) {\n if(data.fatal) {\n if (data.type === ErrorTypes.NETWORK_ERROR) {\n this.cleanTimer();\n }\n return;\n }\n\n let details = data.details, hls = this.hls, levelId, level, levelError = false;\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 hls.nextAutoLevel = Math.max(0,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 // boolean used to inform stream controller not to switch back to IDLE on non fatal error\n data.levelRetry = true;\n } else {\n logger.error(`cannot recover ${details} error`);\n this._level = undefined;\n // stopping live reloading timer if any\n this.cleanTimer();\n // switch error to fatal\n data.fatal = true;\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];\n if (level && level.url) {\n var urlId = level.urlId;\n this.hls.trigger(Event.LEVEL_LOADING, {url: level.url[urlId], level: levelId, id: urlId});\n }\n }\n }\n\n get nextLoadLevel() {\n if (this._manualLevel !== -1) {\n return this._manualLevel;\n } else {\n return this.hls.nextAutoLevel;\n }\n }\n\n set nextLoadLevel(nextLevel) {\n this.level = nextLevel;\n if (this._manualLevel === -1) {\n this.hls.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._state = State.STOPPED;\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 this.forceStartLoad = true;\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 this.forceStartLoad = false;\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 this._doTickIdle();\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;\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\n if (!levelInfo) {\n return;\n }\n\n let 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;\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;\n }\n\n // we just got done loading the final fragment, and currentPos is buffered, and there is no other buffered range after ...\n // rationale is that in case there are any buffered rangesafter, it means that there are unbuffered portion in between\n // so we should not switch to ENDED in that case, to be able to buffer themx\n let fragPrevious = this.fragPrevious;\n if (!levelDetails.live && fragPrevious && fragPrevious.sn === levelDetails.endSN && bufferLen && !bufferInfo.nextStart) {\n // fragPrevious is last fragment. retrieve level duration using last frag start offset + duration\n // real duration might be lower than initial duration if there are drifts between real frag duration and playlist signaling\n const duration = Math.min(media.duration,fragPrevious.start + fragPrevious.duration);\n // if 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 (audio/video offsets...)\n // tolerate up to one frag duration to cope with these cases.\n // also cope with almost zero last frag duration (max last frag duration with 200ms) refer to https://github.com/video-dev/hls.js/pull/657\n if (duration - Math.max(bufferInfo.end,fragPrevious.start) <= Math.max(0.2,fragPrevious.duration)) {\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;\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 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;\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 if (levelDetails.initSegment && !levelDetails.initSegment.data) {\n frag = levelDetails.initSegment;\n } else {\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;\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;\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 }\n if (!frag) {\n frag = this._findFragment(start, fragPrevious, fragLen, fragments, bufferEnd, end, levelDetails);\n }\n if(frag) {\n this._loadFragmentOrKey(frag, level, levelDetails, pos, bufferEnd);\n }\n return;\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-config.maxFragLookUpTolerance, 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 this.nextLoadPosition = liveSyncPosition;\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 const targetSN = fragPrevious.sn + 1;\n if (targetSN >= levelDetails.startSN && targetSN <= levelDetails.endSN) {\n const fragNext = fragments[targetSN - levelDetails.startSN];\n if (fragPrevious.cc === fragNext.cc) {\n frag = fragNext;\n logger.log(`live playlist, switching playlist, load frag with next SN: ${frag.sn}`);\n }\n }\n // next frag SN not available (or not with same continuity counter)\n // look for a frag sharing the same CC\n if (!frag) {\n frag = BinarySearch.search(fragments, function(frag) {\n return fragPrevious.cc - frag.cc;\n });\n if (frag) {\n logger.log(`live playlist, switching playlist, load frag with same CC: ${frag.sn}`);\n }\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 let frag;\n let foundFrag;\n let maxFragLookUpTolerance = config.maxFragLookUpTolerance;\n const fragNext = fragPrevious ? fragments[fragPrevious.sn - fragments[0].sn + 1] : undefined;\n let fragmentWithinToleranceTest = (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 // Set the lookup tolerance to be small enough to detect the current segment - ensures we don't skip over very small segments\n let candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration);\n if (candidate.start + candidate.duration - candidateLookupTolerance <= bufferEnd) {\n return 1;\n } // if maxFragLookUpTolerance will have negative value then don't return -1 for first element\n else if (candidate.start - candidateLookupTolerance > bufferEnd && candidate.start) {\n return -1;\n }\n return 0;\n };\n\n if (bufferEnd < end) {\n if (bufferEnd > end - maxFragLookUpTolerance) {\n maxFragLookUpTolerance = 0;\n }\n // Prefer the next fragment if it's within tolerance\n if (fragNext && !fragmentWithinToleranceTest(fragNext)) {\n foundFrag = fragNext;\n } else {\n foundFrag = BinarySearch.search(fragments, fragmentWithinToleranceTest);\n }\n } else {\n // reach end of playlist\n foundFrag = fragments[fragLen-1];\n }\n if (foundFrag) {\n frag = foundFrag;\n const curSNIdx = frag.sn - levelDetails.startSN;\n const sameLevel = fragPrevious && frag.level === fragPrevious.level;\n const prevFrag = fragments[curSNIdx - 1];\n const nextFrag = fragments[curSNIdx + 1];\n //logger.log('find SN matching with pos:' + bufferEnd + ':' + frag.sn);\n if (fragPrevious && frag.sn === fragPrevious.sn) {\n if (sameLevel && !frag.backtracked) {\n if (frag.sn < levelDetails.endSN) {\n let deltaPTS = fragPrevious.deltaPTS;\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 = prevFrag;\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 = nextFrag;\n logger.log(`SN just loaded, load next one: ${frag.sn}`);\n }\n } else {\n frag = null;\n }\n } else if (frag.backtracked) {\n // Only backtrack a max of 1 consecutive fragment to prevent sliding back too far when little or no frags start with keyframes\n if (nextFrag && nextFrag.backtracked) {\n logger.warn(`Already backtracked from fragment ${nextFrag.sn}, will not backtrack to fragment ${frag.sn}. Loading fragment ${nextFrag.sn}`);\n frag = nextFrag;\n } else {\n // If a fragment has dropped frames and it's in a same level/sequence, load the previous fragment to try and find the keyframe\n // Reset the dropped count now since it won't be reset until we parse the fragment again, which prevents infinite backtracking on the same segment\n logger.warn('Loaded fragment with dropped frames, backtracking 1 segment to find a keyframe');\n frag.dropped = 0;\n if (prevFrag) {\n if (prevFrag.loadCounter) {\n prevFrag.loadCounter--;\n }\n frag = prevFrag;\n frag.backtracked = true;\n } else if (curSNIdx) {\n // can't backtrack on very first fragment\n frag = null;\n }\n }\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 && 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;\n }\n } else {\n frag.loadCounter = 1;\n }\n frag.loadIdx = this.fragLoadIdx;\n this.fragCurrent = frag;\n this.startFragRequested = true;\n if (!isNaN(frag.sn)) {\n this.nextLoadPosition = frag.start + frag.duration;\n }\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;\n }\n }\n\n set state(nextState) {\n if (this.state !== nextState) {\n const previousState = this.state;\n this._state = nextState;\n logger.log(`main stream:${previousState}->${nextState}`);\n this.hls.trigger(Event.STREAM_STATE_TRANSITION, {previousState, nextState});\n }\n }\n\n get state() {\n return this._state;\n }\n\n getBufferedFrag(position) {\n return BinarySearch.search(this._bufferedFrags, function(frag) {\n if (position < frag.startPTS) {\n return -1;\n } else if (position > frag.endPTS) {\n return 1;\n }\n return 0;\n });\n }\n\n get currentLevel() {\n let media = this.media;\n if (media) {\n const frag = this.getBufferedFrag(media.currentTime);\n if (frag) {\n return frag.level;\n }\n }\n return -1;\n }\n\n get nextBufferedFrag() {\n let media = this.media;\n if (media) {\n // first get end range of current fragment\n return this.followingBufferedFrag(this.getBufferedFrag(media.currentTime));\n } else {\n return null;\n }\n }\n\n followingBufferedFrag(frag) {\n if (frag) {\n // try to get range of next fragment (500ms after this range)\n return this.getBufferedFrag(frag.endPTS + 0.5);\n }\n return null;\n }\n\n get nextLevel() {\n const frag = this.nextBufferedFrag;\n if (frag) {\n return frag.level;\n } else {\n return -1;\n }\n }\n\n _checkFragmentChanged() {\n var fragPlayingCurrent, 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 fragPlayingCurrent = this.getBufferedFrag(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 fragPlayingCurrent = this.getBufferedFrag(currentTime + 0.1);\n }\n if (fragPlayingCurrent) {\n var fragPlaying = fragPlayingCurrent;\n if (fragPlaying !== this.fragPlaying) {\n this.hls.trigger(Event.FRAG_CHANGED, {frag: fragPlaying});\n const fragPlayingLevel = fragPlaying.level;\n if (!this.fragPlaying || this.fragPlaying.level !== fragPlayingLevel) {\n this.hls.trigger(Event.LEVEL_SWITCHED, {level: fragPlayingLevel});\n }\n this.fragPlaying = 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, fragPlayingCurrent, nextBufferedFrag;\n // increase fragment load Index to avoid frag loop loading error after buffer flush\n this.fragLoadIdx += 2 * this.config.fragLoadingLoopThreshold;\n fragPlayingCurrent = this.getBufferedFrag(media.currentTime);\n if (fragPlayingCurrent && fragPlayingCurrent.startPTS > 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,fragPlayingCurrent.startPTS - 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 nextBufferedFrag = this.getBufferedFrag(media.currentTime + fetchdelay);\n if (nextBufferedFrag) {\n // we can flush buffer range following this one without stalling playback\n nextBufferedFrag = this.followingBufferedFrag(nextBufferedFrag);\n if (nextBufferedFrag) {\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 // start flush position is the start PTS of next buffered frag.\n // we use frag.naxStartPTS which is max(audio startPTS, video startPTS).\n // in case there is a small PTS Delta between audio and video, using maxStartPTS avoids flushing last samples from current fragment\n this.flushMainBuffer(nextBufferedFrag.maxStartPTS , 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 fragment.backtracked = 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 if (!isNaN(currentTime)) {\n logger.log(`media seeking to ${currentTime.toFixed(3)}`);\n }\n let mediaBuffer = this.mediaBuffer ? this.mediaBuffer : media;\n let bufferInfo = BufferHelper.bufferInfo(mediaBuffer,currentTime,this.config.maxBufferHole);\n if (this.state === State.FRAG_LOADING) {\n let 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 // if seeking to unbuffered area, clean up fragPrevious\n if (bufferInfo.len === 0) {\n this.fragPrevious = 0;\n }\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 const media = this.media, currentTime = media ? media.currentTime : undefined;\n if (!isNaN(currentTime)) {\n logger.log(`media seeked to ${currentTime.toFixed(3)}`);\n }\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._bufferedFrags = [];\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 || this.forceStartLoad) {\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 this.stats = stats;\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 if (fragLoaded.sn === 'initSegment') {\n this.state = State.IDLE;\n stats.tparsed = stats.tbuffered = performance.now();\n details.initSegment.data = data.payload;\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 let duration = details.totalduration,\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 let initSegmentData = details.initSegment ? details.initSegment.data : [];\n demuxer.push(data.payload, initSegmentData,audioCodec, currentLevel.videoCodec, fragCurrent, duration, accurateTimeOffset,undefined);\n }\n }\n this.fragLoadError = 0;\n }\n\n onFragParsingInitSegment(data) {\n const fragCurrent = this.fragCurrent;\n const fragNew = data.frag;\n if (fragCurrent &&\n data.id === 'main' &&\n fragNew.sn === fragCurrent.sn &&\n fragNew.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 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 const fragCurrent = this.fragCurrent;\n const fragNew = data.frag;\n if (fragCurrent &&\n data.id === 'main' &&\n fragNew.sn === fragCurrent.sn &&\n fragNew.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 = fragCurrent;\n if (isNaN(data.endPTS)) {\n data.endPTS = data.startPTS + fragCurrent.duration;\n data.endDTS = data.startDTS + fragCurrent.duration;\n }\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 // Detect gaps in a fragment and try to fix it by finding a keyframe in the previous fragment (see _findFragments)\n if(data.type === 'video') {\n frag.dropped = data.dropped;\n if (frag.dropped) {\n if (!frag.backtracked) {\n logger.warn('missing video frame(s), backtracking fragment');\n // Return back to the IDLE state without appending to buffer\n // Causes findFragments to backtrack a segment and find the keyframe\n // Audio fragments arriving before video sets the nextLoadPosition, causing _findFragments to skip the backtracked fragment\n frag.backtracked = true;\n this.nextLoadPosition = data.startPTS;\n this.state = State.IDLE;\n this.fragPrevious = frag;\n this.tick();\n return;\n } else {\n logger.warn('Already backtracked on this fragment, appending with the gap');\n }\n } else {\n // Only reset the backtracked flag if we've loaded the frag without any dropped frames\n frag.backtracked = false;\n }\n }\n\n var drift = LevelHelper.updateFragPTSDTS(level.details,frag,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 [data.data1, data.data2].forEach(buffer => {\n // only append in PARSING state (rationale is that an appending error could happen synchronously on first segment appending)\n // in that case it is useless to append following segments\n if (buffer && buffer.length && this.state === State.PARSING) {\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 //trigger handler right now\n this.tick();\n }\n }\n\n onFragParsed(data) {\n const fragCurrent = this.fragCurrent;\n const fragNew = data.frag;\n if (fragCurrent &&\n data.id === 'main' &&\n fragNew.sn === fragCurrent.sn &&\n fragNew.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 const frag = this.fragCurrent;\n if (frag) {\n const media = this.mediaBuffer ? this.mediaBuffer : this.media;\n logger.log(`main buffered : ${TimeRanges.toString(media.buffered)}`);\n // filter fragments potentially evicted from buffer. this is to avoid memleak on live streams\n let bufferedFrags = this._bufferedFrags.filter(frag => {return BufferHelper.isBuffered(media,(frag.startPTS + frag.endPTS) / 2);});\n // push new range\n bufferedFrags.push(frag);\n // sort frags, as we use BinarySearch for lookup in getBufferedFrag ...\n this._bufferedFrags = bufferedFrags.sort(function(a,b) {return (a.startPTS - b.startPTS);});\n this.fragPrevious = frag;\n const stats = this.stats;\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 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 // switch error to fatal\n data.fatal = true;\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 // switch error to fatal\n data.fatal = true;\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 case of non fatal error while loading level, if level controller is not retrying to load level , switch back to IDLE\n if (!data.levelRetry && 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 (data.parent === 'main' && (this.state === State.PARSING || this.state === State.PARSED)) {\n // reduce max buf len if current position is buffered\n if (mediaBuffered) {\n this._reduceMaxBufferLength(this.config.maxBufferLength);\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/video-dev/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(`main:reduce max buffer length to ${config.maxMaxBufferLength}s`);\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 config = this.config;\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) {\n this.loadedmetadata = true;\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 = media.seeking ? currentTime : this.startPosition,\n startPositionBuffered = BufferHelper.isBuffered(mediaBuffer,startPosition),\n firstbufferedPosition = buffered.start(0);\n // if currentTime not matching with expected startPosition or startPosition not buffered\n if (currentTime !== startPosition ||\n (!startPositionBuffered && (Math.abs(startPosition-firstbufferedPosition) < config.maxSeekHole))) {\n logger.log(`target start position:${startPosition}`);\n // if startPosition not buffered, let's seek to buffered.start(0)\n if(!startPositionBuffered) {\n startPosition = firstbufferedPosition;\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 !== this.lastCurrentTime;\n\n if (playheadMoving) {\n // played moving, but was previously stalled => now not stuck anymore\n if (this.stallReported) {\n logger.warn(`playback not stuck anymore @${currentTime}, after ${Math.round(performance.now()-this.stalled)}ms`);\n this.stallReported = false;\n }\n this.stalled = undefined;\n this.nudgeRetry = 0;\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 this.stalled = tnow;\n this.stallReported = false;\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 const bufferLen = bufferInfo.len;\n let nudgeRetry = this.nudgeRetry || 0;\n // have we reached stall deadline ?\n if (bufferLen <= jumpThreshold && stalledDuration > config.lowBufferWatchdogPeriod * 1000) {\n // report stalled error once\n if (!this.stallReported) {\n this.stallReported = true;\n logger.warn(`playback stalling in low buffer @${currentTime}`);\n hls.trigger(Event.ERROR, {type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.BUFFER_STALLED_ERROR, fatal: false, buffer : bufferLen});\n }\n // if buffer len is below threshold, try to jump to start of next buffer range if close\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 this.nudgeRetry = ++nudgeRetry;\n const nudgeOffset = nudgeRetry * config.nudgeOffset;\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 media.currentTime = nextBufferStart + nudgeOffset;\n // reset stalled so to rearm watchdog timer\n this.stalled = undefined;\n hls.trigger(Event.ERROR, {type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.BUFFER_SEEK_OVER_HOLE, fatal: false, hole : nextBufferStart + nudgeOffset - currentTime});\n }\n } else if (bufferLen > jumpThreshold && stalledDuration > config.highBufferWatchdogPeriod * 1000) {\n // report stalled error once\n if (!this.stallReported) {\n this.stallReported = true;\n logger.warn(`playback stalling in high buffer @${currentTime}`);\n hls.trigger(Event.ERROR, {type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.BUFFER_STALLED_ERROR, fatal: false, buffer : bufferLen});\n }\n // reset stalled so to rearm watchdog timer\n this.stalled = undefined;\n this.nudgeRetry = ++nudgeRetry;\n if (nudgeRetry < config.nudgeMaxRetry) {\n const currentTime = media.currentTime;\n const targetTime = currentTime + nudgeRetry * config.nudgeOffset;\n logger.log(`adjust currentTime from ${currentTime} to ${targetTime}`);\n // playback stalled in buffered area ... let's nudge currentTime to try to overcome this\n media.currentTime = targetTime;\n hls.trigger(Event.ERROR, {type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.BUFFER_NUDGE_ON_STALL, fatal: false});\n } else {\n logger.error(`still stuck in high buffer @${currentTime} after ${config.nudgeMaxRetry}, raise fatal error`);\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 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, filter flushed fragments from bufferedFrags\n use mediaBuffered instead of media (so that we will check against video.buffered ranges in case of alt audio track)\n */\n const media = this.mediaBuffer ? this.mediaBuffer : this.media;\n this._bufferedFrags = this._bufferedFrags.filter(frag => {return BufferHelper.isBuffered(media,(frag.startPTS + frag.endPTS) / 2);});\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 * Subtitle Stream Controller\n*/\n\nimport Event from '../events';\nimport EventHandler from '../event-handler';\nimport {logger} from '../utils/logger';\n\nclass SubtitleStreamController extends EventHandler {\n\n constructor(hls) {\n super(hls,\n Event.ERROR,\n Event.SUBTITLE_TRACKS_UPDATED,\n Event.SUBTITLE_TRACK_SWITCH,\n Event.SUBTITLE_TRACK_LOADED,\n Event.SUBTITLE_FRAG_PROCESSED);\n this.config = hls.config;\n this.vttFragSNsProcessed = {};\n this.vttFragQueues = undefined;\n this.currentlyProcessing = null;\n this.currentTrackId = -1;\n }\n\n destroy() {\n EventHandler.prototype.destroy.call(this);\n }\n\n // Remove all queued items and create a new, empty queue for each track.\n clearVttFragQueues() {\n this.vttFragQueues = {};\n this.tracks.forEach(track => {\n this.vttFragQueues[track.id] = [];\n });\n }\n\n // If no frag is being processed and queue isn't empty, initiate processing of next frag in line.\n nextFrag() {\n if(this.currentlyProcessing === null && this.currentTrackId > -1 && this.vttFragQueues[this.currentTrackId].length) {\n let frag = this.currentlyProcessing = this.vttFragQueues[this.currentTrackId].shift();\n this.hls.trigger(Event.FRAG_LOADING, {frag});\n }\n }\n\n // When fragment has finished processing, add sn to list of completed if successful.\n onSubtitleFragProcessed(data) {\n if(data.success) {\n this.vttFragSNsProcessed[data.frag.trackId].push(data.frag.sn);\n }\n this.currentlyProcessing = null;\n this.nextFrag();\n }\n\n // If something goes wrong, procede to next frag, if we were processing one.\n onError(data) {\n let frag = data.frag;\n // don't handle frag error not related to subtitle fragment\n if (frag && frag.type !== 'subtitle') {\n return;\n }\n if(this.currentlyProcessing) {\n this.currentlyProcessing = null;\n this.nextFrag();\n }\n }\n\n // Got all new subtitle tracks.\n onSubtitleTracksUpdated(data) {\n logger.log('subtitle tracks updated');\n this.tracks = data.subtitleTracks;\n this.clearVttFragQueues();\n this.vttFragSNsProcessed = {};\n this.tracks.forEach(track => {\n this.vttFragSNsProcessed[track.id] = [];\n });\n }\n\n onSubtitleTrackSwitch(data) {\n this.currentTrackId = data.id;\n this.clearVttFragQueues();\n }\n\n // Got a new set of subtitle fragments.\n onSubtitleTrackLoaded(data) {\n const processedFragSNs = this.vttFragSNsProcessed[data.id],\n fragQueue = this.vttFragQueues[data.id],\n currentFragSN = !!this.currentlyProcessing ? this.currentlyProcessing.sn : -1;\n\n const alreadyProcessed = function(frag) {\n return processedFragSNs.indexOf(frag.sn) > -1;\n };\n\n const alreadyInQueue = function(frag) {\n return fragQueue.some(fragInQueue => {return fragInQueue.sn === frag.sn;});\n };\n\n // Add all fragments that haven't been, aren't currently being and aren't waiting to be processed, to queue.\n data.details.fragments.forEach(frag => {\n if(!(alreadyProcessed(frag) || frag.sn === currentFragSN || alreadyInQueue(frag))) {\n // Frags don't know their subtitle track ID, so let's just add that...\n frag.trackId = data.id;\n fragQueue.push(frag);\n }\n });\n\n this.nextFrag();\n }\n}\nexport default SubtitleStreamController;\n\n",
"/*\n * audio track controller\n*/\n\nimport Event from '../events';\nimport EventHandler from '../event-handler';\nimport {logger} from '../utils/logger';\n\nfunction filterSubtitleTracks(textTrackList) {\n let tracks = [];\n for (let i = 0; i < textTrackList.length; i++) {\n if (textTrackList[i].kind === 'subtitles') {\n tracks.push(textTrackList[i]);\n }\n }\n return tracks;\n}\n\nclass SubtitleTrackController extends EventHandler {\n\n constructor(hls) {\n super(hls,\n Event.MEDIA_ATTACHED,\n Event.MEDIA_DETACHING,\n Event.MANIFEST_LOADING,\n Event.MANIFEST_LOADED,\n Event.SUBTITLE_TRACK_LOADED);\n this.tracks = [];\n this.trackId = -1;\n this.media = undefined;\n }\n\n _onTextTracksChanged() {\n // Media is undefined when switching streams via loadSource()\n if (!this.media) {\n return;\n }\n\n let trackId = -1;\n let tracks = filterSubtitleTracks(this.media.textTracks);\n for (let id = 0; id < tracks.length; id++) {\n if (tracks[id].mode === 'showing') {\n trackId = id;\n }\n }\n\n // Setting current subtitleTrack will invoke code.\n this.subtitleTrack = trackId;\n }\n\n destroy() {\n EventHandler.prototype.destroy.call(this);\n }\n\n // Listen for subtitle track change, then extract the current track ID.\n onMediaAttached(data) {\n this.media = data.media;\n if (!this.media) {\n return;\n }\n\n this.trackChangeListener = this._onTextTracksChanged.bind(this);\n this.media.textTracks.addEventListener('change', this.trackChangeListener);\n }\n\n onMediaDetaching() {\n if (!this.media) {\n return;\n }\n\n this.media.textTracks.removeEventListener('change', this.trackChangeListener);\n\n this.media = undefined;\n }\n\n // Reset subtitle tracks on manifest loading\n onManifestLoading() {\n this.tracks = [];\n this.trackId = -1;\n }\n\n // Fired whenever a new manifest is loaded.\n onManifestLoaded(data) {\n let tracks = data.subtitles || [];\n let defaultFound = false;\n this.tracks = tracks;\n this.trackId = -1;\n this.hls.trigger(Event.SUBTITLE_TRACKS_UPDATED, {subtitleTracks : tracks});\n\n // loop through available subtitle tracks and autoselect default if needed\n // TODO: improve selection logic to handle forced, etc\n tracks.forEach(track => {\n if (track.default) {\n this.subtitleTrack = track.id;\n defaultFound = true;\n }\n });\n }\n\n // Trigger subtitle track playlist reload.\n onTick() {\n const trackId = this.trackId;\n const subtitleTrack = this.tracks[trackId];\n if (!subtitleTrack) {\n return;\n }\n\n const details = subtitleTrack.details;\n // check if we need to load playlist for this subtitle Track\n if (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 subtitle track ${trackId}`);\n this.hls.trigger(Event.SUBTITLE_TRACK_LOADING, {url: subtitleTrack.url, id: trackId});\n }\n }\n\n onSubtitleTrackLoaded(data) {\n if (data.id < this.tracks.length) {\n logger.log(`subtitle track ${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(() => {\n this.onTick();\n }, 1000 * data.details.targetduration, this);\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 subtitle tracks list from playlist **/\n get subtitleTracks() {\n return this.tracks;\n }\n\n /** get index of the selected subtitle track (index in subtitle track lists) **/\n get subtitleTrack() {\n return this.trackId;\n }\n\n /** select a subtitle track, based on its index in subtitle track lists**/\n set subtitleTrack(subtitleTrackId) {\n if (this.trackId !== subtitleTrackId) {// || this.tracks[subtitleTrackId].details === undefined) {\n this.setSubtitleTrackInternal(subtitleTrackId);\n }\n }\n\n setSubtitleTrackInternal(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 subtitle track ${newId}`);\n let subtitleTrack = this.tracks[newId];\n this.hls.trigger(Event.SUBTITLE_TRACK_SWITCH, {id: newId});\n // check if we need to load playlist for this subtitle Track\n let details = subtitleTrack.details;\n if (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 subtitle track ${newId}`);\n this.hls.trigger(Event.SUBTITLE_TRACK_LOADING, {url: subtitleTrack.url, id: newId});\n }\n }\n }\n}\n\nexport default SubtitleTrackController;\n",
"/*\n * Timeline Controller\n*/\n\nimport Event from '../events';\nimport EventHandler from '../event-handler';\nimport Cea608Parser from '../utils/cea-608-parser';\nimport WebVTTParser from '../utils/webvtt-parser';\nimport {logger} from '../utils/logger';\n\nfunction clearCurrentCues(track) {\n if (track && track.cues) {\n while (track.cues.length > 0) {\n track.removeCue(track.cues[0]);\n }\n }\n}\n\nfunction reuseVttTextTrack(inUseTrack, manifestTrack) {\n return inUseTrack && inUseTrack.label === manifestTrack.name && !(inUseTrack.textTrack1 || inUseTrack.textTrack2);\n}\n\nfunction intersection(x1, x2, y1, y2) {\n return Math.min(x2, y2) - Math.max(x1, y1);\n}\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.MANIFEST_LOADED,\n Event.FRAG_LOADED,\n Event.LEVEL_SWITCHING,\n Event.INIT_PTS_FOUND);\n\n this.hls = hls;\n this.config = hls.config;\n this.enabled = true;\n this.Cues = hls.config.cueHandler;\n this.textTracks = [];\n this.tracks = [];\n this.unparsedVttFrags = [];\n this.initPTS = undefined;\n this.cueRanges = [];\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 const textTrack1 = self.createTextTrack('captions', self.config.captionsTextTrack1Label, self.config.captionsTextTrack1LanguageCode);\n if (textTrack1) {\n textTrack1.textTrack1 = true;\n self.textTrack1 = textTrack1;\n }\n }\n else\n {\n self.textTrack1 = existingTrack1;\n clearCurrentCues(self.textTrack1);\n\n sendAddTrackEvent(self.textTrack1, self.media);\n }\n }\n self.addCues('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 const textTrack2 = self.createTextTrack('captions', self.config.captionsTextTrack2Label, self.config.captionsTextTrack1LanguageCode);\n if (textTrack2) {\n textTrack2.textTrack2 = true;\n self.textTrack2 = textTrack2;\n }\n }\n else\n {\n self.textTrack2 = existingTrack2;\n clearCurrentCues(self.textTrack2);\n\n sendAddTrackEvent(self.textTrack2, self.media);\n }\n }\n self.addCues('textTrack2', startTime, endTime, screen);\n }\n };\n\n this.cea608Parser = new Cea608Parser(0, channel1, channel2);\n }\n }\n\n addCues(channel, startTime, endTime, screen) {\n // skip cues which overlap more than 50% with previously parsed time ranges\n const ranges = this.cueRanges;\n let merged = false;\n for (let i = ranges.length; i--;) {\n let cueRange = ranges[i];\n let overlap = intersection(cueRange[0], cueRange[1], startTime, endTime);\n if (overlap >= 0) {\n cueRange[0] = Math.min(cueRange[0], startTime);\n cueRange[1] = Math.max(cueRange[1], endTime);\n merged = true;\n if ((overlap / (endTime - startTime)) > 0.5) {\n return;\n }\n }\n }\n if (!merged) {\n ranges.push([startTime, endTime]);\n }\n this.Cues.newCue(this[channel], startTime, endTime, screen);\n }\n\n // Triggered when an initial PTS is found; used for synchronisation of WebVTT.\n onInitPtsFound(data) {\n if (typeof this.initPTS === 'undefined') {\n this.initPTS = data.initPTS;\n }\n\n // Due to asynchrony, initial PTS may arrive later than the first VTT fragments are loaded.\n // Parse any unparsed fragments upon receiving the initial PTS.\n if (this.unparsedVttFrags.length) {\n this.unparsedVttFrags.forEach(frag => {\n this.onFragLoaded(frag);\n });\n this.unparsedVttFrags = [];\n }\n }\n\n getExistingTrack(channelNumber) {\n const media = this.media;\n if (media) {\n for (let i = 0; i < media.textTracks.length; i++) {\n let textTrack = media.textTracks[i];\n let propName = 'textTrack' + channelNumber;\n if (textTrack[propName] === true) {\n return textTrack;\n }\n }\n }\n return null;\n }\n\n createTextTrack(kind, label, lang) {\n const media = this.media;\n if (media)\n {\n return 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 clearCurrentCues(this.textTrack1);\n clearCurrentCues(this.textTrack2);\n }\n\n onManifestLoading()\n {\n this.lastSn = -1; // Detect discontiguity in fragment parsing\n this.prevCC = -1;\n this.vttCCs = {ccOffset: 0, presentationOffset: 0}; // Detect discontinuity in subtitle manifests\n\n // clear outdated subtitles\n const media = this.media;\n if (media) {\n const textTracks = media.textTracks;\n if (textTracks) {\n for (let i = 0; i < textTracks.length; i++) {\n clearCurrentCues(textTracks[i]);\n }\n }\n }\n }\n\n onManifestLoaded(data) {\n this.textTracks = [];\n this.unparsedVttFrags = this.unparsedVttFrags || [];\n this.initPTS = undefined;\n this.cueRanges = [];\n\n if (this.config.enableWebVTT) {\n this.tracks = data.subtitles || [];\n const inUseTracks = this.media ? this.media.textTracks : [];\n\n this.tracks.forEach((track, index) => {\n let textTrack;\n if (index < inUseTracks.length) {\n const inUseTrack = inUseTracks[index];\n // Reuse tracks with the same label, but do not reuse 608/708 tracks\n if (reuseVttTextTrack(inUseTrack, track)) {\n textTrack = inUseTrack;\n }\n }\n if (!textTrack) {\n textTrack = this.createTextTrack('subtitles', track.name, track.lang);\n }\n textTrack.mode = track.default ? 'showing' : 'hidden';\n this.textTracks.push(textTrack);\n });\n }\n }\n\n onLevelSwitching() {\n this.enabled = this.hls.currentLevel.closedCaptions !== 'NONE';\n }\n\n onFragLoaded(data) {\n let frag = data.frag,\n payload = data.payload;\n if (frag.type === 'main') {\n var sn = frag.sn;\n // if this frag isn't contiguous, clear the parser so cues with bad start/end times aren't added to the textTrack\n if (sn !== this.lastSn + 1) {\n const cea608Parser = this.cea608Parser;\n if (cea608Parser) {\n cea608Parser.reset();\n }\n }\n this.lastSn = sn;\n }\n // If fragment is subtitle type, parse as WebVTT.\n else if (frag.type === 'subtitle') {\n if (payload.byteLength) {\n // We need an initial synchronisation PTS. Store fragments as long as none has arrived.\n if (typeof this.initPTS === 'undefined') {\n this.unparsedVttFrags.push(data);\n return;\n }\n let vttCCs = this.vttCCs;\n if (!vttCCs[frag.cc]) {\n vttCCs[frag.cc] = { start: frag.start, prevCC: this.prevCC, new: true };\n this.prevCC = frag.cc;\n }\n let textTracks = this.textTracks,\n hls = this.hls;\n\n // Parse the WebVTT file contents.\n WebVTTParser.parse(payload, this.initPTS, vttCCs, frag.cc, function (cues) {\n const currentTrack = textTracks[frag.trackId];\n // Add cues and trigger event with success true.\n cues.forEach(cue => {\n // Sometimes there are cue overlaps on segmented vtts so the same\n // cue can appear more than once in different vtt files.\n // This avoid showing duplicated cues with same timecode and text.\n if (!currentTrack.cues.getCueById(cue.id)) {\n try {\n currentTrack.addCue(cue);\n } catch (err) {\n const textTrackCue = new window.TextTrackCue(cue.startTime, cue.endTime, cue.text);\n textTrackCue.id = cue.id;\n currentTrack.addCue(textTrackCue);\n }\n }\n });\n hls.trigger(Event.SUBTITLE_FRAG_PROCESSED, {success: true, frag: frag});\n },\n function (e) {\n // Something went wrong while parsing. Trigger event with success false.\n logger.log(`Failed to parse VTT cue: ${e}`);\n hls.trigger(Event.SUBTITLE_FRAG_PROCESSED, {success: false, frag: frag});\n });\n }\n else {\n // In case there is no payload, finish unsuccessfully.\n this.hls.trigger(Event.SUBTITLE_FRAG_PROCESSED, {success: false, frag: frag});\n }\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 for (var i=0; i<data.samples.length; i++) {\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 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;\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 this.subMix = [new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)];\n this.invSubMix = [new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)];\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 < 4; 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 subMix = this.subMix;\n let subMix0 = subMix[0];\n let subMix1 = subMix[1];\n let subMix2 = subMix[2];\n let subMix3 = subMix[3];\n let invSubMix = this.invSubMix;\n let invSubMix0 = invSubMix[0];\n let invSubMix1 = invSubMix[1];\n let invSubMix2 = invSubMix[2];\n let invSubMix3 = 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(ksRows);\n let invKeySchedule = this.invKeySchedule = new Uint32Array(ksRows);\n let sbox = this.sBox;\n let rcon = this.rcon;\n\n let invSubMix = this.invSubMix;\n let invSubMix0 = invSubMix[0];\n let invSubMix1 = invSubMix[1];\n let invSubMix2 = invSubMix[2];\n let invSubMix3 = 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 invSubMix = this.invSubMix;\n let invSubMix0 = invSubMix[0];\n let invSubMix1 = invSubMix[1];\n let invSubMix2 = invSubMix[2];\n let invSubMix3 = 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 let swapWord = this.networkToHostOrderSwap;\n\n while (offset < inputInt32.length) {\n inputWords0 = swapWord(inputInt32[offset]);\n inputWords1 = swapWord(inputInt32[offset + 1]);\n inputWords2 = swapWord(inputInt32[offset + 2]);\n inputWords3 = swapWord(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] = swapWord(t0 ^ initVector0);\n outputInt32[offset + 1] = swapWord(t3 ^ initVector1);\n outputInt32[offset + 2] = swapWord(t2 ^ initVector2);\n outputInt32[offset + 3] = swapWord(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\n/*globals self: false */\n\nclass Decrypter {\n constructor(observer,config) {\n this.observer = observer;\n this.config = config;\n this.logEnabled = true;\n try {\n const browserCrypto = crypto ? crypto : self.crypto;\n this.subtle = browserCrypto.subtle || browserCrypto.webkitSubtle;\n } catch (e) {}\n this.disableWebCrypto = !this.subtle;\n }\n\n isSync() {\n return (this.disableWebCrypto && this.config.enableSoftwareAES);\n }\n\n decrypt(data, key, iv, callback) {\n if (this.disableWebCrypto && this.config.enableSoftwareAES) {\n if (this.logEnabled) {\n logger.log('JS AES decrypt');\n this.logEnabled = false;\n }\n let decryptor = this.decryptor;\n if (!decryptor) {\n this.decryptor = decryptor = new AESDecryptor();\n }\n decryptor.expandKey(key);\n callback(decryptor.decrypt(data, 0, iv));\n }\n else {\n if (this.logEnabled) {\n logger.log('WebCrypto AES decrypt');\n this.logEnabled = false;\n }\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 catch ((err) => {\n this.onWebCryptoError(err, data, key, iv, callback);\n }).\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 if (this.config.enableSoftwareAES) {\n logger.log('WebCrypto Error, disable WebCrypto API');\n this.disableWebCrypto = true;\n this.logEnabled = true;\n this.decrypt(data, key, iv, callback);\n }\n else {\n logger.error(`decrypting error : ${err.message}`);\n this.observer.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\nclass AACDemuxer {\n\n constructor(observer, remuxer, config) {\n this.observer = observer;\n this.config = config;\n this.remuxer = remuxer;\n }\n\n resetInitSegment(initSegment, audioCodec, videoCodec, duration) {\n this._audioTrack = { container: 'audio/adts', type: 'audio', id: -1, sequenceNumber: 0, isAAC: true, samples: [], len: 0, manifestCodec: audioCodec, duration: duration, inputTimeScale: 90000 };\n }\n\n resetTimeStamp() {\n }\n\n static probe(data) {\n // check if data contains ID3 timestamp and ADTS sync word\n var offset, length;\n let id3Data = ID3.getID3Data(data, 0);\n if (id3Data && ID3.getTimeStamp(id3Data) !== undefined) {\n // Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1\n // Layer bits (position 14 and 15) in header should be always 0 for ADTS\n // More info https://wiki.multimedia.cx/index.php?title=ADTS\n for (offset = id3Data.length, length = Math.min(data.length - 1, offset + 100); offset < length; offset++) {\n if (ADTS.probe(data, offset)) {\n logger.log('ADTS sync word found !');\n return true;\n }\n }\n }\n return false;\n }\n\n // feed incoming data to the front of the parsing pipeline\n append(data, timeOffset, contiguous, accurateTimeOffset) {\n var track = this._audioTrack,\n id3Data = ID3.getID3Data(data, 0),\n pts = 90 * ID3.getTimeStamp(id3Data),\n frameIndex = 0,\n stamp = pts,\n length = data.length,\n offset = id3Data.length;\n\n let id3Samples = [{ pts: stamp, dts: stamp, data: id3Data }];\n\n while (offset < length - 1) {\n if (ADTS.isHeader(data, offset) && (offset + 5) < length) {\n ADTS.initTrackConfig(track, this.observer, data, offset, track.manifestCodec);\n var frame = ADTS.appendFrame(track, data, offset, pts, frameIndex);\n if (frame) {\n offset += frame.length;\n stamp = frame.sample.pts;\n frameIndex++;\n } else {\n logger.log('Unable to parse AAC frame');\n break;\n }\n } else if (ID3.isHeader(data, offset)) {\n id3Data = ID3.getID3Data(data, offset);\n id3Samples.push({ pts: stamp, dts: stamp, data: id3Data });\n offset += id3Data.length;\n } else {\n //nothing found, keep looking\n offset++;\n }\n }\n\n this.remuxer.remux(track,\n { samples: [] },\n { samples: id3Samples, inputTimeScale: 90000 },\n { samples: [] },\n timeOffset,\n contiguous,\n accurateTimeOffset);\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\nconst ADTS = {\n getAudioConfig: function (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: freq less than 24kHz = AAC SBR (HE-AAC)\n if (/firefox/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/Opera ...)\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 /vivaldi/i.test(userAgent)) ||\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 return { config: config, samplerate: adtsSampleingRates[adtsSampleingIndex], channelCount: adtsChanelConfig, codec: ('mp4a.40.' + adtsObjectType), manifestCodec: manifestCodec };\n },\n\n isHeaderPattern: function (data, offset) {\n return data[offset] === 0xff && (data[offset + 1] & 0xf6) === 0xf0;\n },\n\n getHeaderLength: function (data, offset) {\n return (!!(data[offset + 1] & 0x01) ? 7 : 9);\n },\n\n getFullFrameLength: function (data, offset) {\n return ((data[offset + 3] & 0x03) << 11) |\n (data[offset + 4] << 3) |\n ((data[offset + 5] & 0xE0) >>> 5);\n },\n\n isHeader: function (data, offset) {\n // Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1\n // Layer bits (position 14 and 15) in header should be always 0 for ADTS\n // More info https://wiki.multimedia.cx/index.php?title=ADTS\n if (offset + 1 < data.length && this.isHeaderPattern(data, offset)) {\n return true;\n }\n return false;\n },\n\n probe: function (data, offset) {\n // same as isHeader but we also check that ADTS frame follows last ADTS frame\n // or end of data is reached\n if (offset + 1 < data.length && this.isHeaderPattern(data, offset)) {\n // ADTS header Length\n let headerLength = this.getHeaderLength(data, offset);\n // ADTS frame Length\n let frameLength = headerLength;\n if (offset + 5 < data.length) {\n frameLength = this.getFullFrameLength(data, offset);\n }\n let newOffset = offset + frameLength;\n if (newOffset === data.length || (newOffset + 1 < data.length && this.isHeaderPattern(data, newOffset))) {\n return true;\n }\n }\n return false;\n },\n\n initTrackConfig: function (track, observer, data, offset, audioCodec) {\n if (!track.samplerate) {\n var config = this.getAudioConfig(observer, data, offset, audioCodec);\n track.config = config.config;\n track.samplerate = config.samplerate;\n track.channelCount = config.channelCount;\n track.codec = config.codec;\n track.manifestCodec = config.manifestCodec;\n logger.log(`parsed codec:${track.codec},rate:${config.samplerate},nb channel:${config.channelCount}`);\n }\n },\n\n getFrameDuration: function (samplerate) {\n return 1024 * 90000 / samplerate;\n },\n\n appendFrame: function (track, data, offset, pts, frameIndex) {\n var frameDuration = this.getFrameDuration(track.samplerate);\n var header = this.parseFrameHeader(data, offset, pts, frameIndex, frameDuration);\n if (header) {\n var stamp = header.stamp;\n var headerLength = header.headerLength;\n var frameLength = header.frameLength;\n\n //logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}/${(stamp/90).toFixed(0)}`);\n var aacSample = { unit: data.subarray(offset + headerLength, offset + headerLength + frameLength), pts: stamp, dts: stamp };\n\n track.samples.push(aacSample);\n track.len += frameLength;\n\n return { sample: aacSample, length: frameLength + headerLength };\n }\n\n return undefined;\n },\n\n parseFrameHeader: function (data, offset, pts, frameIndex, frameDuration) {\n var headerLength, frameLength, stamp;\n var length = data.length;\n\n // The protection skip bit tells us if we have 2 bytes of CRC data at the end of the ADTS header\n headerLength = this.getHeaderLength(data, offset);\n // retrieve frame size\n frameLength = this.getFullFrameLength(data, offset);\n frameLength -= headerLength;\n\n if ((frameLength > 0) && ((offset + headerLength + frameLength) <= length)) {\n stamp = pts + frameIndex * frameDuration;\n //logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}/${(stamp/90).toFixed(0)}`);\n return { headerLength, frameLength, stamp };\n }\n\n return undefined;\n }\n};\n\nmodule.exports = ADTS;",
"/* 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 Decrypter from '../crypt/decrypter';\nimport AACDemuxer from '../demux/aacdemuxer';\nimport MP4Demuxer from '../demux/mp4demuxer';\nimport TSDemuxer from '../demux/tsdemuxer';\nimport MP3Demuxer from '../demux/mp3demuxer';\nimport MP4Remuxer from '../remux/mp4-remuxer';\nimport PassThroughRemuxer from '../remux/passthrough-remuxer';\n\nclass DemuxerInline {\n\n constructor(observer, typeSupported, config, vendor) {\n this.observer = observer;\n this.typeSupported = typeSupported;\n this.config = config;\n this.vendor = vendor;\n }\n\n destroy() {\n var demuxer = this.demuxer;\n if (demuxer) {\n demuxer.destroy();\n }\n }\n\n push(data, decryptdata, initSegment, audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS) {\n if ((data.byteLength > 0) && (decryptdata != null) && (decryptdata.key != null) && (decryptdata.method === 'AES-128')) {\n let decrypter = this.decrypter;\n if (decrypter == null) {\n decrypter = this.decrypter = new Decrypter(this.observer, this.config);\n }\n var localthis = this;\n // performance.now() not available on WebWorker, at least on Safari Desktop\n var startTime;\n try {\n startTime = performance.now();\n } catch (error) {\n startTime = Date.now();\n }\n decrypter.decrypt(data, decryptdata.key.buffer, decryptdata.iv.buffer, function (decryptedData) {\n var endTime;\n try {\n endTime = performance.now();\n } catch (error) {\n endTime = Date.now();\n }\n localthis.observer.trigger(Event.FRAG_DECRYPTED, { stats: { tstart: startTime, tdecrypt: endTime } });\n localthis.pushDecrypted(new Uint8Array(decryptedData), decryptdata, new Uint8Array(initSegment), audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS);\n });\n } else {\n this.pushDecrypted(new Uint8Array(data), decryptdata, new Uint8Array(initSegment), audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS);\n }\n }\n\n pushDecrypted(data, decryptdata, initSegment, audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, 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 (discontinuity && !this.probe(data))) {\n const observer = this.observer;\n const typeSupported = this.typeSupported;\n const config = this.config;\n // probing order is AAC/MP3/TS/MP4\n const muxConfig = [{ demux: AACDemuxer, remux: MP4Remuxer },\n { demux: MP3Demuxer, remux: MP4Remuxer },\n { demux: TSDemuxer, remux: MP4Remuxer },\n { demux: MP4Demuxer, remux: PassThroughRemuxer }];\n\n // probe for content type\n for (let i = 0, len = muxConfig.length; i < len; i++) {\n const mux = muxConfig[i];\n const probe = mux.demux.probe;\n if (probe(data)) {\n const remuxer = this.remuxer = new mux.remux(observer, config, typeSupported, this.vendor);\n demuxer = new mux.demux(observer, remuxer, config, typeSupported);\n this.probe = probe;\n break;\n }\n }\n if (!demuxer) {\n observer.trigger(Event.ERROR, { type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.FRAG_PARSING_ERROR, fatal: true, reason: 'no demux matching with content found' });\n return;\n }\n this.demuxer = demuxer;\n }\n const remuxer = this.remuxer;\n\n if (discontinuity || trackSwitch) {\n demuxer.resetInitSegment(initSegment, audioCodec, videoCodec, duration);\n remuxer.resetInitSegment();\n }\n if (discontinuity) {\n demuxer.resetTimeStamp(defaultInitPTS);\n remuxer.resetTimeStamp(defaultInitPTS);\n }\n if (typeof demuxer.setDecryptData === 'function') {\n demuxer.setDecryptData(decryptdata);\n }\n demuxer.append(data, timeOffset, contiguous, accurateTimeOffset);\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.typeSupported, config, data.vendor);\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(data.data, data.decryptdata, data.initSegment, data.audioCodec, data.videoCodec, data.timeOffset,data.discontinuity, data.trackSwitch,data.contiguous,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_DECRYPTED, forwardMessage);\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 transferable = [];\n let message = {event: ev, data:data};\n if (data.data1) {\n message.data1 = data.data1.buffer;\n transferable.push(data.data1.buffer);\n delete data.data1;\n }\n if (data.data2) {\n message.data2 = data.data2.buffer;\n transferable.push(data.data2.buffer);\n delete data.data2;\n }\n self.postMessage(message,transferable);\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 {ErrorTypes, ErrorDetails} from '../errors';\nimport EventEmitter from 'events';\n\nclass Demuxer {\n\n constructor(hls, id) {\n this.hls = hls;\n this.id = id;\n // observer setup\n const observer = this.observer = new EventEmitter();\n const config = hls.config;\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 data = data || {};\n data.frag = this.frag;\n data.id = this.id;\n hls.trigger(ev,data);\n }.bind(this);\n\n // forward events to main thread\n observer.on(Event.FRAG_DECRYPTED, forwardMessage);\n observer.on(Event.FRAG_PARSING_INIT_SEGMENT, forwardMessage);\n observer.on(Event.FRAG_PARSING_DATA, 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 const typeSupported = {\n mp4 : MediaSource.isTypeSupported('video/mp4'),\n mpeg: MediaSource.isTypeSupported('audio/mpeg'),\n mp3: MediaSource.isTypeSupported('audio/mp4; codecs=\"mp3\"')\n };\n // navigator.vendor is not always available in Web Worker\n // refer to https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/navigator\n const vendor = navigator.vendor;\n if (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, vendor : vendor, id : id, config: JSON.stringify(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(observer,typeSupported,config,vendor);\n this.w = undefined;\n }\n } else {\n this.demuxer = new DemuxerInline(observer,typeSupported,config, vendor);\n }\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 observer = this.observer;\n if (observer) {\n observer.removeAllListeners();\n this.observer = null;\n }\n }\n\n push(data, initSegment, audioCodec, videoCodec, frag, duration,accurateTimeOffset,defaultInitPTS) {\n const w = this.w;\n const timeOffset = !isNaN(frag.startDTS) ? frag.startDTS : frag.start;\n const decryptdata = frag.decryptdata;\n const lastFrag = this.frag;\n const discontinuity = !(lastFrag && (frag.cc === lastFrag.cc));\n const trackSwitch = !(lastFrag && (frag.level === lastFrag.level));\n const nextSN = lastFrag && (frag.sn === (lastFrag.sn+1));\n const contiguous = !trackSwitch && nextSN;\n if (discontinuity) {\n logger.log(`${this.id}:discontinuity detected`);\n }\n if (trackSwitch) {\n logger.log(`${this.id}:switch detected`);\n }\n this.frag = frag;\n if (w) {\n // post fragment payload as transferable objects (no copy)\n w.postMessage({cmd: 'demux', data, decryptdata, initSegment, audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset,defaultInitPTS}, [data]);\n } else {\n let demuxer = this.demuxer;\n if (demuxer) {\n demuxer.push(data, decryptdata, initSegment, audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset,defaultInitPTS);\n }\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 if (data.data2) {\n data.data.data2 = new Uint8Array(data.data2);\n }\n /* falls through */\n default:\n data.data = data.data || {};\n data.data.frag = this.frag;\n data.data.id = this.id;\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 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 let pixelRatio = [1,1];\n if (readBoolean()) {\n // vui_parameters_present_flag\n if (readBoolean()) {\n // aspect_ratio_info_present_flag\n const aspectRatioIdc = readUByte();\n switch (aspectRatioIdc) {\n case 1: pixelRatio = [1,1]; break;\n case 2: pixelRatio = [12,11]; break;\n case 3: pixelRatio = [10,11]; break;\n case 4: pixelRatio = [16,11]; break;\n case 5: pixelRatio = [40,33]; break;\n case 6: pixelRatio = [24,11]; break;\n case 7: pixelRatio = [20,11]; break;\n case 8: pixelRatio = [32,11]; break;\n case 9: pixelRatio = [80,33]; break;\n case 10: pixelRatio = [18,11]; break;\n case 11: pixelRatio = [15,11]; break;\n case 12: pixelRatio = [64,33]; break;\n case 13: pixelRatio = [160,99]; break;\n case 14: pixelRatio = [4,3]; break;\n case 15: pixelRatio = [3,2]; break;\n case 16: pixelRatio = [2,1]; break;\n case 255: {\n pixelRatio = [readUByte() << 8 | readUByte(), readUByte() << 8 | readUByte()];\n break;\n }\n }\n }\n }\n return {\n width: Math.ceil((((picWidthInMbsMinus1 + 1) * 16) - frameCropLeftOffset * 2 - frameCropRightOffset * 2)),\n height: ((2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16) - ((frameMbsOnlyFlag? 2 : 4) * (frameCropTopOffset + frameCropBottomOffset)),\n pixelRatio : pixelRatio\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 */\n class ID3 {\n /**\n * Returns true if an ID3 header can be found at offset in data\n * @param {Uint8Array} data - The data to search in\n * @param {number} offset - The offset at which to start searching\n * @return {boolean} - True if an ID3 header is found\n */\n static isHeader(data, offset) {\n /*\n * http://id3.org/id3v2.3.0\n * [0] = 'I'\n * [1] = 'D'\n * [2] = '3'\n * [3,4] = {Version}\n * [5] = {Flags}\n * [6-9] = {ID3 Size}\n *\n * An ID3v2 tag can be detected with the following pattern:\n * $49 44 33 yy yy xx zz zz zz zz\n * Where yy is less than $FF, xx is the 'flags' byte and zz is less than $80\n */\n if (offset + 10 <= data.length) {\n //look for 'ID3' identifier\n if (data[offset] === 0x49 && data[offset+1] === 0x44 && data[offset+2] === 0x33) {\n //check version is within range\n if (data[offset+3] < 0xFF && data[offset+4] < 0xFF) {\n //check size is within range\n if (data[offset+6] < 0x80 && data[offset+7] < 0x80 && data[offset+8] < 0x80 && data[offset+9] < 0x80) {\n return true;\n }\n }\n }\n }\n\n return false;\n }\n\n /**\n * Returns true if an ID3 footer can be found at offset in data\n * @param {Uint8Array} data - The data to search in\n * @param {number} offset - The offset at which to start searching\n * @return {boolean} - True if an ID3 footer is found\n */\n static isFooter(data, offset) {\n /*\n * The footer is a copy of the header, but with a different identifier\n */\n if (offset + 10 <= data.length) {\n //look for '3DI' identifier\n if (data[offset] === 0x33 && data[offset+1] === 0x44 && data[offset+2] === 0x49) {\n //check version is within range\n if (data[offset+3] < 0xFF && data[offset+4] < 0xFF) {\n //check size is within range\n if (data[offset+6] < 0x80 && data[offset+7] < 0x80 && data[offset+8] < 0x80 && data[offset+9] < 0x80) {\n return true;\n }\n }\n }\n }\n\n return false;\n }\n\n /**\n * Returns any adjacent ID3 tags found in data starting at offset, as one block of data\n * @param {Uint8Array} data - The data to search in\n * @param {number} offset - The offset at which to start searching\n * @return {Uint8Array} - The block of data containing any ID3 tags found\n */\n static getID3Data(data, offset) {\n const front = offset;\n let length = 0;\n\n while (ID3.isHeader(data, offset)) {\n //ID3 header is 10 bytes\n length += 10;\n\n const size = ID3._readSize(data, offset + 6);\n length += size;\n\n if (ID3.isFooter(data, offset + 10)) {\n //ID3 footer is 10 bytes\n length += 10;\n }\n\n offset += length;\n }\n\n if (length > 0) {\n return data.subarray(front, front + length);\n }\n\n return undefined;\n }\n\n static _readSize(data, offset) {\n let size = 0;\n size = ((data[offset] & 0x7f) << 21);\n size |= ((data[offset+1] & 0x7f) << 14);\n size |= ((data[offset+2] & 0x7f) << 7);\n size |= (data[offset+3] & 0x7f);\n return size;\n }\n\n /**\n * Searches for the Elementary Stream timestamp found in the ID3 data chunk\n * @param {Uint8Array} data - Block of data containing one or more ID3 tags\n * @return {number} - The timestamp\n */\n static getTimeStamp(data) {\n const frames = ID3.getID3Frames(data);\n for(let i = 0; i < frames.length; i++) {\n const frame = frames[i];\n if (ID3.isTimeStampFrame(frame)) {\n return ID3._readTimeStamp(frame);\n }\n }\n\n return undefined;\n }\n\n /**\n * Returns true if the ID3 frame is an Elementary Stream timestamp frame\n * @param {ID3 frame} frame\n */\n static isTimeStampFrame(frame) {\n return (frame && frame.key === 'PRIV' && frame.info === 'com.apple.streaming.transportStreamTimestamp');\n }\n\n static _getFrameData(data) {\n /*\n Frame ID $xx xx xx xx (four characters)\n Size $xx xx xx xx\n Flags $xx xx\n */\n const type = String.fromCharCode(data[0], data[1], data[2], data[3]);\n const size = ID3._readSize(data, 4);\n\n //skip frame id, size, and flags\n let offset = 10;\n\n return { type, size, data: data.subarray(offset, offset + size) };\n }\n\n /**\n * Returns an array of ID3 frames found in all the ID3 tags in the id3Data\n * @param {Uint8Array} id3Data - The ID3 data containing one or more ID3 tags\n * @return {ID3 frame[]} - Array of ID3 frame objects\n */\n static getID3Frames(id3Data) {\n let offset = 0;\n const frames = [];\n\n while (ID3.isHeader(id3Data, offset)) {\n const size = ID3._readSize(id3Data, offset + 6);\n //skip past ID3 header\n offset += 10;\n const end = offset + size;\n //loop through frames in the ID3 tag\n while (offset + 8 < end) {\n const frameData = ID3._getFrameData(id3Data.subarray(offset));\n const frame = ID3._decodeFrame(frameData);\n if (frame) {\n frames.push(frame);\n }\n //skip frame header and frame data\n offset += frameData.size + 10;\n }\n\n if (ID3.isFooter(id3Data, offset)) {\n offset += 10;\n }\n }\n\n return frames;\n }\n\n static _decodeFrame(frame) {\n if (frame.type === 'PRIV') {\n return ID3._decodePrivFrame(frame);\n } else if (frame.type[0] === 'T') {\n return ID3._decodeTextFrame(frame);\n } else if (frame.type[0] === 'W') {\n return ID3._decodeURLFrame(frame);\n }\n\n return undefined;\n }\n\n static _readTimeStamp(timeStampFrame) {\n if (timeStampFrame.data.byteLength === 8) {\n const data = new Uint8Array(timeStampFrame.data);\n // timestamp is 33 bit expressed as a big-endian eight-octet number,\n // with the upper 31 bits set to zero.\n const pts33Bit = data[3] & 0x1;\n let timestamp = (data[4] << 23) +\n (data[5] << 15) +\n (data[6] << 7) +\n data[7];\n timestamp /= 45;\n\n if (pts33Bit) {\n timestamp += 47721858.84; // 2^32 / 90\n }\n\n return Math.round(timestamp);\n }\n\n return undefined;\n }\n\n static _decodePrivFrame(frame) {\n /*\n Format: <text string>\\0<binary data>\n */\n if (frame.size < 2) {\n return undefined;\n }\n\n const owner = ID3._utf8ArrayToStr(frame.data);\n const privateData = new Uint8Array(frame.data.subarray(owner.length + 1));\n\n return { key: frame.type, info: owner, data: privateData.buffer };\n }\n\n static _decodeTextFrame(frame) {\n if (frame.size < 2) {\n return undefined;\n }\n\n if (frame.type === 'TXXX') {\n /*\n Format:\n [0] = {Text Encoding}\n [1-?] = {Description}\\0{Value}\n */\n let index = 1;\n const description = ID3._utf8ArrayToStr(frame.data.subarray(index));\n\n index += description.length + 1;\n const value = ID3._utf8ArrayToStr(frame.data.subarray(index));\n\n return { key: frame.type, info: description, data: value };\n } else {\n /*\n Format:\n [0] = {Text Encoding}\n [1-?] = {Value}\n */\n const text = ID3._utf8ArrayToStr(frame.data.subarray(1));\n return { key: frame.type, data: text };\n }\n }\n\n static _decodeURLFrame(frame) {\n if (frame.type === 'WXXX') {\n /*\n Format:\n [0] = {Text Encoding}\n [1-?] = {Description}\\0{URL}\n */\n if (frame.size < 2) {\n return undefined;\n }\n\n let index = 1;\n const description = ID3._utf8ArrayToStr(frame.data.subarray(index));\n\n index += description.length + 1;\n const value = ID3._utf8ArrayToStr(frame.data.subarray(index));\n\n return { key: frame.type, info: description, data: value };\n } else {\n /*\n Format:\n [0-?] = {URL}\n */\n const url = ID3._utf8ArrayToStr(frame.data);\n return { key: frame.type, data: url };\n }\n }\n\n // http://stackoverflow.com/questions/8936984/uint8array-to-string-in-javascript/22373197\n // http://www.onicos.com/staff/iz/amuse/javascript/expert/utf.txt\n /* utf.js - UTF-8 <=> UTF-16 convertion\n *\n * Copyright (C) 1999 Masanao Izumo <iz@onicos.co.jp>\n * Version: 1.0\n * LastModified: Dec 25 1999\n * This library is free. You can redistribute it and/or modify it.\n */\n static _utf8ArrayToStr(array) {\n\n let char2;\n let char3;\n let out = '';\n let i = 0;\n let length = array.length;\n\n while (i < length) {\n let c = array[i++];\n switch (c >> 4) {\n case 0:\n return out;\n case 1: case 2: case 3: case 4: case 5: case 6: case 7:\n // 0xxxxxxx\n out += String.fromCharCode(c);\n break;\n case 12: case 13:\n // 110x xxxx 10xx xxxx\n char2 = array[i++];\n out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));\n break;\n case 14:\n // 1110 xxxx 10xx xxxx 10xx xxxx\n char2 = array[i++];\n char3 = array[i++];\n out += String.fromCharCode(((c & 0x0F) << 12) |\n ((char2 & 0x3F) << 6) |\n ((char3 & 0x3F) << 0));\n break;\n }\n }\n\n return out;\n }\n}\n\nexport default ID3;\n",
"/**\n * MP3 demuxer\n */\nimport ID3 from '../demux/id3';\nimport { logger } from '../utils/logger';\nimport MpegAudio from './mpegaudio';\n\nclass MP3Demuxer {\n\n constructor(observer, remuxer, config) {\n this.observer = observer;\n this.config = config;\n this.remuxer = remuxer;\n }\n\n resetInitSegment(initSegment, audioCodec, videoCodec, duration) {\n this._audioTrack = { container: 'audio/mpeg', type: 'audio', id: -1, sequenceNumber: 0, isAAC: false, samples: [], len: 0, manifestCodec: audioCodec, duration: duration, inputTimeScale: 90000 };\n }\n\n resetTimeStamp() {\n }\n\n static probe(data) {\n // check if data contains ID3 timestamp and MPEG sync word\n var offset, length;\n let id3Data = ID3.getID3Data(data, 0);\n if (id3Data && ID3.getTimeStamp(id3Data) !== undefined) {\n // Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1\n // Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III)\n // More info http://www.mp3-tech.org/programmer/frame_header.html\n for (offset = id3Data.length, length = Math.min(data.length - 1, offset + 100); offset < length; offset++) {\n if (MpegAudio.probe(data, offset)) {\n logger.log('MPEG Audio sync word found !');\n return true;\n }\n }\n }\n return false;\n }\n\n // feed incoming data to the front of the parsing pipeline\n append(data, timeOffset, contiguous, accurateTimeOffset) {\n let id3Data = ID3.getID3Data(data, 0);\n let pts = 90 * ID3.getTimeStamp(id3Data);\n var offset = id3Data.length;\n var length = data.length;\n var frameIndex = 0, stamp = 0;\n var track = this._audioTrack;\n\n let id3Samples = [{ pts: pts, dts: pts, data: id3Data }];\n\n while (offset < length) {\n if (MpegAudio.isHeader(data, offset)) {\n var frame = MpegAudio.appendFrame(track, data, offset, pts, frameIndex);\n if (frame) {\n offset += frame.length;\n stamp = frame.sample.pts;\n frameIndex++;\n } else {\n //logger.log('Unable to parse Mpeg audio frame');\n break;\n }\n } else if (ID3.isHeader(data, offset)) {\n id3Data = ID3.getID3Data(data, offset);\n id3Samples.push({ pts: stamp, dts: stamp, data: id3Data });\n offset += id3Data.length;\n } else {\n //nothing found, keep looking\n offset++;\n }\n }\n\n this.remuxer.remux(track,\n { samples: [] },\n { samples: id3Samples, inputTimeScale: 90000 },\n { samples: [] },\n timeOffset,\n contiguous,\n accurateTimeOffset);\n }\n\n destroy() {\n }\n}\n\nexport default MP3Demuxer;\n",
"/**\n * MP4 demuxer\n */\n//import {logger} from '../utils/logger';\nimport Event from '../events';\n\nconst UINT32_MAX = Math.pow(2, 32) - 1;\n\n class MP4Demuxer {\n\n constructor(observer, remuxer) {\n this.observer = observer;\n this.remuxer = remuxer;\n }\n\n resetTimeStamp(initPTS) {\n this.initPTS = initPTS;\n }\n\n resetInitSegment(initSegment,audioCodec,videoCodec, duration) {\n //jshint unused:false\n if (initSegment && initSegment.byteLength) {\n const initData = this.initData = MP4Demuxer.parseInitSegment(initSegment);\n var tracks = {};\n if (initData.audio) {\n tracks.audio = { container : 'audio/mp4', codec : audioCodec, initSegment : duration ? initSegment : null };\n }\n if (initData.video) {\n tracks.video = { container : 'video/mp4', codec : videoCodec, initSegment : duration ? initSegment : null };\n }\n this.observer.trigger(Event.FRAG_PARSING_INIT_SEGMENT,{ tracks : tracks });\n } else {\n if (audioCodec) {\n this.audioCodec = audioCodec;\n }\n if (videoCodec) {\n this.videoCodec = videoCodec;\n }\n }\n }\n\n static probe(data) {\n if (data.length >= 8) {\n const dataType = MP4Demuxer.bin2str(data.subarray(4,8));\n return (['moof','ftyp','styp'].indexOf(dataType) >= 0);\n }\n return false;\n }\n\n\n static bin2str(buffer) {\n return String.fromCharCode.apply(null, buffer);\n }\n\n static readUint32(buffer, offset) {\n if (buffer.data) {\n offset += buffer.start;\n buffer = buffer.data;\n }\n\n const val = buffer[offset] << 24 |\n buffer[offset + 1] << 16 |\n buffer[offset + 2] << 8 |\n buffer[offset + 3];\n return val < 0 ? 4294967296 + val : val;\n }\n\n static writeUint32(buffer, offset, value) {\n if (buffer.data) {\n offset += buffer.start;\n buffer = buffer.data;\n }\n buffer[offset] = value >> 24;\n buffer[offset+1] = (value >> 16) & 0xff;\n buffer[offset+2] = (value >> 8) & 0xff;\n buffer[offset+3] = value & 0xff;\n }\n\n\n // Find the data for a box specified by its path\n static findBox(data,path) {\n var results = [],\n i, size, type, end, subresults, start, endbox;\n\n if (data.data) {\n start = data.start;\n end = data.end;\n data = data.data;\n } else {\n start = 0;\n end = data.byteLength;\n }\n\n if (!path.length) {\n // short-circuit the search for empty paths\n return null;\n }\n\n for (i = start; i < end;) {\n size = MP4Demuxer.readUint32(data, i);\n type = MP4Demuxer.bin2str(data.subarray(i + 4, i + 8));\n endbox = size > 1 ? i + size : end;\n\n if (type === path[0]) {\n\n if (path.length === 1) {\n // this is the end of the path and we've found the box we were\n // looking for\n results.push({ data : data, start : i + 8, end : endbox});\n } else {\n // recursively search for the next box along the path\n subresults = MP4Demuxer.findBox({ data : data, start : i +8, end : endbox }, path.slice(1));\n if (subresults.length) {\n results = results.concat(subresults);\n }\n }\n }\n i = endbox;\n }\n\n // we've finished searching all of data\n return results;\n }\n\n\n\n/**\n * Parses an MP4 initialization segment and extracts stream type and\n * timescale values for any declared tracks. Timescale values indicate the\n * number of clock ticks per second to assume for time-based values\n * elsewhere in the MP4.\n *\n * To determine the start time of an MP4, you need two pieces of\n * information: the timescale unit and the earliest base media decode\n * time. Multiple timescales can be specified within an MP4 but the\n * base media decode time is always expressed in the timescale from\n * the media header box for the track:\n * ```\n * moov > trak > mdia > mdhd.timescale\n * moov > trak > mdia > hdlr\n * ```\n * @param init {Uint8Array} the bytes of the init segment\n * @return {object} a hash of track type to timescale values or null if\n * the init segment is malformed.\n */\n static parseInitSegment(initSegment) {\n var result = [];\n var traks = MP4Demuxer.findBox(initSegment, ['moov', 'trak']);\n\n traks.forEach(trak => {\n const tkhd = MP4Demuxer.findBox(trak, ['tkhd'])[0];\n if (tkhd) {\n let version = tkhd.data[tkhd.start];\n let index = version === 0 ? 12 : 20;\n let trackId = MP4Demuxer.readUint32(tkhd, index);\n\n const mdhd = MP4Demuxer.findBox(trak, ['mdia', 'mdhd'])[0];\n if (mdhd) {\n version = mdhd.data[mdhd.start];\n index = version === 0 ? 12 : 20;\n const timescale = MP4Demuxer.readUint32(mdhd, index);\n\n const hdlr = MP4Demuxer.findBox(trak, ['mdia', 'hdlr'])[0];\n if (hdlr) {\n const hdlrType = MP4Demuxer.bin2str(hdlr.data.subarray(hdlr.start+8, hdlr.start+12));\n let type = { 'soun' : 'audio', 'vide' : 'video'}[hdlrType];\n if (type) {\n result[trackId] = { timescale : timescale , type : type};\n result[type] = { timescale : timescale , id : trackId};\n }\n }\n }\n }\n });\n return result;\n }\n\n\n/**\n * Determine the base media decode start time, in seconds, for an MP4\n * fragment. If multiple fragments are specified, the earliest time is\n * returned.\n *\n * The base media decode time can be parsed from track fragment\n * metadata:\n * ```\n * moof > traf > tfdt.baseMediaDecodeTime\n * ```\n * It requires the timescale value from the mdhd to interpret.\n *\n * @param timescale {object} a hash of track ids to timescale values.\n * @return {number} the earliest base media decode start time for the\n * fragment, in seconds\n */\nstatic getStartDTS(initData, fragment) {\n var trafs, baseTimes, result;\n\n // we need info from two childrend of each track fragment box\n trafs = MP4Demuxer.findBox(fragment, ['moof', 'traf']);\n\n // determine the start times for each track\n baseTimes = [].concat.apply([], trafs.map(function(traf) {\n return MP4Demuxer.findBox(traf, ['tfhd']).map(function(tfhd) {\n var id, scale, baseTime;\n\n // get the track id from the tfhd\n id = MP4Demuxer.readUint32(tfhd, 4);\n // assume a 90kHz clock if no timescale was specified\n scale = initData[id].timescale || 90e3;\n\n // get the base media decode time from the tfdt\n baseTime = MP4Demuxer.findBox(traf, ['tfdt']).map(function(tfdt) {\n var version, result;\n\n version = tfdt.data[tfdt.start];\n result = MP4Demuxer.readUint32(tfdt, 4);\n if (version === 1) {\n result *= Math.pow(2, 32);\n\n result += MP4Demuxer.readUint32(tfdt, 8);\n }\n return result;\n })[0];\n baseTime = baseTime || Infinity;\n\n // convert base time to seconds\n return baseTime / scale;\n });\n }));\n\n // return the minimum\n result = Math.min.apply(null, baseTimes);\n return isFinite(result) ? result : 0;\n}\n\n\n\n\nstatic offsetStartDTS(initData,fragment,timeOffset) {\n MP4Demuxer.findBox(fragment, ['moof', 'traf']).map(function(traf) {\n return MP4Demuxer.findBox(traf, ['tfhd']).map(function(tfhd) {\n // get the track id from the tfhd\n var id = MP4Demuxer.readUint32(tfhd, 4);\n // assume a 90kHz clock if no timescale was specified\n var timescale = initData[id].timescale || 90e3;\n\n // get the base media decode time from the tfdt\n MP4Demuxer.findBox(traf, ['tfdt']).map(function(tfdt) {\n var version = tfdt.data[tfdt.start];\n var baseMediaDecodeTime = MP4Demuxer.readUint32(tfdt, 4);\n if (version === 0) {\n MP4Demuxer.writeUint32(tfdt, 4, baseMediaDecodeTime - timeOffset*timescale);\n } else {\n baseMediaDecodeTime *= Math.pow(2, 32);\n baseMediaDecodeTime += MP4Demuxer.readUint32(tfdt, 8);\n baseMediaDecodeTime -= timeOffset*timescale;\n const upper = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1));\n const lower = Math.floor(baseMediaDecodeTime % (UINT32_MAX + 1));\n MP4Demuxer.writeUint32(tfdt, 4, upper);\n MP4Demuxer.writeUint32(tfdt, 8, lower);\n }\n });\n });\n });\n}\n\n // feed incoming data to the front of the parsing pipeline\n append(data, timeOffset,contiguous,accurateTimeOffset) {\n let initData = this.initData;\n if(!initData) {\n this.resetInitSegment(data,this.audioCodec,this.videoCodec);\n initData = this.initData;\n }\n let startDTS, initPTS = this.initPTS;\n if (initPTS === undefined) {\n let startDTS = MP4Demuxer.getStartDTS(initData,data);\n this.initPTS = initPTS = startDTS - timeOffset;\n this.observer.trigger(Event.INIT_PTS_FOUND, { initPTS: initPTS});\n }\n MP4Demuxer.offsetStartDTS(initData,data,initPTS);\n startDTS = MP4Demuxer.getStartDTS(initData,data);\n this.remuxer.remux(initData.audio, initData.video, null, null, startDTS, contiguous,accurateTimeOffset,data);\n }\n\n destroy() {\n }\n\n}\n\nexport default MP4Demuxer;\n",
"/**\n * MPEG parser helper\n */\n\nconst MpegAudio = {\n\n 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\n SamplingRateMap: [44100, 48000, 32000, 22050, 24000, 16000, 11025, 12000, 8000],\n\n appendFrame: function (track, data, offset, pts, frameIndex) {\n // Using http://www.datavoyage.com/mpgscript/mpeghdr.htm as a reference\n if (offset + 24 > data.length) {\n return undefined;\n }\n\n var header = this.parseHeader(data, offset);\n if (header && offset + header.frameLength <= data.length) {\n var frameDuration = 1152 * 90000 / header.sampleRate;\n var stamp = pts + frameIndex * frameDuration;\n var sample = { unit: data.subarray(offset, offset + header.frameLength), pts: stamp, dts: stamp };\n\n track.config = [];\n track.channelCount = header.channelCount;\n track.samplerate = header.sampleRate;\n track.samples.push(sample);\n track.len += header.frameLength;\n\n return { sample, length: header.frameLength };\n }\n\n return undefined;\n },\n\n parseHeader: function (data, offset) {\n var headerB = (data[offset + 1] >> 3) & 3;\n var headerC = (data[offset + 1] >> 1) & 3;\n var headerE = (data[offset + 2] >> 4) & 15;\n var headerF = (data[offset + 2] >> 2) & 3;\n var headerG = !!(data[offset + 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 = MpegAudio.BitratesMap[columnInBitrates * 14 + headerE - 1] * 1000;\n var columnInSampleRates = headerB === 3 ? 0 : headerB === 2 ? 1 : 2;\n var sampleRate = MpegAudio.SamplingRateMap[columnInSampleRates * 3 + headerF];\n var padding = headerG ? 1 : 0;\n var channelCount = data[offset + 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\n return { sampleRate, channelCount, frameLength };\n }\n\n return undefined;\n },\n\n isHeaderPattern: function (data, offset) {\n return data[offset] === 0xff && (data[offset + 1] & 0xe0) === 0xe0 && (data[offset + 1] & 0x06) !== 0x00;\n },\n\n isHeader: function (data, offset) {\n // Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1\n // Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III)\n // More info http://www.mp3-tech.org/programmer/frame_header.html\n if (offset + 1 < data.length && this.isHeaderPattern(data, offset)) {\n return true;\n }\n return false;\n },\n\n probe: function (data, offset) {\n // same as isHeader but we also check that MPEG frame follows last MPEG frame \n // or end of data is reached\n if (offset + 1 < data.length && this.isHeaderPattern(data, offset)) {\n // MPEG header Length\n let headerLength = 4;\n // MPEG frame Length\n let header = this.parseHeader(data, offset);\n let frameLength = headerLength;\n if (header && header.frameLength) {\n frameLength = header.frameLength;\n }\n let newOffset = offset + frameLength;\n if (newOffset === data.length || (newOffset + 1 < data.length && this.isHeaderPattern(data, newOffset))) {\n return true;\n }\n }\n return false;\n }\n};\n\nmodule.exports = MpegAudio;",
"/**\n * SAMPLE-AES decrypter\n*/\n\n import Decrypter from '../crypt/decrypter';\n\n class SampleAesDecrypter {\n\n constructor(observer, config, decryptdata, discardEPB) {\n this.decryptdata = decryptdata;\n this.discardEPB = discardEPB;\n this.decrypter = new Decrypter(observer, config);\n }\n\n decryptBuffer(encryptedData, callback) {\n this.decrypter.decrypt(encryptedData, this.decryptdata.key.buffer, this.decryptdata.iv.buffer, callback);\n }\n\n // AAC - encrypt all full 16 bytes blocks starting from offset 16\n decryptAacSample(samples, sampleIndex, callback, sync) {\n let curUnit = samples[sampleIndex].unit;\n let encryptedData = curUnit.subarray(16, curUnit.length - curUnit.length % 16);\n let encryptedBuffer = encryptedData.buffer.slice(\n encryptedData.byteOffset,\n encryptedData.byteOffset + encryptedData.length);\n\n let localthis = this;\n this.decryptBuffer(encryptedBuffer, function (decryptedData) {\n decryptedData = new Uint8Array(decryptedData);\n curUnit.set(decryptedData, 16);\n\n if (!sync) {\n localthis.decryptAacSamples(samples, sampleIndex + 1, callback);\n }\n });\n }\n\n decryptAacSamples(samples, sampleIndex, callback) {\n for (;; sampleIndex++) {\n if (sampleIndex >= samples.length) {\n callback();\n return;\n }\n\n if (samples[sampleIndex].unit.length < 32) {\n continue;\n }\n\n let sync = this.decrypter.isSync();\n\n this.decryptAacSample(samples, sampleIndex, callback, sync);\n\n if (!sync) {\n return;\n }\n }\n }\n\n // AVC - encrypt one 16 bytes block out of ten, starting from offset 32\n getAvcEncryptedData(decodedData) {\n let encryptedDataLen = Math.floor((decodedData.length - 48) / 160) * 16 + 16;\n let encryptedData = new Int8Array(encryptedDataLen);\n let outputPos = 0;\n for (let inputPos = 32; inputPos <= decodedData.length - 16; inputPos += 160, outputPos += 16) {\n encryptedData.set(decodedData.subarray(inputPos, inputPos + 16), outputPos);\n }\n return encryptedData;\n }\n\n getAvcDecryptedUnit(decodedData, decryptedData) {\n decryptedData = new Uint8Array(decryptedData);\n let inputPos = 0;\n for (let outputPos = 32; outputPos <= decodedData.length - 16; outputPos += 160, inputPos += 16) {\n decodedData.set(decryptedData.subarray(inputPos, inputPos + 16), outputPos);\n }\n return decodedData;\n }\n\n decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit, sync) {\n let decodedData = this.discardEPB(curUnit.data);\n let encryptedData = this.getAvcEncryptedData(decodedData);\n let localthis = this;\n\n this.decryptBuffer(encryptedData.buffer, function (decryptedData) {\n curUnit.data = localthis.getAvcDecryptedUnit(decodedData, decryptedData);\n\n if (!sync) {\n localthis.decryptAvcSamples(samples, sampleIndex, unitIndex + 1, callback);\n }\n });\n }\n\n decryptAvcSamples(samples, sampleIndex, unitIndex, callback) {\n for (;; sampleIndex++, unitIndex = 0) {\n if (sampleIndex >= samples.length) {\n callback();\n return;\n }\n\n let curUnits = samples[sampleIndex].units;\n for (;; unitIndex++) {\n if (unitIndex >= curUnits.length) {\n break;\n }\n\n let curUnit = curUnits[unitIndex];\n if (curUnit.length <= 48 || (curUnit.type !== 1 && curUnit.type !== 5)) {\n continue;\n }\n\n let sync = this.decrypter.isSync();\n\n this.decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit, sync);\n\n if (!sync) {\n return;\n }\n }\n }\n }\n }\n\n export default SampleAesDecrypter;\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 MpegAudio from './mpegaudio';\n import Event from '../events';\n import ExpGolomb from './exp-golomb';\n import SampleAesDecrypter from './sample-aes';\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, remuxer, config, typeSupported) {\n this.observer = observer;\n this.config = config;\n this.typeSupported = typeSupported;\n this.remuxer = remuxer;\n this.sampleAes = null;\n }\n\n setDecryptData(decryptdata) {\n if ((decryptdata != null) && (decryptdata.key != null) && (decryptdata.method === 'SAMPLE-AES')) {\n this.sampleAes = new SampleAesDecrypter(this.observer, this.config, decryptdata, this.discardEPB);\n } else {\n this.sampleAes = null;\n }\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 resetInitSegment(initSegment,audioCodec,videoCodec, duration) {\n this.pmtParsed = false;\n this._pmtId = -1;\n this._avcTrack = {container : 'video/mp2t', type: 'video', id :-1, inputTimeScale : 90000, sequenceNumber: 0, samples : [], len : 0, dropped : 0};\n this._audioTrack = {container : 'video/mp2t', type: 'audio', id :-1, inputTimeScale : 90000, duration: duration, sequenceNumber: 0, samples : [], len : 0, isAAC: true};\n this._id3Track = {type: 'id3', id :-1, inputTimeScale : 90000, sequenceNumber: 0, samples : [], len : 0};\n this._txtTrack = {type: 'text', id: -1, inputTimeScale : 90000, sequenceNumber: 0, samples : [], len : 0};\n // flush any partial content\n this.aacOverFlow = null;\n this.aacLastPTS = null;\n this.avcSample = null;\n this.audioCodec = audioCodec;\n this.videoCodec = videoCodec;\n this._duration = duration;\n }\n\n resetTimeStamp() {\n }\n\n // feed incoming data to the front of the parsing pipeline\n append(data, timeOffset, contiguous,accurateTimeOffset) {\n var start, len = data.length, stt, pid, atf, offset,pes,\n unknownPIDs = false;\n this.contiguous = contiguous;\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 }\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 }\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, this.sampleAes != null);\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, 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\n if (this.sampleAes == null) {\n this.remuxer.remux(audioTrack, avcTrack, id3Track, this._txtTrack, timeOffset, contiguous, accurateTimeOffset);\n } else {\n this.decryptAndRemux(audioTrack, avcTrack, id3Track, this._txtTrack, timeOffset, contiguous, accurateTimeOffset);\n }\n }\n\n decryptAndRemux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset) {\n if (audioTrack.samples && audioTrack.isAAC) {\n let localthis = this;\n this.sampleAes.decryptAacSamples(audioTrack.samples, 0, function() {\n localthis.decryptAndRemuxAvc(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset);\n });\n } else {\n this.decryptAndRemuxAvc(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset);\n }\n }\n\n decryptAndRemuxAvc(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset) {\n if (videoTrack.samples) {\n let localthis = this;\n this.sampleAes.decryptAvcSamples(videoTrack.samples, 0, 0, function () {\n localthis.remuxer.remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset);\n });\n } else {\n this.remuxer.remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset);\n }\n }\n\n destroy() {\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, isSampleAes) {\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 case 0xcf: // SAMPLE-AES AAC\n if (!isSampleAes) {\n logger.log('unkown stream type:' + data[offset]);\n break;\n }\n /* falls through */\n\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\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\n case 0xdb: // SAMPLE-AES AVC\n if (!isSampleAes) {\n logger.log('unkown stream type:' + data[offset]);\n break;\n }\n /* falls through */\n\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\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\n case 0x24:\n logger.warn('HEVC stream type found, not supported for now');\n break;\n\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.length && avcSample.frame) {\n const samples = avcTrack.samples;\n const nbSamples = samples.length;\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 && (nbSamples || this.contiguous))) {\n avcSample.id = nbSamples;\n 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);\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 spsfound = false,\n i,\n pushAccesUnit = this.pushAccesUnit.bind(this),\n createAVCSample = function(key,pts,dts,debug) {\n return { key : key, pts : pts, dts : dts, units : [], debug : debug};\n };\n //free pes.data to save up some memory\n pes.data = null;\n\n // if new NAL units found and last sample still there, let's push ...\n // this helps parsing streams with missing AUD\n if (avcSample && units.length) {\n pushAccesUnit(avcSample,track);\n avcSample = this.avcSample = createAVCSample(false,pes.pts,pes.dts,'');\n }\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 let data = unit.data;\n // only check slice type to detect KF in case SPS found in same packet (any keyframe is preceded by SPS ...)\n if (spsfound && data.length > 4) {\n // retrieve slice type by parsing beginning of NAL unit (follow H264 spec, slice_header definition) to detect keyframe embedded in NDR\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 = 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 spsfound = 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.pixelRatio = config.pixelRatio;\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 pushAccesUnit(avcSample,track);\n }\n avcSample = this.avcSample = 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.push(unit);\n }\n });\n // if last PES packet, push samples\n if (last && avcSample) {\n pushAccesUnit(avcSample,track);\n this.avcSample = null;\n }\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.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;\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 frameDuration, frameIndex, offset, stamp, len;\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 (ADTS.isHeader(data, offset)) {\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, details: ErrorDetails.FRAG_PARSING_ERROR, fatal: fatal, reason: reason});\n if (fatal) {\n return;\n }\n }\n\n ADTS.initTrackConfig(track, this.observer, data, offset, this.audioCodec);\n frameIndex = 0;\n frameDuration = ADTS.getFrameDuration(track.samplerate);\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 //scan for aac samples\n while (offset < len) {\n if (ADTS.isHeader(data, offset) && (offset + 5) < len) {\n var frame = ADTS.appendFrame(track, data, offset, pts, frameIndex);\n if (frame) {\n //logger.log(`${Math.round(frame.sample.pts)} : AAC`);\n offset += frame.length;\n stamp = frame.sample.pts;\n frameIndex++;\n } else {\n //logger.log('Unable to parse AAC frame');\n break;\n }\n } else {\n //nothing found, keep looking\n offset++;\n }\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 length = data.length;\n var frameIndex = 0;\n var offset = 0;\n var pts = pes.pts;\n\n while (offset < length) {\n if (MpegAudio.isHeader(data, offset)) {\n var frame = MpegAudio.appendFrame(this._audioTrack, data, offset, pts, frameIndex);\n if (frame) {\n offset += frame.length;\n frameIndex++;\n } else {\n //logger.log('Unable to parse Mpeg audio frame');\n break;\n }\n } else {\n //nothing found, keep looking\n offset++;\n }\n }\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: {id : demuxer Id,frag: fragment object, reason : 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, frag : fragment object, 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 // Malformed WebVTT contents\n WEBVTT_EXCEPTION: 'webVTTException'\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 }, this);\n }\n }\n\n unregisterListeners() {\n if (this.isEventHandler()) {\n this.handledEvents.forEach(function(event) {\n this.hls.off(event, this.onEvent);\n }, 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 reset - data: { }\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 - 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 buffer has been flushed - data: { }\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 switch is requested - data: { level : id of new level } // deprecated in favor LEVEL_SWITCHING\n LEVEL_SWITCH: 'hlsLevelSwitch',\n // fired when a level switch is requested - data: { level : id of new level }\n LEVEL_SWITCHING: 'hlsLevelSwitching',\n // fired when a level switch is effective - data: { level : id of new level }\n LEVEL_SWITCHED: 'hlsLevelSwitched',\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 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 in favor AUDIO_TRACK_SWITCHING\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 to notify that subtitle track lists has been updated - data: { subtitleTracks : subtitleTracks }\n SUBTITLE_TRACKS_UPDATED: 'hlsSubtitleTracksUpdated',\n // fired when an subtitle track switch occurs - data: { id : subtitle track id }\n SUBTITLE_TRACK_SWITCH: 'hlsSubtitleTrackSwitch',\n // fired when a subtitle track loading starts - data: { url : subtitle track URL, id : subtitle track id }\n SUBTITLE_TRACK_LOADING: 'hlsSubtitleTrackLoading',\n // fired when a subtitle track loading finishes - data: { details : levelDetails object, id : subtitle track id, stats : { trequest, tfirst, tload, mtime } }\n SUBTITLE_TRACK_LOADED: 'hlsSubtitleTrackLoaded',\n // fired when a subtitle fragment has been processed - data: { success : boolean, frag : the processed frag }\n SUBTITLE_FRAG_PROCESSED: 'hlsSubtitleFragProcessed',\n // fired when the first timestamp is found - data: { id : demuxer id, initPTS: initPTS, frag : fragment object }\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: { id : demuxer id, frag: fragment object, stats : { tstart, tdecrypt } }\n FRAG_DECRYPTED: 'hlsFragDecrypted',\n // fired when Init Segment has been extracted from fragment - data: { id : demuxer id, frag: fragment object, 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, frag: fragment object, samples : [ sei samples pes ] }\n FRAG_PARSING_USERDATA: 'hlsFragParsingUserdata',\n // fired when parsing id3 is completed - data: { id : demuxer id, frag: fragment object, samples : [ id3 samples pes ] }\n FRAG_PARSING_METADATA: 'hlsFragParsingMetadata',\n // fired when data have been extracted from fragment - data: { id : demuxer id, frag: fragment object, 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, frag: fragment object }\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, bwEstimate } }\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 - data: { }\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 utils, providing methods dealing buffer length retrieval\n*/\n\nconst BufferHelper = {\n isBuffered : function(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 bufferInfo : function(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: pos, end: pos, nextStart : undefined} ;\n }\n },\n\n bufferedInfo : function(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\nmodule.exports = BufferHelper;\n",
"/**\n * Level Helper class, providing methods dealing with playlist sliding and drift\n*/\n\nimport {logger} from '../utils/logger';\n\nconst LevelHelper = {\n\n mergeDetails : function(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 newFrag.backtracked = oldFrag.backtracked;\n newFrag.dropped = oldFrag.dropped;\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,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 updateFragPTSDTS : function(details,frag,startPTS,endPTS,startDTS,endDTS) {\n // update frag PTS/DTS\n let maxStartPTS = startPTS;\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 maxStartPTS = Math.max(startPTS,frag.startPTS);\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 const drift = startPTS - frag.start;\n frag.start = frag.startPTS = startPTS;\n frag.maxStartPTS = maxStartPTS;\n frag.endPTS = endPTS;\n frag.startDTS = startDTS;\n frag.endDTS = endDTS;\n frag.duration = endPTS - startPTS;\n\n const sn = frag.sn;\n // exit if sn out of range\n if (!details || sn < details.startSN || sn > details.endSN) {\n return 0;\n }\n var fragIdx, fragments, i;\n fragIdx = sn - details.startSN;\n fragments = details.fragments;\n // update frag reference in fragments array\n // rationale is that fragments array might not contain this frag object.\n // this will happpen if playlist has been refreshed between frag loading and call to updateFragPTSDTS()\n // if we don't update frag, we won't be able to propagate PTS info on the playlist\n // resulting in invalid sliding computation\n fragments[fragIdx] = frag;\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 updatePTS : function(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 = Math.max(fragFrom.start - fragTo.duration, 0);\n }\n }\n }\n};\n\nmodule.exports = LevelHelper;\n",
"/**\n * HLS interface\n */\nimport URLToolkit from 'url-toolkit';\nimport Event from './events';\nimport {ErrorTypes, ErrorDetails} from './errors';\nimport PlaylistLoader from './loader/playlist-loader';\nimport FragmentLoader from './loader/fragment-loader';\nimport KeyLoader from './loader/key-loader';\n\nimport StreamController from './controller/stream-controller';\nimport LevelController from './controller/level-controller';\nimport ID3TrackController from './controller/id3-track-controller';\n\nimport {logger, enableLogs} from './utils/logger';\nimport EventEmitter from 'events';\nimport {hlsDefaultConfig} from './config';\n\nclass Hls {\n\n static get version() {\n // replaced with browserify-versionify transform\n return '0.7.11';\n }\n\n static isSupported() {\n const mediaSource = window.MediaSource = window.MediaSource || window.WebKitMediaSource;\n const sourceBuffer = window.SourceBuffer = window.SourceBuffer || window.WebKitSourceBuffer;\n const isTypeSupported = mediaSource &&\n typeof mediaSource.isTypeSupported === 'function' &&\n mediaSource.isTypeSupported('video/mp4; codecs=\"avc1.42E01E,mp4a.40.2\"');\n\n // if SourceBuffer is exposed ensure its API is valid\n // safari and old version of Chrome doe not expose SourceBuffer globally so checking SourceBuffer.prototype is impossible\n const sourceBufferValidAPI = !sourceBuffer ||\n (sourceBuffer.prototype &&\n typeof sourceBuffer.prototype.appendBuffer === 'function' &&\n typeof sourceBuffer.prototype.remove === 'function');\n return isTypeSupported && sourceBufferValidAPI;\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 return hlsDefaultConfig;\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 this._autoLevelCapping = -1;\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\n // core controllers and network loaders\n const abrController = this.abrController = new config.abrController(this);\n const bufferController = new config.bufferController(this);\n const capLevelController = new config.capLevelController(this);\n const fpsController = new config.fpsController(this);\n const playListLoader = new PlaylistLoader(this);\n const fragmentLoader = new FragmentLoader(this);\n const keyLoader = new KeyLoader(this);\n const id3TrackController = new ID3TrackController(this);\n\n // network controllers\n const levelController = this.levelController = new LevelController(this);\n const streamController = this.streamController = new StreamController(this);\n let networkControllers = [levelController, streamController];\n\n // optional audio stream controller\n let Controller = config.audioStreamController;\n if (Controller) {\n networkControllers.push(new Controller(this));\n }\n this.networkControllers = networkControllers;\n\n let coreComponents = [ playListLoader, fragmentLoader, keyLoader, abrController, bufferController, capLevelController, fpsController, id3TrackController ];\n\n // optional audio track and subtitle controller\n Controller = config.audioTrackController;\n if (Controller) {\n let audioTrackController = new Controller(this);\n this.audioTrackController = audioTrackController;\n coreComponents.push(audioTrackController);\n }\n\n Controller = config.subtitleTrackController;\n if (Controller) {\n let subtitleTrackController = new Controller(this);\n this.subtitleTrackController = subtitleTrackController;\n coreComponents.push(subtitleTrackController);\n }\n\n // optional subtitle controller\n [config.subtitleStreamController, config.timelineController].forEach(Controller => {\n if (Controller) {\n coreComponents.push(new Controller(this));\n }\n });\n this.coreComponents = coreComponents;\n }\n\n destroy() {\n logger.log('destroy');\n this.trigger(Event.DESTROYING);\n this.detachMedia();\n this.coreComponents.concat(this.networkControllers).forEach(component => {component.destroy();});\n this.url = null;\n this.observer.removeAllListeners();\n this._autoLevelCapping = -1;\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 url = URLToolkit.buildAbsoluteURL(window.location.href, url, { alwaysNormalize: true });\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.networkControllers.forEach(controller => {controller.startLoad(startPosition);});\n }\n\n stopLoad() {\n logger.log('stopLoad');\n this.networkControllers.forEach(controller => {controller.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.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 const hls = this;\n // if not in automatic start level detection, ensure startLevel is greater than minAutoLevel\n if (newLevel !== -1) {\n newLevel = Math.max(newLevel,hls.minAutoLevel);\n }\n hls.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._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._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 /* return min level selectable in auto mode according to config.minAutoBitrate */\n get minAutoLevel() {\n let hls = this, levels = hls.levels, minAutoBitrate = hls.config.minAutoBitrate, len = levels ? levels.length : 0;\n for (let i = 0; i < len; i++) {\n const levelNextBitrate = levels[i].realBitrate ? Math.max(levels[i].realBitrate,levels[i].bitrate) : levels[i].bitrate;\n if (levelNextBitrate > minAutoBitrate) {\n return i;\n }\n }\n return 0;\n }\n\n /* return max level selectable in auto mode according to autoLevelCapping */\n get maxAutoLevel() {\n const hls = this;\n const levels = hls.levels;\n const autoLevelCapping = hls.autoLevelCapping;\n let 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 // return next auto level\n get nextAutoLevel() {\n const hls = this;\n // ensure next auto level is between min and max auto level\n return Math.min(Math.max(hls.abrController.nextAutoLevel,hls.minAutoLevel),hls.maxAutoLevel);\n }\n\n // this setter is used to force next auto level\n // this is useful to force a switch down in auto mode : in case of load error on level N, hls.js can set nextAutoLevel to N-1 for example)\n // forced value is valid for one fragment. upon succesful frag loading at forced level, this value will be resetted to -1 by ABR controller\n set nextAutoLevel(nextLevel) {\n const hls = this;\n hls.abrController.nextAutoLevel = Math.max(hls.minAutoLevel,nextLevel);\n }\n\n /** get alternate audio tracks list from playlist **/\n get audioTracks() {\n const audioTrackController = this.audioTrackController;\n return audioTrackController ? audioTrackController.audioTracks : [];\n }\n\n /** get index of the selected audio track (index in audio track lists) **/\n get audioTrack() {\n const audioTrackController = this.audioTrackController;\n return audioTrackController ? audioTrackController.audioTrack : -1;\n }\n\n /** select an audio track, based on its index in audio track lists**/\n set audioTrack(audioTrackId) {\n const audioTrackController = this.audioTrackController;\n if (audioTrackController) {\n audioTrackController.audioTrack = audioTrackId;\n }\n }\n\n get liveSyncPosition() {\n return this.streamController.liveSyncPosition;\n }\n\n /** get alternate subtitle tracks list from playlist **/\n get subtitleTracks() {\n const subtitleTrackController = this.subtitleTrackController;\n return subtitleTrackController ? subtitleTrackController.subtitleTracks : [];\n }\n\n /** get index of the selected subtitle track (index in subtitle track lists) **/\n get subtitleTrack() {\n const subtitleTrackController = this.subtitleTrackController;\n return subtitleTrackController ? subtitleTrackController.subtitleTrack : -1;\n }\n\n /** select an subtitle track, based on its index in subtitle track lists**/\n set subtitleTrack(subtitleTrackId) {\n const subtitleTrackController = this.subtitleTrackController;\n if (subtitleTrackController) {\n subtitleTrackController.subtitleTrack = subtitleTrackId;\n }\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, networkDetails=null) {\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, networkDetails: networkDetails});\n }\n\n loaderror(response, context, networkDetails=null) {\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, networkDetails: networkDetails});\n }\n\n loadtimeout(stats, context, networkDetails=null) {\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, networkDetails: networkDetails});\n }\n\n // data will be used for progressive parsing\n loadprogress(stats, context, data, networkDetails=null) { // 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, networkDetails: networkDetails});\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;\n\nconst LEVEL_PLAYLIST_REGEX_FAST = new RegExp([\n /#EXTINF:(\\d*(?:\\.\\d+)?)(?:,(.*)\\s+)?/.source, // duration (#EXTINF:<duration>,<title>), group 1 => duration, group 2 => title\n /|(?!#)(\\S+)/.source, // segment URI, group 3 => the URI (note newline is not eaten)\n /|#EXT-X-BYTERANGE:*(.+)/.source, // next segment's byterange, group 4 => range spec (x@y)\n /|#EXT-X-PROGRAM-DATE-TIME:(.+)/.source, // next segment's program date/time group 5 => the datetime spec\n /|#.*/.source // All other non-segment oriented tags will match with all groups empty\n].join(''), 'g');\n\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+))|(?:#EXT-X-(MAP):(.+))|(?:(#)(.*):(.*))|(?:(#)(.*))(?:.*)\\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, { alwaysNormalize: true });\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 this.tagList = [];\n }\n\n get url() {\n if (!this._url && this.relurl) {\n this._url = URLToolkit.buildAbsoluteURL(this.baseurl, this.relurl, { alwaysNormalize: true });\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 let byteRange = this._byteRange = [];\n if (this.rawByteRange) {\n const params = this.rawByteRange.split('@', 2);\n if (params.length === 1) {\n const lastByteRangeEndOffset = this.lastByteRangeEndOffset;\n byteRange[0] = lastByteRangeEndOffset ? lastByteRangeEndOffset : 0;\n } else {\n byteRange[0] = parseInt(params[1]);\n }\n byteRange[1] = parseInt(params[0]) + byteRange[0];\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 Event.SUBTITLE_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 onSubtitleTrackLoading(data) {\n this.load(data.url, { type : 'subtitleTrack', 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, { alwaysNormalize: true });\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 if (codec.indexOf('hvc1') !== -1) {\n level.videoCodec = 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, audioCodec=null) {\n let result, medias = [], id = 0;\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 if (audioCodec) {\n media.audioCodec = audioCodec;\n }\n media.id = id++;\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 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 // avoid sliced strings https://github.com/video-dev/hls.js/issues/939\n const title = (' ' + result[2]).slice(1);\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.start = totalduration;\n frag.levelkey = levelkey;\n frag.sn = sn;\n frag.level = id;\n frag.cc = cc;\n frag.baseurl = baseurl;\n // avoid sliced strings https://github.com/video-dev/hls.js/issues/939\n frag.relurl = (' ' + result[3]).slice(1);\n\n level.fragments.push(frag);\n prevFrag = frag;\n totalduration += frag.duration;\n\n frag = new Fragment();\n }\n } else if (result[4]) { // X-BYTERANGE\n frag.rawByteRange = (' ' + result[4]).slice(1);\n if (prevFrag) {\n const lastByteRangeEndOffset = prevFrag.byteRangeEndOffset;\n if (lastByteRangeEndOffset) {\n frag.lastByteRangeEndOffset = lastByteRangeEndOffset;\n }\n }\n } else if (result[5]) { // PROGRAM-DATE-TIME\n // avoid sliced strings https://github.com/video-dev/hls.js/issues/939\n frag.rawProgramDateTime = (' ' + result[5]).slice(1);\n frag.tagList.push(['PROGRAM-DATE-TIME', frag.rawProgramDateTime]);\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 // avoid sliced strings https://github.com/video-dev/hls.js/issues/939\n const value1 = (' ' + result[i+1]).slice(1);\n const value2 = (' ' + result[i+2]).slice(1);\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) && (['AES-128', 'SAMPLE-AES'].indexOf(decryptmethod) >= 0)) {\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 case 'MAP':\n let mapAttrs = new AttrList(value1);\n frag.relurl = mapAttrs.URI;\n frag.rawByteRange = mapAttrs.BYTERANGE;\n frag.baseurl = baseurl;\n frag.level = id;\n frag.type = type;\n frag.sn = 'initSegment';\n level.initSegment = frag;\n frag = new Fragment();\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, networkDetails=null) {\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' && type !== 'subtitleTrack'),\n levelId = !isNaN(level) ? level : !isNaN(id) ? id : 0,\n levelDetails = this.parseLevelPlaylist(string, url, levelId, (type === 'audioTrack' ? 'audio' : (type === 'subtitleTrack' ? 'subtitle' : 'main') ));\n levelDetails.tload = stats.tload;\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, networkDetails: networkDetails});\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, networkDetails: networkDetails});\n } else {\n if (type === 'audioTrack') {\n hls.trigger(Event.AUDIO_TRACK_LOADED, {details: levelDetails, id: id, stats: stats, networkDetails: networkDetails});\n }\n else if (type === 'subtitleTrack') {\n hls.trigger(Event.SUBTITLE_TRACK_LOADED, {details: levelDetails, id: id, stats: stats, networkDetails: networkDetails});\n }\n }\n } else {\n hls.trigger(Event.ERROR, {type: ErrorTypes.NETWORK_ERROR, details: ErrorDetails.MANIFEST_PARSING_ERROR, fatal: true, url: url, reason: 'invalid targetduration', networkDetails: networkDetails});\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', levels[0].audioCodec);\n let subtitles = this.parseMasterPlaylistMedia(string, url, 'SUBTITLES');\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, audioTracks, subtitles, url, stats, networkDetails});\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', networkDetails: networkDetails});\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', networkDetails: networkDetails});\n }\n }\n\n loaderror(response, context, networkDetails=null) {\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, networkDetails: networkDetails});\n }\n\n loadtimeout(stats, context, networkDetails=null) {\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, networkDetails: networkDetails});\n }\n}\n\nexport default PlaylistLoader;\n",
"/**\n * Generate MP4 Box\n*/\n\n//import Hex from '../utils/hex';\n\nconst UINT32_MAX = Math.pow(2, 32) - 1;\n\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 pasp: [],\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 const upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));\n const lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));\n return MP4.box(MP4.types.mdhd, new Uint8Array([\n 0x01, // version 1\n 0x00, 0x00, 0x00, // flags\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, // creation_time\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, // modification_time\n (timescale >> 24) & 0xFF,\n (timescale >> 16) & 0xFF,\n (timescale >> 8) & 0xFF,\n timescale & 0xFF, // timescale\n (upperWordDuration >> 24),\n (upperWordDuration >> 16) & 0xFF,\n (upperWordDuration >> 8) & 0xFF,\n upperWordDuration & 0xFF,\n (lowerWordDuration >> 24),\n (lowerWordDuration >> 16) & 0xFF,\n (lowerWordDuration >> 8) & 0xFF,\n lowerWordDuration & 0xFF,\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 const upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));\n const lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));\n var\n bytes = new Uint8Array([\n 0x01, // version 1\n 0x00, 0x00, 0x00, // flags\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, // creation_time\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, // modification_time\n (timescale >> 24) & 0xFF,\n (timescale >> 16) & 0xFF,\n (timescale >> 8) & 0xFF,\n timescale & 0xFF, // timescale\n (upperWordDuration >> 24),\n (upperWordDuration >> 16) & 0xFF,\n (upperWordDuration >> 8) & 0xFF,\n upperWordDuration & 0xFF,\n (lowerWordDuration >> 24),\n (lowerWordDuration >> 16) & 0xFF,\n (lowerWordDuration >> 8) & 0xFF,\n lowerWordDuration & 0xFF,\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 hSpacing = track.pixelRatio[0],\n vSpacing = track.pixelRatio[1];\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 MP4.box(MP4.types.pasp, new Uint8Array([\n (hSpacing >> 24), // hSpacing\n (hSpacing >> 16) & 0xFF,\n (hSpacing >> 8) & 0xFF,\n hSpacing & 0xFF,\n (vSpacing >> 24), // vSpacing\n (vSpacing >> 16) & 0xFF,\n (vSpacing >> 8) & 0xFF,\n vSpacing & 0xFF]))\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 samplerate = track.samplerate;\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 (samplerate >> 8) & 0xFF,\n samplerate & 0xff, //\n 0x00, 0x00]),\n MP4.box(MP4.types.esds, MP4.esds(track)));\n }\n\n static mp3(track) {\n var samplerate = track.samplerate;\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 (samplerate >> 8) & 0xFF,\n samplerate & 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 upperWordDuration = Math.floor(duration / (UINT32_MAX + 1)),\n lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));\n return MP4.box(MP4.types.tkhd, new Uint8Array([\n 0x01, // version 1\n 0x00, 0x00, 0x07, // flags\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, // creation_time\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, // 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 (upperWordDuration >> 24),\n (upperWordDuration >> 16) & 0xFF,\n (upperWordDuration >> 8) & 0xFF,\n upperWordDuration & 0xFF,\n (lowerWordDuration >> 24),\n (lowerWordDuration >> 16) & 0xFF,\n (lowerWordDuration >> 8) & 0xFF,\n lowerWordDuration & 0xFF,\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 upperWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1)),\n lowerWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime % (UINT32_MAX + 1));\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 0x01, // version 1\n 0x00, 0x00, 0x00, // flags\n (upperWordBaseMediaDecodeTime >>24),\n (upperWordBaseMediaDecodeTime >> 16) & 0XFF,\n (upperWordBaseMediaDecodeTime >> 8) & 0XFF,\n (upperWordBaseMediaDecodeTime & 0xFF),\n (lowerWordBaseMediaDecodeTime >>24),\n (lowerWordBaseMediaDecodeTime >> 16) & 0XFF,\n (lowerWordBaseMediaDecodeTime >> 8) & 0XFF,\n (lowerWordBaseMediaDecodeTime & 0xFF)\n ])),\n MP4.trun(track,\n sampleDependencyTable.length +\n 16 + // tfhd\n 20 + // 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\n// 10 seconds\nconst MAX_SILENT_FRAME_DURATION = 10 * 1000;\n\nclass MP4Remuxer {\n constructor(observer, config, typeSupported, vendor) {\n this.observer = observer;\n this.config = config;\n this.typeSupported = typeSupported;\n const userAgent = navigator.userAgent;\n this.isSafari = vendor && vendor.indexOf('Apple') > -1 && userAgent && !userAgent.match('CriOS');\n this.ISGenerated = false;\n }\n\n destroy() {\n }\n\n resetTimeStamp(defaultTimeStamp) {\n this._initPTS = this._initDTS = defaultTimeStamp;\n }\n\n resetInitSegment() {\n this.ISGenerated = false;\n }\n\n remux(audioTrack,videoTrack,id3Track,textTrack,timeOffset, contiguous,accurateTimeOffset) {\n // generate Init Segment if needed\n if (!this.ISGenerated) {\n this.generateIS(audioTrack,videoTrack,timeOffset);\n } else {\n if (accurateTimeOffset) {\n // check timestamp consistency. it there is more than 10s gap between expected PTS/DTS, recompute initPTS/DTS\n const refPTS = this._initPTS;\n const ptsNormalize = this._PTSNormalize;\n const timeScale = audioTrack.inputTimeScale || videoTrack.inputTimeScale;\n let initPTS = Infinity, initDTS = Infinity;\n let samples = audioTrack.samples;\n if (samples.length) {\n initPTS = initDTS = ptsNormalize(samples[0].pts - timeScale * timeOffset, refPTS);\n }\n samples = videoTrack.samples;\n if (samples.length) {\n let sample = samples[0];\n initPTS = Math.min(initPTS,ptsNormalize(sample.pts - timeScale * timeOffset, refPTS));\n initDTS = Math.min(initDTS,ptsNormalize(sample.dts - timeScale * timeOffset, refPTS));\n }\n if (initPTS !== Infinity) {\n const initPTSDelta = refPTS - initPTS;\n if (Math.abs(initPTSDelta) > 10 * timeScale) {\n logger.warn(`timestamp inconsistency, ${(initPTSDelta/timeScale).toFixed(3)}s delta against expected value: missing discontinuity ? reset initPTS/initDTS`);\n this._initPTS = initPTS;\n this._initDTS = initDTS;\n this.observer.trigger(Event.INIT_PTS_FOUND, { initPTS: initPTS});\n }\n }\n }\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 // if initSegment was generated without video samples, regenerate it again\n if (!audioTrack.timescale) {\n logger.warn('regenerate InitSegment as audio detected');\n this.generateIS(audioTrack,videoTrack,timeOffset);\n }\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 // if initSegment was generated without video samples, regenerate it again\n if (!videoTrack.timescale) {\n logger.warn('regenerate InitSegment as video detected');\n this.generateIS(audioTrack,videoTrack,timeOffset);\n }\n this.remuxVideo(videoTrack,timeOffset,contiguous,audioTrackLength, accurateTimeOffset);\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, accurateTimeOffset);\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);\n }\n\n generateIS(audioTrack,videoTrack,timeOffset) {\n var observer = this.observer,\n audioSamples = audioTrack.samples,\n videoSamples = videoTrack.samples,\n typeSupported = this.typeSupported,\n container = 'audio/mp4',\n tracks = {},\n data = { tracks : tracks },\n computePTSDTS = (this._initPTS === undefined),\n initPTS, initDTS;\n\n if (computePTSDTS) {\n initPTS = initDTS = Infinity;\n }\n if (audioTrack.config && audioSamples.length) {\n // let's use audio sampling rate as MP4 time scale.\n // rationale is that there is a integer nb of audio frames per audio sample (1024 for AAC)\n // using audio sampling rate here helps having an integer MP4 frame duration\n // this avoids potential rounding issue and AV sync issue\n audioTrack.timescale = audioTrack.samplerate;\n logger.log (`audio sampling rate : ${audioTrack.samplerate}`);\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 - audioTrack.inputTimeScale * timeOffset;\n }\n }\n\n if (videoTrack.sps && videoTrack.pps && videoSamples.length) {\n // let's use input time scale as MP4 video timescale\n // we use input time scale straight away to avoid rounding issues on frame duration / cts computation\n const inputTimeScale = videoTrack.inputTimeScale;\n videoTrack.timescale = inputTimeScale;\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 - inputTimeScale * timeOffset);\n initDTS = Math.min(initDTS,videoSamples[0].dts - inputTimeScale * timeOffset);\n this.observer.trigger(Event.INIT_PTS_FOUND, { initPTS: initPTS});\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, details: ErrorDetails.FRAG_PARSING_ERROR, fatal: false, reason: 'no audio/video samples found'});\n }\n }\n\n remuxVideo(track, timeOffset, contiguous, audioTrackLength, accurateTimeOffset) {\n var offset = 8,\n timeScale = track.timescale,\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;\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 // if parsed fragment is contiguous with last one, let's use last DTS value as reference\n let nextAvcDts = this.nextAvcDts;\n\n const isSafari = this.isSafari;\n\n // Safari does not like overlapping DTS on consecutive fragments. let's use nextAvcDts to overcome this if fragments are consecutive\n if (isSafari) {\n // 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 (if accurate) and next expected PTS OR\n // - less than 200 ms PTS gaps (timeScale/5)\n contiguous |= (inputSamples.length && nextAvcDts &&\n ((accurateTimeOffset && Math.abs(timeOffset-nextAvcDts/timeScale) < 0.1) ||\n Math.abs((inputSamples[0].pts-nextAvcDts-initDTS)) < timeScale/5)\n );\n }\n\n if (!contiguous) {\n // if not contiguous, let's use target timeOffset\n nextAvcDts = timeOffset*timeScale;\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 inputSamples.forEach(function(sample) {\n sample.pts = ptsNormalize(sample.pts-initDTS, nextAvcDts);\n sample.dts = ptsNormalize(sample.dts-initDTS, nextAvcDts);\n });\n\n // sort video samples by DTS then PTS then demux id order\n inputSamples.sort(function(a, b) {\n const deltadts = a.dts - b.dts;\n const deltapts = a.pts - b.pts;\n return deltadts ? deltadts : deltapts ? deltapts : (a.id - b.id);\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 // compute first DTS and last DTS, normalize them against reference value\n let sample = inputSamples[0];\n firstDTS = Math.max(sample.dts,0);\n firstPTS = Math.max(sample.pts,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;\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;\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(sample.dts,0);\n lastPTS = Math.max(sample.pts,0,lastDTS);\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)/(inputSamples.length-1));\n }\n\n let nbNalu = 0, naluLen = 0;\n for (let i = 0 ; i < nbSamples; i++) {\n // compute total/avc sample length and nb of NAL units\n let sample = inputSamples[i], units = sample.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 // normalize PTS/DTS\n if (isSafari) {\n // sample DTS is computed using a constant decoding offset (mp4SampleDuration) between samples\n sample.dts = firstDTS + i*mp4SampleDuration;\n } else {\n // ensure sample monotonic DTS\n sample.dts = Math.max(sample.dts,firstDTS);\n }\n // ensure that computed value is greater or equal than sample DTS\n sample.pts = Math.max(sample.pts , sample.dts);\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 = naluLen + (4 * nbNalu) + 8;\n try {\n mdat = new Uint8Array(mdatSize);\n } catch(err) {\n this.observer.trigger(Event.ERROR, {type : ErrorTypes.MUX_ERROR, 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,\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) * timeScale),\n deltaToFrameEnd = (audioTrackLength ? firstPTS + audioTrackLength * timeScale : 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 compositionTimeOffset = Math.round(avcSample.pts - avcSample.dts);\n } else {\n compositionTimeOffset = Math.max(0,mp4SampleDuration*Math.round((avcSample.pts - avcSample.dts)/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;\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 , track);\n track.samples = [];\n\n let data = {\n data1: moof,\n data2: mdat,\n startPTS: firstPTS / timeScale,\n endPTS: (lastPTS + mp4SampleDuration) / timeScale,\n startDTS: firstDTS / timeScale,\n endDTS: this.nextAvcDts / timeScale,\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 inputTimeScale = track.inputTimeScale,\n mp4timeScale = track.timescale,\n scaleFactor = inputTimeScale/mp4timeScale,\n mp4SampleDuration = track.isAAC ? 1024 : 1152,\n inputSampleDuration = mp4SampleDuration * scaleFactor,\n ptsNormalize = this._PTSNormalize,\n initDTS = this._initDTS,\n rawMPEG = !track.isAAC && this.typeSupported.mpeg;\n\n var offset,\n mp4Sample,\n fillFrame,\n mdat, moof,\n firstPTS, lastPTS,\n inputSamples = track.samples,\n outputSamples = [],\n nextAudioPts = this.nextAudioPts;\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 (if accurate) 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 contiguous |= (inputSamples.length && nextAudioPts &&\n ((accurateTimeOffset && Math.abs(timeOffset-nextAudioPts/inputTimeScale) < 0.1) ||\n Math.abs((inputSamples[0].pts-nextAudioPts-initDTS)) < 20*inputSampleDuration)\n );\n\n if (!contiguous) {\n // if fragments are not contiguous, let's use timeOffset to compute next Audio PTS\n nextAudioPts = timeOffset*inputTimeScale;\n }\n\n // compute normalized PTS\n inputSamples.forEach(function(sample) {\n sample.pts = sample.dts = ptsNormalize(sample.pts - initDTS, nextAudioPts);\n });\n\n // sort based on normalized PTS (this is to avoid sorting issues in case timestamp\n // reloop in the middle of our samples array)\n inputSamples.sort(function(a, b) {\n return a.pts - b.pts;\n });\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, nextPts = 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], delta;\n let pts = sample.pts;\n delta = pts - nextPts;\n\n const duration = Math.abs(1000*delta/inputTimeScale);\n\n // If we're overlapping by more than a duration, drop this sample\n if (delta <= -inputSampleDuration) {\n logger.warn(`Dropping 1 audio frame @ ${(nextPts/inputTimeScale).toFixed(3)}s due to ${duration} ms overlap.`);\n inputSamples.splice(i, 1);\n track.len -= sample.unit.length;\n // Don't touch nextPtsNorm or i\n }\n\n // Insert missing frames if:\n // 1: We're more than one frame away\n // 2: Not more than MAX_SILENT_FRAME_DURATION away\n // 3: currentTime (aka nextPtsNorm) is not 0\n else if (delta >= inputSampleDuration && duration < MAX_SILENT_FRAME_DURATION && nextPts) {\n var missing = Math.round(delta / inputSampleDuration);\n logger.warn(`Injecting ${missing} audio frame @ ${(nextPts/inputTimeScale).toFixed(3)}s due to ${Math.round(1000*delta/inputTimeScale)} ms gap.`);\n for (var j = 0; j < missing; j++) {\n let newStamp = Math.max(nextPts,0);\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 nextPts += inputSampleDuration;\n i++;\n }\n\n // Adjust sample to next expected pts\n sample.pts = sample.dts = nextPts;\n nextPts += inputSampleDuration;\n i++;\n } else {\n // Otherwise, just adjust pts\n if (Math.abs(delta) > (0.1 * inputSampleDuration)) {\n //logger.log(`Invalid frame delta ${Math.round(delta + inputSampleDuration)} at PTS ${Math.round(pts / 90)} (should be ${Math.round(inputSampleDuration)}).`);\n }\n sample.pts = sample.dts = nextPts;\n nextPts += inputSampleDuration;\n i++;\n }\n }\n }\n\n\n for (let j =0 , nbSamples = inputSamples.length; j < nbSamples ; j++) {\n let audioSample = inputSamples[j];\n let unit = audioSample.unit;\n let pts = audioSample.pts;\n //logger.log(`Audio/PTS:${Math.round(pts/90)}`);\n // if not first sample\n if (lastPTS !== undefined) {\n mp4Sample.duration = Math.round((pts - lastPTS) / scaleFactor);\n } else {\n let delta = Math.round(1000 * (pts - nextAudioPts) / inputTimeScale),\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 && delta < MAX_SILENT_FRAME_DURATION) {\n numMissingFrames = Math.round((pts - nextAudioPts) / inputSampleDuration);\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(`drop overlapping AAC sample, expected/parsed/delta:${(nextAudioPts/inputTimeScale).toFixed(3)}s/${(pts/inputTimeScale).toFixed(3)}s/${(-delta)}ms`);\n track.len -= unit.byteLength;\n continue;\n }\n // set PTS/DTS to expected PTS/DTS\n pts = nextAudioPts;\n }\n }\n // remember first PTS of our audioSamples, ensure value is positive\n firstPTS = Math.max(0, pts);\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 let mdatSize = rawMPEG ? track.len : track.len + 8;\n offset = rawMPEG ? 0 : 8;\n try {\n mdat = new Uint8Array(mdatSize);\n } catch(err) {\n this.observer.trigger(Event.ERROR, {type : ErrorTypes.MUX_ERROR, details: ErrorDetails.REMUX_ALLOC_ERROR, fatal: false, bytes : mdatSize, reason: `fail allocating audio mdat ${mdatSize}`});\n return;\n }\n if (!rawMPEG) {\n const 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 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 lastPTS = pts;\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 = nextAudioPts = lastPTS + scaleFactor * 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++, firstPTS / scaleFactor, track);\n }\n track.samples = [];\n const start = firstPTS / inputTimeScale;\n const end = nextAudioPts / inputTimeScale;\n const audioData = {\n data1: moof,\n data2: mdat,\n startPTS: start,\n endPTS: end,\n startDTS: start,\n endDTS: end,\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 inputTimeScale = track.inputTimeScale,\n mp4timeScale = track.samplerate ? track.samplerate : inputTimeScale,\n scaleFactor = inputTimeScale/mp4timeScale,\n nextAudioPts = this.nextAudioPts,\n\n // sync with video's timestamp\n startDTS = (nextAudioPts !== undefined ? nextAudioPts : videoData.startDTS * inputTimeScale) + this._initDTS,\n endDTS = videoData.endDTS * inputTimeScale + this._initDTS,\n // one sample's duration value\n sampleDuration = 1024,\n frameDuration = scaleFactor * 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 const inputTimeScale = track.inputTimeScale;\n const initPTS = this._initPTS;\n const initDTS = this._initDTS;\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 - initPTS) / inputTimeScale);\n sample.dts = ((sample.dts - initDTS) / inputTimeScale);\n }\n this.observer.trigger(Event.FRAG_PARSING_METADATA, {\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 const inputTimeScale = track.inputTimeScale;\n const initPTS = this._initPTS;\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 - initPTS) / inputTimeScale);\n }\n this.observer.trigger(Event.FRAG_PARSING_USERDATA, {\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) {\n this.observer = observer;\n }\n\n destroy() {\n }\n\n resetTimeStamp() {\n }\n\n resetInitSegment() {\n }\n\n remux(audioTrack,videoTrack,id3Track,textTrack,timeOffset, contiguous,accurateTimeOffset,rawData) {\n var observer = this.observer;\n var streamType = '';\n if (audioTrack) {\n streamType += 'audio';\n }\n if (videoTrack) {\n streamType += 'video';\n }\n observer.trigger(Event.FRAG_PARSING_DATA, {\n data1: rawData,\n startPTS: timeOffset,\n startDTS: timeOffset,\n type: streamType,\n nb: 1,\n dropped : 0\n });\n //notify end of parsing\n observer.trigger(Event.FRAG_PARSED);\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 = 100;\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) {\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 (let 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 const lastOutputScreen = this.lastOutputScreen;\n if (lastOutputScreen) {\n var prevLineTime = lastOutputScreen.rows[topRowIndex].cueStartTime;\n if(prevLineTime && prevLineTime < logger.time) {\n for (let i = 0; i < this.nrRollUpRows; i++) {\n this.rows[newRow-this.nrRollUpRows+i+1].copy(lastOutputScreen.rows[topRowIndex+i]);\n }\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);\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 }\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",
"import { fixLineBreaks } from './vttparser';\n\nconst 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\n // Give a slight bump to the endTime if it's equal to startTime to avoid a SyntaxError in IE\n if (startTime === endTime)\n {\n endTime += 0.0001;\n }\n\n cue = new VTTCue(startTime, endTime, fixLineBreaks(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",
"import BinarySearch from './binary-search';\n\nexport function findFragWithCC(fragments, CC) {\n return BinarySearch.search(fragments, (candidate) => {\n if (candidate.cc < CC) {\n return 1;\n } else if (candidate.cc > CC) {\n return -1;\n } else {\n return 0;\n }\n });\n}\n",
"/*\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 * 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",
"function 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\nconst TimeRanges = {\n toString : function(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\nmodule.exports = TimeRanges;\n",
"/**\n * Copyright 2013 vtt.js Contributors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport default (function() {\n if (typeof window !== 'undefined' && window.VTTCue) {\n return window.VTTCue;\n }\n\n var autoKeyword = 'auto';\n var directionSetting = {\n '': true,\n lr: true,\n rl: true\n };\n var alignSetting = {\n start: true,\n middle: true,\n end: true,\n left: true,\n right: true\n };\n\n function findDirectionSetting(value) {\n if (typeof value !== 'string') {\n return false;\n }\n var dir = directionSetting[value.toLowerCase()];\n return dir ? value.toLowerCase() : false;\n }\n\n function findAlignSetting(value) {\n if (typeof value !== 'string') {\n return false;\n }\n var align = alignSetting[value.toLowerCase()];\n return align ? value.toLowerCase() : false;\n }\n\n function extend(obj) {\n var i = 1;\n for (; i < arguments.length; i++) {\n var cobj = arguments[i];\n for (var p in cobj) {\n obj[p] = cobj[p];\n }\n }\n\n return obj;\n }\n\n function VTTCue(startTime, endTime, text) {\n var cue = this;\n var isIE8 = (function () {\n if (typeof navigator === 'undefined') {\n return;\n }\n return (/MSIE\\s8\\.0/).test(navigator.userAgent);\n })();\n var baseObj = {};\n\n if (isIE8) {\n cue = document.createElement('custom');\n } else {\n baseObj.enumerable = true;\n }\n\n /**\n * Shim implementation specific properties. These properties are not in\n * the spec.\n */\n\n // Lets us know when the VTTCue's data has changed in such a way that we need\n // to recompute its display state. This lets us compute its display state\n // lazily.\n cue.hasBeenReset = false;\n\n /**\n * VTTCue and TextTrackCue properties\n * http://dev.w3.org/html5/webvtt/#vttcue-interface\n */\n\n var _id = '';\n var _pauseOnExit = false;\n var _startTime = startTime;\n var _endTime = endTime;\n var _text = text;\n var _region = null;\n var _vertical = '';\n var _snapToLines = true;\n var _line = 'auto';\n var _lineAlign = 'start';\n var _position = 50;\n var _positionAlign = 'middle';\n var _size = 50;\n var _align = 'middle';\n\n Object.defineProperty(cue, 'id', extend({}, baseObj, {\n get: function () {\n return _id;\n },\n set: function (value) {\n _id = '' + value;\n }\n }));\n\n Object.defineProperty(cue, 'pauseOnExit', extend({}, baseObj, {\n get: function () {\n return _pauseOnExit;\n },\n set: function (value) {\n _pauseOnExit = !!value;\n }\n }));\n\n Object.defineProperty(cue, 'startTime', extend({}, baseObj, {\n get: function () {\n return _startTime;\n },\n set: function (value) {\n if (typeof value !== 'number') {\n throw new TypeError('Start time must be set to a number.');\n }\n _startTime = value;\n this.hasBeenReset = true;\n }\n }));\n\n Object.defineProperty(cue, 'endTime', extend({}, baseObj, {\n get: function () {\n return _endTime;\n },\n set: function (value) {\n if (typeof value !== 'number') {\n throw new TypeError('End time must be set to a number.');\n }\n _endTime = value;\n this.hasBeenReset = true;\n }\n }));\n\n Object.defineProperty(cue, 'text', extend({}, baseObj, {\n get: function () {\n return _text;\n },\n set: function (value) {\n _text = '' + value;\n this.hasBeenReset = true;\n }\n }));\n\n Object.defineProperty(cue, 'region', extend({}, baseObj, {\n get: function () {\n return _region;\n },\n set: function (value) {\n _region = value;\n this.hasBeenReset = true;\n }\n }));\n\n Object.defineProperty(cue, 'vertical', extend({}, baseObj, {\n get: function () {\n return _vertical;\n },\n set: function (value) {\n var setting = findDirectionSetting(value);\n // Have to check for false because the setting an be an empty string.\n if (setting === false) {\n throw new SyntaxError('An invalid or illegal string was specified.');\n }\n _vertical = setting;\n this.hasBeenReset = true;\n }\n }));\n\n Object.defineProperty(cue, 'snapToLines', extend({}, baseObj, {\n get: function () {\n return _snapToLines;\n },\n set: function (value) {\n _snapToLines = !!value;\n this.hasBeenReset = true;\n }\n }));\n\n Object.defineProperty(cue, 'line', extend({}, baseObj, {\n get: function () {\n return _line;\n },\n set: function (value) {\n if (typeof value !== 'number' && value !== autoKeyword) {\n throw new SyntaxError('An invalid number or illegal string was specified.');\n }\n _line = value;\n this.hasBeenReset = true;\n }\n }));\n\n Object.defineProperty(cue, 'lineAlign', extend({}, baseObj, {\n get: function () {\n return _lineAlign;\n },\n set: function (value) {\n var setting = findAlignSetting(value);\n if (!setting) {\n throw new SyntaxError('An invalid or illegal string was specified.');\n }\n _lineAlign = setting;\n this.hasBeenReset = true;\n }\n }));\n\n Object.defineProperty(cue, 'position', extend({}, baseObj, {\n get: function () {\n return _position;\n },\n set: function (value) {\n if (value < 0 || value > 100) {\n throw new Error('Position must be between 0 and 100.');\n }\n _position = value;\n this.hasBeenReset = true;\n }\n }));\n\n Object.defineProperty(cue, 'positionAlign', extend({}, baseObj, {\n get: function () {\n return _positionAlign;\n },\n set: function (value) {\n var setting = findAlignSetting(value);\n if (!setting) {\n throw new SyntaxError('An invalid or illegal string was specified.');\n }\n _positionAlign = setting;\n this.hasBeenReset = true;\n }\n }));\n\n Object.defineProperty(cue, 'size', extend({}, baseObj, {\n get: function () {\n return _size;\n },\n set: function (value) {\n if (value < 0 || value > 100) {\n throw new Error('Size must be between 0 and 100.');\n }\n _size = value;\n this.hasBeenReset = true;\n }\n }));\n\n Object.defineProperty(cue, 'align', extend({}, baseObj, {\n get: function () {\n return _align;\n },\n set: function (value) {\n var setting = findAlignSetting(value);\n if (!setting) {\n throw new SyntaxError('An invalid or illegal string was specified.');\n }\n _align = setting;\n this.hasBeenReset = true;\n }\n }));\n\n /**\n * Other <track> spec defined properties\n */\n\n // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#text-track-cue-display-state\n cue.displayState = undefined;\n\n if (isIE8) {\n return cue;\n }\n }\n\n /**\n * VTTCue methods\n */\n\n VTTCue.prototype.getCueAsHTML = function () {\n // Assume WebVTT.convertCueToDOMTree is on the global.\n var WebVTT = window.WebVTT;\n return WebVTT.convertCueToDOMTree(window, this.text);\n };\n\n return VTTCue;\n})();\n",
"/*\n * Source: https://github.com/mozilla/vtt.js/blob/master/dist/vtt.js#L1716\n */\n\nimport VTTCue from './vttcue';\n\nconst StringDecoder = function StringDecoder() {\n return {\n decode: function(data) {\n if (!data) {\n return '';\n }\n if (typeof data !== 'string') {\n throw new Error('Error - expected string data.');\n }\n return decodeURIComponent(encodeURIComponent(data));\n },\n };\n };\n\nfunction VTTParser() {\n this.window = window;\n this.state = 'INITIAL';\n this.buffer = '';\n this.decoder = new StringDecoder();\n this.regionList = [];\n}\n\n\n// Try to parse input as a time stamp.\nfunction parseTimeStamp(input) {\n\n function computeSeconds(h, m, s, f) {\n return (h | 0) * 3600 + (m | 0) * 60 + (s | 0) + (f | 0) / 1000;\n }\n\n var m = input.match(/^(\\d+):(\\d{2})(:\\d{2})?\\.(\\d{3})/);\n if (!m) {\n return null;\n }\n\n if (m[3]) {\n // Timestamp takes the form of [hours]:[minutes]:[seconds].[milliseconds]\n return computeSeconds(m[1], m[2], m[3].replace(':', ''), m[4]);\n } else if (m[1] > 59) {\n // Timestamp takes the form of [hours]:[minutes].[milliseconds]\n // First position is hours as it's over 59.\n return computeSeconds(m[1], m[2], 0, m[4]);\n } else {\n // Timestamp takes the form of [minutes]:[seconds].[milliseconds]\n return computeSeconds(0, m[1], m[2], m[4]);\n }\n}\n\n// A settings object holds key/value pairs and will ignore anything but the first\n// assignment to a specific key.\nfunction Settings() {\n this.values = Object.create(null);\n}\n\nSettings.prototype = {\n // Only accept the first assignment to any key.\n set: function(k, v) {\n if (!this.get(k) && v !== '') {\n this.values[k] = v;\n }\n },\n // Return the value for a key, or a default value.\n // If 'defaultKey' is passed then 'dflt' is assumed to be an object with\n // a number of possible default values as properties where 'defaultKey' is\n // the key of the property that will be chosen; otherwise it's assumed to be\n // a single value.\n get: function(k, dflt, defaultKey) {\n if (defaultKey) {\n return this.has(k) ? this.values[k] : dflt[defaultKey];\n }\n return this.has(k) ? this.values[k] : dflt;\n },\n // Check whether we have a value for a key.\n has: function(k) {\n return k in this.values;\n },\n // Accept a setting if its one of the given alternatives.\n alt: function(k, v, a) {\n for (var n = 0; n < a.length; ++n) {\n if (v === a[n]) {\n this.set(k, v);\n break;\n }\n }\n },\n // Accept a setting if its a valid (signed) integer.\n integer: function(k, v) {\n if (/^-?\\d+$/.test(v)) { // integer\n this.set(k, parseInt(v, 10));\n }\n },\n // Accept a setting if its a valid percentage.\n percent: function(k, v) {\n var m;\n if ((m = v.match(/^([\\d]{1,3})(\\.[\\d]*)?%$/))) {\n v = parseFloat(v);\n if (v >= 0 && v <= 100) {\n this.set(k, v);\n return true;\n }\n }\n return false;\n }\n};\n\n// Helper function to parse input into groups separated by 'groupDelim', and\n// interprete each group as a key/value pair separated by 'keyValueDelim'.\nfunction parseOptions(input, callback, keyValueDelim, groupDelim) {\n var groups = groupDelim ? input.split(groupDelim) : [input];\n for (var i in groups) {\n if (typeof groups[i] !== 'string') {\n continue;\n }\n var kv = groups[i].split(keyValueDelim);\n if (kv.length !== 2) {\n continue;\n }\n var k = kv[0];\n var v = kv[1];\n callback(k, v);\n }\n}\n\nvar defaults = new VTTCue(0, 0, 0);\n// 'middle' was changed to 'center' in the spec: https://github.com/w3c/webvtt/pull/244\n// Chrome and Safari don't yet support this change, but FF does\nvar center = defaults.align === 'middle' ? 'middle' : 'center';\n\nfunction parseCue(input, cue, regionList) {\n // Remember the original input if we need to throw an error.\n var oInput = input;\n // 4.1 WebVTT timestamp\n function consumeTimeStamp() {\n var ts = parseTimeStamp(input);\n if (ts === null) {\n throw new Error('Malformed timestamp: ' + oInput);\n }\n // Remove time stamp from input.\n input = input.replace(/^[^\\sa-zA-Z-]+/, '');\n return ts;\n }\n\n // 4.4.2 WebVTT cue settings\n function consumeCueSettings(input, cue) {\n var settings = new Settings();\n\n parseOptions(input, function(k, v) {\n switch (k) {\n case 'region':\n // Find the last region we parsed with the same region id.\n for (var i = regionList.length - 1; i >= 0; i--) {\n if (regionList[i].id === v) {\n settings.set(k, regionList[i].region);\n break;\n }\n }\n break;\n case 'vertical':\n settings.alt(k, v, ['rl', 'lr']);\n break;\n case 'line':\n var vals = v.split(','),\n vals0 = vals[0];\n settings.integer(k, vals0);\n if (settings.percent(k, vals0)) {\n settings.set('snapToLines', false);\n }\n settings.alt(k, vals0, ['auto']);\n if (vals.length === 2) {\n settings.alt('lineAlign', vals[1], ['start', center, 'end']);\n }\n break;\n case 'position':\n vals = v.split(',');\n settings.percent(k, vals[0]);\n if (vals.length === 2) {\n settings.alt('positionAlign', vals[1], ['start', center, 'end', 'line-left', 'line-right', 'auto']);\n }\n break;\n case 'size':\n settings.percent(k, v);\n break;\n case 'align':\n settings.alt(k, v, ['start', center, 'end', 'left', 'right']);\n break;\n }\n }, /:/, /\\s/);\n\n // Apply default values for any missing fields.\n cue.region = settings.get('region', null);\n cue.vertical = settings.get('vertical', '');\n var line = settings.get('line', 'auto');\n if (line === 'auto' && defaults.line === -1) {\n // set numeric line number for Safari\n line = -1;\n }\n cue.line = line;\n cue.lineAlign = settings.get('lineAlign', 'start');\n cue.snapToLines = settings.get('snapToLines', true);\n cue.size = settings.get('size', 100);\n cue.align = settings.get('align', center);\n var position = settings.get('position', 'auto');\n if (position === 'auto' && defaults.position === 50) {\n // set numeric position for Safari\n position = cue.align === 'start' || cue.align === 'left' ? 0 : cue.align === 'end' || cue.align === 'right' ? 100 : 50;\n }\n cue.position = position;\n }\n\n function skipWhitespace() {\n input = input.replace(/^\\s+/, '');\n }\n\n // 4.1 WebVTT cue timings.\n skipWhitespace();\n cue.startTime = consumeTimeStamp(); // (1) collect cue start time\n skipWhitespace();\n if (input.substr(0, 3) !== '-->') { // (3) next characters must match '-->'\n throw new Error('Malformed time stamp (time stamps must be separated by \\'-->\\'): ' +\n oInput);\n }\n input = input.substr(3);\n skipWhitespace();\n cue.endTime = consumeTimeStamp(); // (5) collect cue end time\n\n // 4.1 WebVTT cue settings list.\n skipWhitespace();\n consumeCueSettings(input, cue);\n}\n\nfunction fixLineBreaks(input) {\n return input.replace(/<br(?: \\/)?>/gi, '\\n');\n}\n\nVTTParser.prototype = {\n parse: function(data) {\n var self = this;\n\n // If there is no data then we won't decode it, but will just try to parse\n // whatever is in buffer already. This may occur in circumstances, for\n // example when flush() is called.\n if (data) {\n // Try to decode the data that we received.\n self.buffer += self.decoder.decode(data, {stream: true});\n }\n\n function collectNextLine() {\n var buffer = self.buffer;\n var pos = 0;\n\n buffer = fixLineBreaks(buffer);\n\n while (pos < buffer.length && buffer[pos] !== '\\r' && buffer[pos] !== '\\n') {\n ++pos;\n }\n var line = buffer.substr(0, pos);\n // Advance the buffer early in case we fail below.\n if (buffer[pos] === '\\r') {\n ++pos;\n }\n if (buffer[pos] === '\\n') {\n ++pos;\n }\n self.buffer = buffer.substr(pos);\n return line;\n }\n\n // 3.2 WebVTT metadata header syntax\n function parseHeader(input) {\n parseOptions(input, function(k, v) {\n switch (k) {\n case 'Region':\n // 3.3 WebVTT region metadata header syntax\n console.log('parse region', v);\n //parseRegion(v);\n break;\n }\n }, /:/);\n }\n\n // 5.1 WebVTT file parsing.\n try {\n var line;\n if (self.state === 'INITIAL') {\n // We can't start parsing until we have the first line.\n if (!/\\r\\n|\\n/.test(self.buffer)) {\n return this;\n }\n\n line = collectNextLine();\n\n var m = line.match(/^WEBVTT([ \\t].*)?$/);\n if (!m || !m[0]) {\n throw new Error('Malformed WebVTT signature.');\n }\n\n self.state = 'HEADER';\n }\n\n var alreadyCollectedLine = false;\n while (self.buffer) {\n // We can't parse a line until we have the full line.\n if (!/\\r\\n|\\n/.test(self.buffer)) {\n return this;\n }\n\n if (!alreadyCollectedLine) {\n line = collectNextLine();\n } else {\n alreadyCollectedLine = false;\n }\n\n switch (self.state) {\n case 'HEADER':\n // 13-18 - Allow a header (metadata) under the WEBVTT line.\n if (/:/.test(line)) {\n parseHeader(line);\n } else if (!line) {\n // An empty line terminates the header and starts the body (cues).\n self.state = 'ID';\n }\n continue;\n case 'NOTE':\n // Ignore NOTE blocks.\n if (!line) {\n self.state = 'ID';\n }\n continue;\n case 'ID':\n // Check for the start of NOTE blocks.\n if (/^NOTE($|[ \\t])/.test(line)) {\n self.state = 'NOTE';\n break;\n }\n // 19-29 - Allow any number of line terminators, then initialize new cue values.\n if (!line) {\n continue;\n }\n self.cue = new VTTCue(0, 0, '');\n self.state = 'CUE';\n // 30-39 - Check if self line contains an optional identifier or timing data.\n if (line.indexOf('-->') === -1) {\n self.cue.id = line;\n continue;\n }\n // Process line as start of a cue.\n /*falls through*/\n case 'CUE':\n // 40 - Collect cue timings and settings.\n try {\n parseCue(line, self.cue, self.regionList);\n } catch (e) {\n // In case of an error ignore rest of the cue.\n self.cue = null;\n self.state = 'BADCUE';\n continue;\n }\n self.state = 'CUETEXT';\n continue;\n case 'CUETEXT':\n var hasSubstring = line.indexOf('-->') !== -1;\n // 34 - If we have an empty line then report the cue.\n // 35 - If we have the special substring '-->' then report the cue,\n // but do not collect the line as we need to process the current\n // one as a new cue.\n if (!line || hasSubstring && (alreadyCollectedLine = true)) {\n // We are done parsing self cue.\n if (self.oncue) {\n self.oncue(self.cue);\n }\n self.cue = null;\n self.state = 'ID';\n continue;\n }\n if (self.cue.text) {\n self.cue.text += '\\n';\n }\n self.cue.text += line;\n continue;\n case 'BADCUE': // BADCUE\n // 54-62 - Collect and discard the remaining cue.\n if (!line) {\n self.state = 'ID';\n }\n continue;\n }\n }\n } catch (e) {\n\n // If we are currently parsing a cue, report what we have.\n if (self.state === 'CUETEXT' && self.cue && self.oncue) {\n self.oncue(self.cue);\n }\n self.cue = null;\n // Enter BADWEBVTT state if header was not parsed correctly otherwise\n // another exception occurred so enter BADCUE state.\n self.state = self.state === 'INITIAL' ? 'BADWEBVTT' : 'BADCUE';\n }\n return this;\n },\n flush: function() {\n var self = this;\n try {\n // Finish decoding the stream.\n self.buffer += self.decoder.decode();\n // Synthesize the end of the current cue or region.\n if (self.cue || self.state === 'HEADER') {\n self.buffer += '\\n\\n';\n self.parse();\n }\n // If we've flushed, parsed, and we're still on the INITIAL state then\n // that means we don't have enough of the stream to parse the first\n // line.\n if (self.state === 'INITIAL') {\n throw new Error('Malformed WebVTT signature.');\n }\n } catch (e) {\n throw e;\n }\n if (self.onflush) {\n self.onflush();\n }\n return this;\n }\n};\n\nexport { fixLineBreaks };\n\nexport default VTTParser;\n",
"import VTTParser from './vttparser';\n\n// String.prototype.startsWith is not supported in IE11\nconst startsWith = function(inputString, searchString, position) {\n return inputString.substr(position || 0, searchString.length) === searchString;\n};\n\nconst cueString2millis = function(timeString) {\n let ts = parseInt(timeString.substr(-3));\n let secs = parseInt(timeString.substr(-6,2));\n let mins = parseInt(timeString.substr(-9,2));\n let hours = timeString.length > 9 ? parseInt(timeString.substr(0, timeString.indexOf(':'))) : 0;\n\n if (isNaN(ts) || isNaN(secs) || isNaN(mins) || isNaN(hours)) {\n return -1;\n }\n\n ts += 1000 * secs;\n ts += 60*1000 * mins;\n ts += 60*60*1000 * hours;\n\n return ts;\n};\n\n// From https://github.com/darkskyapp/string-hash\nconst hash = function(text) {\n let hash = 5381;\n let i = text.length;\n while (i) {\n hash = (hash * 33) ^ text.charCodeAt(--i);\n }\n return (hash >>> 0).toString();\n};\n\nconst calculateOffset = function(vttCCs, cc, presentationTime) {\n let currCC = vttCCs[cc];\n let prevCC = vttCCs[currCC.prevCC];\n\n // This is the first discontinuity or cues have been processed since the last discontinuity\n // Offset = current discontinuity time\n if (!prevCC || (!prevCC.new && currCC.new)) {\n vttCCs.ccOffset = vttCCs.presentationOffset = currCC.start;\n currCC.new = false;\n return;\n }\n\n // There have been discontinuities since cues were last parsed.\n // Offset = time elapsed\n while (prevCC && prevCC.new) {\n vttCCs.ccOffset += currCC.start - prevCC.start;\n currCC.new = false;\n currCC = prevCC;\n prevCC = vttCCs[currCC.prevCC];\n }\n\n vttCCs.presentationOffset = presentationTime;\n};\n\nconst WebVTTParser = {\n parse: function(vttByteArray, syncPTS, vttCCs, cc, callBack, errorCallBack) {\n // Convert byteArray into string, replacing any somewhat exotic linefeeds with \"\\n\", then split on that character.\n let re = /\\r\\n|\\n\\r|\\n|\\r/g;\n let vttLines = String.fromCharCode.apply(null, new Uint8Array(vttByteArray)).trim().replace(re, '\\n').split('\\n');\n let cueTime = '00:00.000';\n let mpegTs = 0;\n let localTime = 0;\n let presentationTime = 0;\n let cues = [];\n let parsingError;\n let inHeader = true;\n // let VTTCue = VTTCue || window.TextTrackCue;\n\n // Create parser object using VTTCue with TextTrackCue fallback on certain browsers.\n let parser = new VTTParser();\n\n parser.oncue = function(cue) {\n // Adjust cue timing; clamp cues to start no earlier than - and drop cues that don't end after - 0 on timeline.\n let currCC = vttCCs[cc];\n let cueOffset = vttCCs.ccOffset;\n\n // Update offsets for new discontinuities\n if (currCC && currCC.new) {\n if (localTime !== undefined) {\n // When local time is provided, offset = discontinuity start time - local time\n cueOffset = vttCCs.ccOffset = currCC.start;\n } else {\n calculateOffset(vttCCs, cc, presentationTime);\n }\n }\n\n if (presentationTime) {\n // If we have MPEGTS, offset = presentation time + discontinuity offset\n cueOffset = presentationTime + vttCCs.ccOffset - vttCCs.presentationOffset;\n }\n\n cue.startTime += cueOffset - localTime;\n cue.endTime += cueOffset - localTime;\n\n // Create a unique hash id for a cue based on start/end times and text.\n // This helps timeline-controller to avoid showing repeated captions.\n cue.id = hash(cue.startTime) + hash(cue.endTime) + hash(cue.text);\n\n // Fix encoding of special characters. TODO: Test with all sorts of weird characters.\n cue.text = decodeURIComponent(escape(cue.text));\n if (cue.endTime > 0) {\n cues.push(cue);\n }\n };\n\n parser.onparsingerror = function(e) {\n parsingError = e;\n };\n\n parser.onflush = function() {\n if (parsingError && errorCallBack) {\n errorCallBack(parsingError);\n return;\n }\n callBack(cues);\n };\n\n // Go through contents line by line.\n vttLines.forEach(line => {\n if (inHeader) {\n // Look for X-TIMESTAMP-MAP in header.\n if (startsWith(line, 'X-TIMESTAMP-MAP=')) {\n // Once found, no more are allowed anyway, so stop searching.\n inHeader = false;\n // Extract LOCAL and MPEGTS.\n line.substr(16).split(',').forEach(timestamp => {\n if (startsWith(timestamp, 'LOCAL:')) {\n cueTime = timestamp.substr(6);\n } else if (startsWith(timestamp, 'MPEGTS:')) {\n mpegTs = parseInt(timestamp.substr(7));\n }\n });\n try {\n // Calculate subtitle offset in milliseconds.\n // If sync PTS is less than zero, we have a 33-bit wraparound, which is fixed by adding 2^33 = 8589934592.\n syncPTS = syncPTS < 0 ? syncPTS + 8589934592 : syncPTS;\n // Adjust MPEGTS by sync PTS.\n mpegTs -= syncPTS;\n // Convert cue time to seconds\n localTime = cueString2millis(cueTime) / 1000;\n // Convert MPEGTS to seconds from 90kHz.\n presentationTime = mpegTs / 90000;\n\n if (localTime === -1) {\n parsingError = new Error(`Malformed X-TIMESTAMP-MAP: ${line}`);\n }\n }\n catch(e) {\n parsingError = new Error(`Malformed X-TIMESTAMP-MAP: ${line}`);\n }\n // Return without parsing X-TIMESTAMP-MAP line.\n return;\n } else if (line === '') {\n inHeader = false;\n }\n }\n // Parse line by default.\n parser.parse(line+'\\n');\n });\n\n parser.flush();\n }\n};\n\n\nmodule.exports = WebVTTParser;\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 let stats = this.stats;\n stats.tfirst = 0;\n stats.loaded = 0;\n const xhrSetup = this.xhrSetup;\n\n try {\n if (xhrSetup) {\n try {\n xhrSetup(xhr, context.url);\n } catch (e) {\n // fix xhrSetup: (xhr, url) => {xhr.setRequestHeader(\"Content-Language\", \"test\");}\n // not working, as xhr.setRequestHeader expects xhr.readyState === OPEN\n xhr.open('GET', context.url, true);\n xhrSetup(xhr, context.url);\n }\n }\n if (!xhr.readyState) {\n xhr.open('GET', context.url, true);\n }\n } catch (e) {\n // IE11 throws an exception on xhr.open if attempting to access an HTTP resource over HTTPS\n this.callbacks.onError({ code : xhr.status, text: e.message }, context, xhr);\n return;\n }\n\n if (context.rangeEnd) {\n xhr.setRequestHeader('Range','bytes=' + context.rangeStart + '-' + (context.rangeEnd-1));\n }\n xhr.onreadystatechange = this.readystatechange.bind(this);\n xhr.onprogress = this.loadprogress.bind(this);\n xhr.responseType = context.responseType;\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 // >= HEADERS_RECEIVED\n if (readyState >=2) {\n // clear xhr timeout and rearm it if readyState less than 4\n window.clearTimeout(this.requestTimeout);\n if (stats.tfirst === 0) {\n stats.tfirst = Math.max(performance.now(), 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, xhr);\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, xhr);\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 } else {\n // readyState >= 2 AND readyState !==4 (readyState = HEADERS_RECEIVED || LOADING) rearm timeout as xhr not finished yet\n this.requestTimeout = window.setTimeout(this.loadtimeout.bind(this), config.timeout);\n }\n }\n }\n\n loadtimeout() {\n logger.warn(`timeout while loading ${this.context.url}` );\n this.callbacks.onTimeout(this.stats, this.context, null);\n }\n\n loadprogress(event) {\n var xhr = event.currentTarget,\n stats = this.stats;\n\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 // third arg is to provide on progress data\n onProgress(stats, this.context, null, xhr);\n }\n }\n}\n\nexport default XhrLoader;\n"
]
}