chjcken

hls.js

May 22nd, 2016
766
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Hls = f()}})(function(){var define,module,exports;return (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})({1:[function(require,module,exports){
  2. // Copyright Joyent, Inc. and other Node contributors.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a
  5. // copy of this software and associated documentation files (the
  6. // "Software"), to deal in the Software without restriction, including
  7. // without limitation the rights to use, copy, modify, merge, publish,
  8. // distribute, sublicense, and/or sell copies of the Software, and to permit
  9. // persons to whom the Software is furnished to do so, subject to the
  10. // following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included
  13. // in all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  16. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  17. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  18. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  19. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  20. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  21. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  22.  
  23. function EventEmitter() {
  24.   this._events = this._events || {};
  25.   this._maxListeners = this._maxListeners || undefined;
  26. }
  27. module.exports = EventEmitter;
  28.  
  29. // Backwards-compat with node 0.10.x
  30. EventEmitter.EventEmitter = EventEmitter;
  31.  
  32. EventEmitter.prototype._events = undefined;
  33. EventEmitter.prototype._maxListeners = undefined;
  34.  
  35. // By default EventEmitters will print a warning if more than 10 listeners are
  36. // added to it. This is a useful default which helps finding memory leaks.
  37. EventEmitter.defaultMaxListeners = 10;
  38.  
  39. // Obviously not all Emitters should be limited to 10. This function allows
  40. // that to be increased. Set to zero for unlimited.
  41. EventEmitter.prototype.setMaxListeners = function(n) {
  42.   if (!isNumber(n) || n < 0 || isNaN(n))
  43.     throw TypeError('n must be a positive number');
  44.   this._maxListeners = n;
  45.   return this;
  46. };
  47.  
  48. EventEmitter.prototype.emit = function(type) {
  49.   var er, handler, len, args, i, listeners;
  50.  
  51.   if (!this._events)
  52.     this._events = {};
  53.  
  54.   // If there is no 'error' event listener then throw.
  55.   if (type === 'error') {
  56.     if (!this._events.error ||
  57.         (isObject(this._events.error) && !this._events.error.length)) {
  58.       er = arguments[1];
  59.       if (er instanceof Error) {
  60.         throw er; // Unhandled 'error' event
  61.       }
  62.       throw TypeError('Uncaught, unspecified "error" event.');
  63.     }
  64.   }
  65.  
  66.   handler = this._events[type];
  67.  
  68.   if (isUndefined(handler))
  69.     return false;
  70.  
  71.   if (isFunction(handler)) {
  72.     switch (arguments.length) {
  73.       // fast cases
  74.       case 1:
  75.         handler.call(this);
  76.         break;
  77.       case 2:
  78.         handler.call(this, arguments[1]);
  79.         break;
  80.       case 3:
  81.         handler.call(this, arguments[1], arguments[2]);
  82.         break;
  83.       // slower
  84.       default:
  85.         args = Array.prototype.slice.call(arguments, 1);
  86.         handler.apply(this, args);
  87.     }
  88.   } else if (isObject(handler)) {
  89.     args = Array.prototype.slice.call(arguments, 1);
  90.     listeners = handler.slice();
  91.     len = listeners.length;
  92.     for (i = 0; i < len; i++)
  93.       listeners[i].apply(this, args);
  94.   }
  95.  
  96.   return true;
  97. };
  98.  
  99. EventEmitter.prototype.addListener = function(type, listener) {
  100.   var m;
  101.  
  102.   if (!isFunction(listener))
  103.     throw TypeError('listener must be a function');
  104.  
  105.   if (!this._events)
  106.     this._events = {};
  107.  
  108.   // To avoid recursion in the case that type === "newListener"! Before
  109.   // adding it to the listeners, first emit "newListener".
  110.   if (this._events.newListener)
  111.     this.emit('newListener', type,
  112.               isFunction(listener.listener) ?
  113.               listener.listener : listener);
  114.  
  115.   if (!this._events[type])
  116.     // Optimize the case of one listener. Don't need the extra array object.
  117.     this._events[type] = listener;
  118.   else if (isObject(this._events[type]))
  119.     // If we've already got an array, just append.
  120.     this._events[type].push(listener);
  121.   else
  122.     // Adding the second element, need to change to array.
  123.     this._events[type] = [this._events[type], listener];
  124.  
  125.   // Check for listener leak
  126.   if (isObject(this._events[type]) && !this._events[type].warned) {
  127.     if (!isUndefined(this._maxListeners)) {
  128.       m = this._maxListeners;
  129.     } else {
  130.       m = EventEmitter.defaultMaxListeners;
  131.     }
  132.  
  133.     if (m && m > 0 && this._events[type].length > m) {
  134.       this._events[type].warned = true;
  135.       console.error('(node) warning: possible EventEmitter memory ' +
  136.                     'leak detected. %d listeners added. ' +
  137.                     'Use emitter.setMaxListeners() to increase limit.',
  138.                     this._events[type].length);
  139.       if (typeof console.trace === 'function') {
  140.         // not supported in IE 10
  141.         console.trace();
  142.       }
  143.     }
  144.   }
  145.  
  146.   return this;
  147. };
  148.  
  149. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  150.  
  151. EventEmitter.prototype.once = function(type, listener) {
  152.   if (!isFunction(listener))
  153.     throw TypeError('listener must be a function');
  154.  
  155.   var fired = false;
  156.  
  157.   function g() {
  158.     this.removeListener(type, g);
  159.  
  160.     if (!fired) {
  161.       fired = true;
  162.       listener.apply(this, arguments);
  163.     }
  164.   }
  165.  
  166.   g.listener = listener;
  167.   this.on(type, g);
  168.  
  169.   return this;
  170. };
  171.  
  172. // emits a 'removeListener' event iff the listener was removed
  173. EventEmitter.prototype.removeListener = function(type, listener) {
  174.   var list, position, length, i;
  175.  
  176.   if (!isFunction(listener))
  177.     throw TypeError('listener must be a function');
  178.  
  179.   if (!this._events || !this._events[type])
  180.     return this;
  181.  
  182.   list = this._events[type];
  183.   length = list.length;
  184.   position = -1;
  185.  
  186.   if (list === listener ||
  187.       (isFunction(list.listener) && list.listener === listener)) {
  188.     delete this._events[type];
  189.     if (this._events.removeListener)
  190.       this.emit('removeListener', type, listener);
  191.  
  192.   } else if (isObject(list)) {
  193.     for (i = length; i-- > 0;) {
  194.       if (list[i] === listener ||
  195.           (list[i].listener && list[i].listener === listener)) {
  196.         position = i;
  197.         break;
  198.       }
  199.     }
  200.  
  201.     if (position < 0)
  202.       return this;
  203.  
  204.     if (list.length === 1) {
  205.       list.length = 0;
  206.       delete this._events[type];
  207.     } else {
  208.       list.splice(position, 1);
  209.     }
  210.  
  211.     if (this._events.removeListener)
  212.       this.emit('removeListener', type, listener);
  213.   }
  214.  
  215.   return this;
  216. };
  217.  
  218. EventEmitter.prototype.removeAllListeners = function(type) {
  219.   var key, listeners;
  220.  
  221.   if (!this._events)
  222.     return this;
  223.  
  224.   // not listening for removeListener, no need to emit
  225.   if (!this._events.removeListener) {
  226.     if (arguments.length === 0)
  227.       this._events = {};
  228.     else if (this._events[type])
  229.       delete this._events[type];
  230.     return this;
  231.   }
  232.  
  233.   // emit removeListener for all listeners on all events
  234.   if (arguments.length === 0) {
  235.     for (key in this._events) {
  236.       if (key === 'removeListener') continue;
  237.       this.removeAllListeners(key);
  238.     }
  239.     this.removeAllListeners('removeListener');
  240.     this._events = {};
  241.     return this;
  242.   }
  243.  
  244.   listeners = this._events[type];
  245.  
  246.   if (isFunction(listeners)) {
  247.     this.removeListener(type, listeners);
  248.   } else if (listeners) {
  249.     // LIFO order
  250.     while (listeners.length)
  251.       this.removeListener(type, listeners[listeners.length - 1]);
  252.   }
  253.   delete this._events[type];
  254.  
  255.   return this;
  256. };
  257.  
  258. EventEmitter.prototype.listeners = function(type) {
  259.   var ret;
  260.   if (!this._events || !this._events[type])
  261.     ret = [];
  262.   else if (isFunction(this._events[type]))
  263.     ret = [this._events[type]];
  264.   else
  265.     ret = this._events[type].slice();
  266.   return ret;
  267. };
  268.  
  269. EventEmitter.prototype.listenerCount = function(type) {
  270.   if (this._events) {
  271.     var evlistener = this._events[type];
  272.  
  273.     if (isFunction(evlistener))
  274.       return 1;
  275.     else if (evlistener)
  276.       return evlistener.length;
  277.   }
  278.   return 0;
  279. };
  280.  
  281. EventEmitter.listenerCount = function(emitter, type) {
  282.   return emitter.listenerCount(type);
  283. };
  284.  
  285. function isFunction(arg) {
  286.   return typeof arg === 'function';
  287. }
  288.  
  289. function isNumber(arg) {
  290.   return typeof arg === 'number';
  291. }
  292.  
  293. function isObject(arg) {
  294.   return typeof arg === 'object' && arg !== null;
  295. }
  296.  
  297. function isUndefined(arg) {
  298.   return arg === void 0;
  299. }
  300.  
  301. },{}],2:[function(require,module,exports){
  302. var bundleFn = arguments[3];
  303. var sources = arguments[4];
  304. var cache = arguments[5];
  305.  
  306. var stringify = JSON.stringify;
  307.  
  308. module.exports = function (fn, options) {
  309.     var wkey;
  310.     var cacheKeys = Object.keys(cache);
  311.  
  312.     for (var i = 0, l = cacheKeys.length; i < l; i++) {
  313.         var key = cacheKeys[i];
  314.         var exp = cache[key].exports;
  315.         // Using babel as a transpiler to use esmodule, the export will always
  316.         // be an object with the default export as a property of it. To ensure
  317.         // the existing api and babel esmodule exports are both supported we
  318.         // check for both
  319.         if (exp === fn || exp && exp.default === fn) {
  320.             wkey = key;
  321.             break;
  322.         }
  323.     }
  324.  
  325.     if (!wkey) {
  326.         wkey = Math.floor(Math.pow(16, 8) * Math.random()).toString(16);
  327.         var wcache = {};
  328.         for (var i = 0, l = cacheKeys.length; i < l; i++) {
  329.             var key = cacheKeys[i];
  330.             wcache[key] = key;
  331.         }
  332.         sources[wkey] = [
  333.             Function(['require','module','exports'], '(' + fn + ')(self)'),
  334.             wcache
  335.         ];
  336.     }
  337.     var skey = Math.floor(Math.pow(16, 8) * Math.random()).toString(16);
  338.  
  339.     var scache = {}; scache[wkey] = wkey;
  340.     sources[skey] = [
  341.         Function(['require'], (
  342.             // try to call default if defined to also support babel esmodule
  343.             // exports
  344.             'var f = require(' + stringify(wkey) + ');' +
  345.             '(f.default ? f.default : f)(self);'
  346.         )),
  347.         scache
  348.     ];
  349.  
  350.     var src = '(' + bundleFn + ')({'
  351.         + Object.keys(sources).map(function (key) {
  352.             return stringify(key) + ':['
  353.                 + sources[key][0]
  354.                 + ',' + stringify(sources[key][1]) + ']'
  355.             ;
  356.         }).join(',')
  357.         + '},{},[' + stringify(skey) + '])'
  358.     ;
  359.  
  360.     var URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  361.  
  362.     var blob = new Blob([src], { type: 'text/javascript' });
  363.     if (options && options.bare) { return blob; }
  364.     var workerUrl = URL.createObjectURL(blob);
  365.     var worker = new Worker(workerUrl);
  366.     if (typeof URL.revokeObjectURL == "function") {
  367.       URL.revokeObjectURL(workerUrl);
  368.     }
  369.     return worker;
  370. };
  371.  
  372. },{}],3:[function(require,module,exports){
  373. 'use strict';
  374.  
  375. Object.defineProperty(exports, "__esModule", {
  376.   value: true
  377. });
  378.  
  379. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  380.  
  381. var _events = require('../events');
  382.  
  383. var _events2 = _interopRequireDefault(_events);
  384.  
  385. var _eventHandler = require('../event-handler');
  386.  
  387. var _eventHandler2 = _interopRequireDefault(_eventHandler);
  388.  
  389. var _bufferHelper = require('../helper/buffer-helper');
  390.  
  391. var _bufferHelper2 = _interopRequireDefault(_bufferHelper);
  392.  
  393. var _errors = require('../errors');
  394.  
  395. var _logger = require('../utils/logger');
  396.  
  397. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  398.  
  399. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  400.  
  401. function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
  402.  
  403. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /*
  404.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 * simple ABR Controller
  405.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 *  - compute next level based on last fragment bw heuristics
  406.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 *  - implement an abandon rules triggered if we have less than 2 frag buffered and if computed bw shows that we risk buffer stalling
  407.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 */
  408.  
  409. var AbrController = function (_EventHandler) {
  410.   _inherits(AbrController, _EventHandler);
  411.  
  412.   function AbrController(hls) {
  413.     _classCallCheck(this, AbrController);
  414.  
  415.     var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(AbrController).call(this, hls, _events2.default.FRAG_LOADING, _events2.default.FRAG_LOAD_PROGRESS, _events2.default.FRAG_LOADED, _events2.default.ERROR));
  416.  
  417.     _this.lastLoadedFragLevel = 0;
  418.     _this._autoLevelCapping = -1;
  419.     _this._nextAutoLevel = -1;
  420.     _this.hls = hls;
  421.     _this.onCheck = _this.abandonRulesCheck.bind(_this);
  422.     return _this;
  423.   }
  424.  
  425.   _createClass(AbrController, [{
  426.     key: 'destroy',
  427.     value: function destroy() {
  428.       this.clearTimer();
  429.       _eventHandler2.default.prototype.destroy.call(this);
  430.     }
  431.   }, {
  432.     key: 'onFragLoading',
  433.     value: function onFragLoading(data) {
  434.       if (!this.timer) {
  435.         this.timer = setInterval(this.onCheck, 100);
  436.       }
  437.       this.fragCurrent = data.frag;
  438.     }
  439.   }, {
  440.     key: 'onFragLoadProgress',
  441.     value: function onFragLoadProgress(data) {
  442.       var stats = data.stats;
  443.       // only update stats if first frag loading
  444.       // if same frag is loaded multiple times, it might be in browser cache, and loaded quickly
  445.       // and leading to wrong bw estimation
  446.       if (stats.aborted === undefined && data.frag.loadCounter === 1) {
  447.         this.lastfetchduration = (performance.now() - stats.trequest) / 1000;
  448.         this.lastbw = stats.loaded * 8 / this.lastfetchduration;
  449.         //console.log(`fetchDuration:${this.lastfetchduration},bw:${(this.lastbw/1000).toFixed(0)}/${stats.aborted}`);
  450.       }
  451.     }
  452.   }, {
  453.     key: 'abandonRulesCheck',
  454.     value: function abandonRulesCheck() {
  455.       /*
  456.         monitor fragment retrieval time...
  457.         we compute expected time of arrival of the complete fragment.
  458.         we compare it to expected time of buffer starvation
  459.       */
  460.       var hls = this.hls,
  461.           v = hls.media,
  462.           frag = this.fragCurrent;
  463.  
  464.       // if loader has been destroyed or loading has been aborted, stop timer and return
  465.       if (!frag.loader || frag.loader.stats && frag.loader.stats.aborted) {
  466.         _logger.logger.warn('frag loader destroy or aborted, disarm abandonRulesCheck');
  467.         this.clearTimer();
  468.         return;
  469.       }
  470.       /* only monitor frag retrieval time if
  471.       (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) */
  472.       if (v && (!v.paused || !v.readyState) && frag.autoLevel && frag.level) {
  473.         var requestDelay = performance.now() - frag.trequest;
  474.         // monitor fragment load progress after half of expected fragment duration,to stabilize bitrate
  475.         if (requestDelay > 500 * frag.duration) {
  476.           var loadRate = Math.max(1, frag.loaded * 1000 / requestDelay); // byte/s; at least 1 byte/s to avoid division by zero
  477.           if (frag.expectedLen < frag.loaded) {
  478.             frag.expectedLen = frag.loaded;
  479.           }
  480.           var pos = v.currentTime;
  481.           var fragLoadedDelay = (frag.expectedLen - frag.loaded) / loadRate;
  482.           var bufferStarvationDelay = _bufferHelper2.default.bufferInfo(v, pos, hls.config.maxBufferHole).end - pos;
  483.           // consider emergency switch down only if we have less than 2 frag buffered AND
  484.           // time to finish loading current fragment is bigger than buffer starvation delay
  485.           // ie if we risk buffer starvation if bw does not increase quickly
  486.           if (bufferStarvationDelay < 2 * frag.duration && fragLoadedDelay > bufferStarvationDelay) {
  487.             var fragLevelNextLoadedDelay = void 0,
  488.                 nextLoadLevel = void 0;
  489.             // lets iterate through lower level and try to find the biggest one that could avoid rebuffering
  490.             // we start from current level - 1 and we step down , until we find a matching level
  491.             for (nextLoadLevel = frag.level - 1; nextLoadLevel >= 0; nextLoadLevel--) {
  492.               // compute time to load next fragment at lower level
  493.               // 0.8 : consider only 80% of current bw to be conservative
  494.               // 8 = bits per byte (bps/Bps)
  495.               fragLevelNextLoadedDelay = frag.duration * hls.levels[nextLoadLevel].bitrate / (8 * 0.8 * loadRate);
  496.               _logger.logger.log('fragLoadedDelay/bufferStarvationDelay/fragLevelNextLoadedDelay[' + nextLoadLevel + '] :' + fragLoadedDelay.toFixed(1) + '/' + bufferStarvationDelay.toFixed(1) + '/' + fragLevelNextLoadedDelay.toFixed(1));
  497.               if (fragLevelNextLoadedDelay < bufferStarvationDelay) {
  498.                 // we found a lower level that be rebuffering free with current estimated bw !
  499.                 break;
  500.               }
  501.             }
  502.             // only emergency switch down if it takes less time to load new fragment at lowest level instead
  503.             // of finishing loading current one ...
  504.             if (fragLevelNextLoadedDelay < fragLoadedDelay) {
  505.               // ensure nextLoadLevel is not negative
  506.               nextLoadLevel = Math.max(0, nextLoadLevel);
  507.               // force next load level in auto mode
  508.               hls.nextLoadLevel = nextLoadLevel;
  509.               // abort fragment loading ...
  510.               _logger.logger.warn('loading too slow, abort fragment loading and switch to level ' + nextLoadLevel);
  511.               //abort fragment loading
  512.               frag.loader.abort();
  513.               this.clearTimer();
  514.               hls.trigger(_events2.default.FRAG_LOAD_EMERGENCY_ABORTED, { frag: frag });
  515.             }
  516.           }
  517.         }
  518.       }
  519.     }
  520.   }, {
  521.     key: 'onFragLoaded',
  522.     value: function onFragLoaded(data) {
  523.       // stop monitoring bw once frag loaded
  524.       this.clearTimer();
  525.       // store level id after successful fragment load
  526.       this.lastLoadedFragLevel = data.frag.level;
  527.       // reset forced auto level value so that next level will be selected
  528.       this._nextAutoLevel = -1;
  529.     }
  530.   }, {
  531.     key: 'onError',
  532.     value: function onError(data) {
  533.       // stop timer in case of frag loading error
  534.       switch (data.details) {
  535.         case _errors.ErrorDetails.FRAG_LOAD_ERROR:
  536.         case _errors.ErrorDetails.FRAG_LOAD_TIMEOUT:
  537.           this.clearTimer();
  538.           break;
  539.         default:
  540.           break;
  541.       }
  542.     }
  543.   }, {
  544.     key: 'clearTimer',
  545.     value: function clearTimer() {
  546.       if (this.timer) {
  547.         clearInterval(this.timer);
  548.         this.timer = null;
  549.       }
  550.     }
  551.  
  552.     /** Return the capping/max level value that could be used by automatic level selection algorithm **/
  553.  
  554.   }, {
  555.     key: 'autoLevelCapping',
  556.     get: function get() {
  557.       return this._autoLevelCapping;
  558.     }
  559.  
  560.     /** set the capping/max level value that could be used by automatic level selection algorithm **/
  561.     ,
  562.     set: function set(newLevel) {
  563.       this._autoLevelCapping = newLevel;
  564.     }
  565.   }, {
  566.     key: 'nextAutoLevel',
  567.     get: function get() {
  568.       var lastbw = this.lastbw,
  569.           hls = this.hls,
  570.           adjustedbw,
  571.           i,
  572.           maxAutoLevel;
  573.       if (this._autoLevelCapping === -1 && hls.levels && hls.levels.length) {
  574.         maxAutoLevel = hls.levels.length - 1;
  575.       } else {
  576.         maxAutoLevel = this._autoLevelCapping;
  577.       }
  578.  
  579.       // in case next auto level has been forced, return it straight-away (but capped)
  580.       if (this._nextAutoLevel !== -1) {
  581.         return Math.min(this._nextAutoLevel, maxAutoLevel);
  582.       }
  583.  
  584.       // follow algorithm captured from stagefright :
  585.       // https://android.googlesource.com/platform/frameworks/av/+/master/media/libstagefright/httplive/LiveSession.cpp
  586.       // Pick the highest bandwidth stream below or equal to estimated bandwidth.
  587.       for (i = 0; i <= maxAutoLevel; i++) {
  588.         // consider only 80% of the available bandwidth, but if we are switching up,
  589.         // be even more conservative (70%) to avoid overestimating and immediately
  590.         // switching back.
  591.         if (i <= this.lastLoadedFragLevel) {
  592.           adjustedbw = 0.8 * lastbw;
  593.         } else {
  594.           adjustedbw = 0.7 * lastbw;
  595.         }
  596.         if (adjustedbw < hls.levels[i].bitrate) {
  597.           return Math.max(0, i - 1);
  598.         }
  599.       }
  600.       return i - 1;
  601.     },
  602.     set: function set(nextLevel) {
  603.       this._nextAutoLevel = nextLevel;
  604.     }
  605.   }]);
  606.  
  607.   return AbrController;
  608. }(_eventHandler2.default);
  609.  
  610. exports.default = AbrController;
  611.  
  612. },{"../errors":21,"../event-handler":22,"../events":23,"../helper/buffer-helper":25,"../utils/logger":39}],4:[function(require,module,exports){
  613. 'use strict';
  614.  
  615. Object.defineProperty(exports, "__esModule", {
  616.   value: true
  617. });
  618.  
  619. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  620.  
  621. var _events = require('../events');
  622.  
  623. var _events2 = _interopRequireDefault(_events);
  624.  
  625. var _eventHandler = require('../event-handler');
  626.  
  627. var _eventHandler2 = _interopRequireDefault(_eventHandler);
  628.  
  629. var _logger = require('../utils/logger');
  630.  
  631. var _errors = require('../errors');
  632.  
  633. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  634.  
  635. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  636.  
  637. function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
  638.  
  639. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /*
  640.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 * Buffer Controller
  641.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                */
  642.  
  643. var BufferController = function (_EventHandler) {
  644.   _inherits(BufferController, _EventHandler);
  645.  
  646.   function BufferController(hls) {
  647.     _classCallCheck(this, BufferController);
  648.  
  649.     // the value that we have set mediasource.duration to
  650.     // (the actual duration may be tweaked slighly by the browser)
  651.  
  652.     var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(BufferController).call(this, hls, _events2.default.MEDIA_ATTACHING, _events2.default.MEDIA_DETACHING, _events2.default.BUFFER_RESET, _events2.default.BUFFER_APPENDING, _events2.default.BUFFER_CODECS, _events2.default.BUFFER_EOS, _events2.default.BUFFER_FLUSHING, _events2.default.LEVEL_UPDATED));
  653.  
  654.     _this._msDuration = null;
  655.     // the value that we want to set mediaSource.duration to
  656.     _this._levelDuration = null;
  657.  
  658.     // Source Buffer listeners
  659.     _this.onsbue = _this.onSBUpdateEnd.bind(_this);
  660.     _this.onsbe = _this.onSBUpdateError.bind(_this);
  661.     return _this;
  662.   }
  663.  
  664.   _createClass(BufferController, [{
  665.     key: 'destroy',
  666.     value: function destroy() {
  667.       _eventHandler2.default.prototype.destroy.call(this);
  668.     }
  669.   }, {
  670.     key: 'onMediaAttaching',
  671.     value: function onMediaAttaching(data) {
  672.       var media = this.media = data.media;
  673.       if (media) {
  674.         // setup the media source
  675.         var ms = this.mediaSource = new MediaSource();
  676.         //Media Source listeners
  677.         this.onmso = this.onMediaSourceOpen.bind(this);
  678.         this.onmse = this.onMediaSourceEnded.bind(this);
  679.         this.onmsc = this.onMediaSourceClose.bind(this);
  680.         ms.addEventListener('sourceopen', this.onmso);
  681.         ms.addEventListener('sourceended', this.onmse);
  682.         ms.addEventListener('sourceclose', this.onmsc);
  683.         // link video and media Source
  684.         media.src = URL.createObjectURL(ms);
  685.       }
  686.     }
  687.   }, {
  688.     key: 'onMediaDetaching',
  689.     value: function onMediaDetaching() {
  690.       _logger.logger.log('media source detaching');
  691.       var ms = this.mediaSource;
  692.       if (ms) {
  693.         if (ms.readyState === 'open') {
  694.           try {
  695.             // endOfStream could trigger exception if any sourcebuffer is in updating state
  696.             // we don't really care about checking sourcebuffer state here,
  697.             // as we are anyway detaching the MediaSource
  698.             // let's just avoid this exception to propagate
  699.             ms.endOfStream();
  700.           } catch (err) {
  701.             _logger.logger.warn('onMediaDetaching:' + err.message + ' while calling endOfStream');
  702.           }
  703.         }
  704.         ms.removeEventListener('sourceopen', this.onmso);
  705.         ms.removeEventListener('sourceended', this.onmse);
  706.         ms.removeEventListener('sourceclose', this.onmsc);
  707.  
  708.         try {
  709.           // unlink MediaSource from video tag
  710.           this.media.src = '';
  711.           this.media.removeAttribute('src');
  712.         } catch (err) {
  713.           _logger.logger.warn('onMediaDetaching:' + err.message + ' while unlinking video.src');
  714.         }
  715.         this.mediaSource = null;
  716.         this.media = null;
  717.         this.pendingTracks = null;
  718.         this.sourceBuffer = {};
  719.       }
  720.       this.onmso = this.onmse = this.onmsc = null;
  721.       this.hls.trigger(_events2.default.MEDIA_DETACHED);
  722.     }
  723.   }, {
  724.     key: 'onMediaSourceOpen',
  725.     value: function onMediaSourceOpen() {
  726.       _logger.logger.log('media source opened');
  727.       this.hls.trigger(_events2.default.MEDIA_ATTACHED, { media: this.media });
  728.       // once received, don't listen anymore to sourceopen event
  729.       this.mediaSource.removeEventListener('sourceopen', this.onmso);
  730.       // if any buffer codecs pending, treat it here.
  731.       var pendingTracks = this.pendingTracks;
  732.       if (pendingTracks) {
  733.         this.onBufferCodecs(pendingTracks);
  734.         this.pendingTracks = null;
  735.         this.doAppending();
  736.       }
  737.     }
  738.   }, {
  739.     key: 'onMediaSourceClose',
  740.     value: function onMediaSourceClose() {
  741.       _logger.logger.log('media source closed');
  742.     }
  743.   }, {
  744.     key: 'onMediaSourceEnded',
  745.     value: function onMediaSourceEnded() {
  746.       _logger.logger.log('media source ended');
  747.     }
  748.   }, {
  749.     key: 'onSBUpdateEnd',
  750.     value: function onSBUpdateEnd() {
  751.  
  752.       if (this._needsFlush) {
  753.         this.doFlush();
  754.       }
  755.  
  756.       if (this._needsEos) {
  757.         this.onBufferEos();
  758.       }
  759.  
  760.       this.updateMediaElementDuration();
  761.  
  762.       this.hls.trigger(_events2.default.BUFFER_APPENDED);
  763.  
  764.       this.doAppending();
  765.     }
  766.   }, {
  767.     key: 'onSBUpdateError',
  768.     value: function onSBUpdateError(event) {
  769.       _logger.logger.error('sourceBuffer error:' + event);
  770.       // according to http://www.w3.org/TR/media-source/#sourcebuffer-append-error
  771.       // this error might not always be fatal (it is fatal if decode error is set, in that case
  772.       // it will be followed by a mediaElement error ...)
  773.       this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.BUFFER_APPENDING_ERROR, fatal: false });
  774.       // we don't need to do more than that, as accordin to the spec, updateend will be fired just after
  775.     }
  776.   }, {
  777.     key: 'onBufferReset',
  778.     value: function onBufferReset() {
  779.       var sourceBuffer = this.sourceBuffer;
  780.       for (var type in sourceBuffer) {
  781.         var sb = sourceBuffer[type];
  782.         try {
  783.           this.mediaSource.removeSourceBuffer(sb);
  784.           sb.removeEventListener('updateend', this.onsbue);
  785.           sb.removeEventListener('error', this.onsbe);
  786.         } catch (err) {}
  787.       }
  788.       this.sourceBuffer = {};
  789.       this.flushRange = [];
  790.       this.appended = 0;
  791.     }
  792.   }, {
  793.     key: 'onBufferCodecs',
  794.     value: function onBufferCodecs(tracks) {
  795.       var mediaSource = this.mediaSource;
  796.  
  797.       // delay sourcebuffer creation if media source not opened yet
  798.       if (!mediaSource || mediaSource.readyState !== 'open') {
  799.         this.pendingTracks = tracks;
  800.         return;
  801.       }
  802.  
  803.       var sourceBuffer = this.sourceBuffer;
  804.  
  805.       for (var trackName in tracks) {
  806.         if (!sourceBuffer[trackName]) {
  807.           var track = tracks[trackName];
  808.           // use levelCodec as first priority
  809.           var codec = track.levelCodec || track.codec;
  810.           var mimeType = track.container + ';codecs=' + codec;
  811.           _logger.logger.log('creating sourceBuffer with mimeType:' + mimeType);
  812.           try {
  813.             var sb = sourceBuffer[trackName] = mediaSource.addSourceBuffer(mimeType);
  814.             sb.addEventListener('updateend', this.onsbue);
  815.             sb.addEventListener('error', this.onsbe);
  816.           } catch (err) {
  817.             _logger.logger.error('error while trying to add sourceBuffer:' + err.message);
  818.             this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.BUFFER_ADD_CODEC_ERROR, fatal: false, err: err, mimeType: mimeType });
  819.           }
  820.         }
  821.       }
  822.     }
  823.   }, {
  824.     key: 'onBufferAppending',
  825.     value: function onBufferAppending(data) {
  826.       if (!this.segments) {
  827.         this.segments = [data];
  828.       } else {
  829.         this.segments.push(data);
  830.       }
  831.       this.doAppending();
  832.     }
  833.   }, {
  834.     key: 'onBufferAppendFail',
  835.     value: function onBufferAppendFail(data) {
  836.       _logger.logger.error('sourceBuffer error:' + data.event);
  837.       // according to http://www.w3.org/TR/media-source/#sourcebuffer-append-error
  838.       // this error might not always be fatal (it is fatal if decode error is set, in that case
  839.       // it will be followed by a mediaElement error ...)
  840.       this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.BUFFER_APPENDING_ERROR, fatal: false, frag: this.fragCurrent });
  841.     }
  842.   }, {
  843.     key: 'onBufferEos',
  844.     value: function onBufferEos() {
  845.       var sb = this.sourceBuffer,
  846.           mediaSource = this.mediaSource;
  847.       if (!mediaSource || mediaSource.readyState !== 'open') {
  848.         return;
  849.       }
  850.       if (!(sb.audio && sb.audio.updating || sb.video && sb.video.updating)) {
  851.         _logger.logger.log('all media data available, signal endOfStream() to MediaSource and stop loading fragment');
  852.         //Notify the media element that it now has all of the media data
  853.         mediaSource.endOfStream();
  854.         this._needsEos = false;
  855.       } else {
  856.         this._needsEos = true;
  857.       }
  858.     }
  859.   }, {
  860.     key: 'onBufferFlushing',
  861.     value: function onBufferFlushing(data) {
  862.       this.flushRange.push({ start: data.startOffset, end: data.endOffset });
  863.       // attempt flush immediatly
  864.       this.flushBufferCounter = 0;
  865.       this.doFlush();
  866.     }
  867.   }, {
  868.     key: 'onLevelUpdated',
  869.     value: function onLevelUpdated(event) {
  870.       var details = event.details;
  871.       if (details.fragments.length === 0) {
  872.         return;
  873.       }
  874.       this._levelDuration = details.totalduration + details.fragments[0].start;
  875.       this.updateMediaElementDuration();
  876.     }
  877.  
  878.     // https://github.com/dailymotion/hls.js/issues/355
  879.  
  880.   }, {
  881.     key: 'updateMediaElementDuration',
  882.     value: function updateMediaElementDuration() {
  883.       if (this._levelDuration === null) {
  884.         return;
  885.       }
  886.       var media = this.media;
  887.       var mediaSource = this.mediaSource;
  888.       if (!media || !mediaSource || media.readyState === 0 || mediaSource.readyState !== 'open') {
  889.         return;
  890.       }
  891.       for (var type in mediaSource.sourceBuffers) {
  892.         if (mediaSource.sourceBuffers[type].updating) {
  893.           // can't set duration whilst a buffer is updating
  894.           return;
  895.         }
  896.       }
  897.       if (this._msDuration === null) {
  898.         // initialise to the value that the media source is reporting
  899.         this._msDuration = mediaSource.duration;
  900.       }
  901.       // this._levelDuration was the last value we set.
  902.       // not using mediaSource.duration as the browser may tweak this value
  903.       if (this._levelDuration !== this._msDuration) {
  904.         _logger.logger.log('Updating mediasource duration to ' + this._levelDuration);
  905.         mediaSource.duration = this._levelDuration;
  906.         this._msDuration = this._levelDuration;
  907.       }
  908.     }
  909.   }, {
  910.     key: 'doFlush',
  911.     value: function doFlush() {
  912.       // loop through all buffer ranges to flush
  913.       while (this.flushRange.length) {
  914.         var range = this.flushRange[0];
  915.         // flushBuffer will abort any buffer append in progress and flush Audio/Video Buffer
  916.         if (this.flushBuffer(range.start, range.end)) {
  917.           // range flushed, remove from flush array
  918.           this.flushRange.shift();
  919.           this.flushBufferCounter = 0;
  920.         } else {
  921.           this._needsFlush = true;
  922.           // avoid looping, wait for SB update end to retrigger a flush
  923.           return;
  924.         }
  925.       }
  926.       if (this.flushRange.length === 0) {
  927.         // everything flushed
  928.         this._needsFlush = false;
  929.  
  930.         // let's recompute this.appended, which is used to avoid flush looping
  931.         var appended = 0;
  932.         var sourceBuffer = this.sourceBuffer;
  933.         for (var type in sourceBuffer) {
  934.           appended += sourceBuffer[type].buffered.length;
  935.         }
  936.         this.appended = appended;
  937.         this.hls.trigger(_events2.default.BUFFER_FLUSHED);
  938.       }
  939.     }
  940.   }, {
  941.     key: 'doAppending',
  942.     value: function doAppending() {
  943.       var hls = this.hls,
  944.           sourceBuffer = this.sourceBuffer,
  945.           segments = this.segments;
  946.       if (sourceBuffer) {
  947.         if (this.media.error) {
  948.           segments = [];
  949.           _logger.logger.error('trying to append although a media error occured, flush segment and abort');
  950.           return;
  951.         }
  952.         for (var type in sourceBuffer) {
  953.           if (sourceBuffer[type].updating) {
  954.             //logger.log('sb update in progress');
  955.             return;
  956.           }
  957.         }
  958.         if (segments.length) {
  959.           var segment = segments.shift();
  960.           try {
  961.             //logger.log(`appending ${segment.type} SB, size:${segment.data.length});
  962.             if (sourceBuffer[segment.type]) {
  963.               sourceBuffer[segment.type].appendBuffer(segment.data);
  964.               this.appendError = 0;
  965.               this.appended++;
  966.             } else {
  967.               // in case we don't have any source buffer matching with this segment type,
  968.               // it means that Mediasource fails to create sourcebuffer
  969.               // discard this segment, and trigger update end
  970.               this.onSBUpdateEnd();
  971.             }
  972.           } catch (err) {
  973.             // in case any error occured while appending, put back segment in segments table
  974.             _logger.logger.error('error while trying to append buffer:' + err.message);
  975.             segments.unshift(segment);
  976.             var event = { type: _errors.ErrorTypes.MEDIA_ERROR };
  977.             if (err.code !== 22) {
  978.               if (this.appendError) {
  979.                 this.appendError++;
  980.               } else {
  981.                 this.appendError = 1;
  982.               }
  983.               event.details = _errors.ErrorDetails.BUFFER_APPEND_ERROR;
  984.               event.frag = this.fragCurrent;
  985.               /* with UHD content, we could get loop of quota exceeded error until
  986.                 browser is able to evict some data from sourcebuffer. retrying help recovering this
  987.               */
  988.               if (this.appendError > hls.config.appendErrorMaxRetry) {
  989.                 _logger.logger.log('fail ' + hls.config.appendErrorMaxRetry + ' times to append segment in sourceBuffer');
  990.                 segments = [];
  991.                 event.fatal = true;
  992.                 hls.trigger(_events2.default.ERROR, event);
  993.                 return;
  994.               } else {
  995.                 event.fatal = false;
  996.                 hls.trigger(_events2.default.ERROR, event);
  997.               }
  998.             } else {
  999.               // QuotaExceededError: http://www.w3.org/TR/html5/infrastructure.html#quotaexceedederror
  1000.               // let's stop appending any segments, and report BUFFER_FULL_ERROR error
  1001.               segments = [];
  1002.               event.details = _errors.ErrorDetails.BUFFER_FULL_ERROR;
  1003.               hls.trigger(_events2.default.ERROR, event);
  1004.             }
  1005.           }
  1006.         }
  1007.       }
  1008.     }
  1009.  
  1010.     /*
  1011.       flush specified buffered range,
  1012.       return true once range has been flushed.
  1013.       as sourceBuffer.remove() is asynchronous, flushBuffer will be retriggered on sourceBuffer update end
  1014.     */
  1015.  
  1016.   }, {
  1017.     key: 'flushBuffer',
  1018.     value: function flushBuffer(startOffset, endOffset) {
  1019.       var sb, i, bufStart, bufEnd, flushStart, flushEnd;
  1020.       //logger.log('flushBuffer,pos/start/end: ' + this.media.currentTime + '/' + startOffset + '/' + endOffset);
  1021.       // safeguard to avoid infinite looping : don't try to flush more than the nb of appended segments
  1022.       if (this.flushBufferCounter < this.appended && this.sourceBuffer) {
  1023.         for (var type in this.sourceBuffer) {
  1024.           sb = this.sourceBuffer[type];
  1025.           if (!sb.updating) {
  1026.             for (i = 0; i < sb.buffered.length; i++) {
  1027.               bufStart = sb.buffered.start(i);
  1028.               bufEnd = sb.buffered.end(i);
  1029.               // workaround firefox not able to properly flush multiple buffered range.
  1030.               if (navigator.userAgent.toLowerCase().indexOf('firefox') !== -1 && endOffset === Number.POSITIVE_INFINITY) {
  1031.                 flushStart = startOffset;
  1032.                 flushEnd = endOffset;
  1033.               } else {
  1034.                 flushStart = Math.max(bufStart, startOffset);
  1035.                 flushEnd = Math.min(bufEnd, endOffset);
  1036.               }
  1037.               /* sometimes sourcebuffer.remove() does not flush
  1038.                  the exact expected time range.
  1039.                  to avoid rounding issues/infinite loop,
  1040.                  only flush buffer range of length greater than 500ms.
  1041.               */
  1042.               if (Math.min(flushEnd, bufEnd) - flushStart > 0.5) {
  1043.                 this.flushBufferCounter++;
  1044.                 _logger.logger.log('flush ' + type + ' [' + flushStart + ',' + flushEnd + '], of [' + bufStart + ',' + bufEnd + '], pos:' + this.media.currentTime);
  1045.                 sb.remove(flushStart, flushEnd);
  1046.                 return false;
  1047.               }
  1048.             }
  1049.           } else {
  1050.             //logger.log('abort ' + type + ' append in progress');
  1051.             // this will abort any appending in progress
  1052.             //sb.abort();
  1053.             _logger.logger.warn('cannot flush, sb updating in progress');
  1054.             return false;
  1055.           }
  1056.         }
  1057.       } else {
  1058.         _logger.logger.warn('abort flushing too many retries');
  1059.       }
  1060.       _logger.logger.log('buffer flushed');
  1061.       // everything flushed !
  1062.       return true;
  1063.     }
  1064.   }]);
  1065.  
  1066.   return BufferController;
  1067. }(_eventHandler2.default);
  1068.  
  1069. exports.default = BufferController;
  1070.  
  1071. },{"../errors":21,"../event-handler":22,"../events":23,"../utils/logger":39}],5:[function(require,module,exports){
  1072. 'use strict';
  1073.  
  1074. Object.defineProperty(exports, "__esModule", {
  1075.   value: true
  1076. });
  1077.  
  1078. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  1079.  
  1080. var _events = require('../events');
  1081.  
  1082. var _events2 = _interopRequireDefault(_events);
  1083.  
  1084. var _eventHandler = require('../event-handler');
  1085.  
  1086. var _eventHandler2 = _interopRequireDefault(_eventHandler);
  1087.  
  1088. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  1089.  
  1090. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  1091.  
  1092. function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
  1093.  
  1094. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /*
  1095.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 * cap stream level to media size dimension controller
  1096.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                */
  1097.  
  1098. var CapLevelController = function (_EventHandler) {
  1099.   _inherits(CapLevelController, _EventHandler);
  1100.  
  1101.   function CapLevelController(hls) {
  1102.     _classCallCheck(this, CapLevelController);
  1103.  
  1104.     return _possibleConstructorReturn(this, Object.getPrototypeOf(CapLevelController).call(this, hls, _events2.default.FPS_DROP_LEVEL_CAPPING, _events2.default.MEDIA_ATTACHING, _events2.default.MANIFEST_PARSED));
  1105.   }
  1106.  
  1107.   _createClass(CapLevelController, [{
  1108.     key: 'destroy',
  1109.     value: function destroy() {
  1110.       if (this.hls.config.capLevelToPlayerSize) {
  1111.         this.media = this.restrictedLevels = null;
  1112.         this.autoLevelCapping = Number.POSITIVE_INFINITY;
  1113.         if (this.timer) {
  1114.           this.timer = clearInterval(this.timer);
  1115.         }
  1116.       }
  1117.     }
  1118.   }, {
  1119.     key: 'onFpsDropLevelCapping',
  1120.     value: function onFpsDropLevelCapping(data) {
  1121.       if (!this.restrictedLevels) {
  1122.         this.restrictedLevels = [];
  1123.       }
  1124.       if (!this.isLevelRestricted(data.droppedLevel)) {
  1125.         this.restrictedLevels.push(data.droppedLevel);
  1126.       }
  1127.     }
  1128.   }, {
  1129.     key: 'onMediaAttaching',
  1130.     value: function onMediaAttaching(data) {
  1131.       this.media = data.media instanceof HTMLVideoElement ? data.media : null;
  1132.     }
  1133.   }, {
  1134.     key: 'onManifestParsed',
  1135.     value: function onManifestParsed(data) {
  1136.       if (this.hls.config.capLevelToPlayerSize) {
  1137.         this.autoLevelCapping = Number.POSITIVE_INFINITY;
  1138.         this.levels = data.levels;
  1139.         this.hls.firstLevel = this.getMaxLevel(data.firstLevel);
  1140.         clearInterval(this.timer);
  1141.         this.timer = setInterval(this.detectPlayerSize.bind(this), 1000);
  1142.         this.detectPlayerSize();
  1143.       }
  1144.     }
  1145.   }, {
  1146.     key: 'detectPlayerSize',
  1147.     value: function detectPlayerSize() {
  1148.       if (this.media) {
  1149.         var levelsLength = this.levels ? this.levels.length : 0;
  1150.         if (levelsLength) {
  1151.           this.hls.autoLevelCapping = this.getMaxLevel(levelsLength - 1);
  1152.           if (this.hls.autoLevelCapping > this.autoLevelCapping) {
  1153.             // if auto level capping has a higher value for the previous one, flush the buffer using nextLevelSwitch
  1154.             // usually happen when the user go to the fullscreen mode.
  1155.             this.hls.streamController.nextLevelSwitch();
  1156.           }
  1157.           this.autoLevelCapping = this.hls.autoLevelCapping;
  1158.         }
  1159.       }
  1160.     }
  1161.  
  1162.     /*
  1163.     * returns level should be the one with the dimensions equal or greater than the media (player) dimensions (so the video will be downscaled)
  1164.     */
  1165.  
  1166.   }, {
  1167.     key: 'getMaxLevel',
  1168.     value: function getMaxLevel(capLevelIndex) {
  1169.       var result = 0,
  1170.           i = void 0,
  1171.           level = void 0,
  1172.           mWidth = this.mediaWidth,
  1173.           mHeight = this.mediaHeight,
  1174.           lWidth = 0,
  1175.           lHeight = 0;
  1176.  
  1177.       for (i = 0; i <= capLevelIndex; i++) {
  1178.         level = this.levels[i];
  1179.         if (this.isLevelRestricted(i)) {
  1180.           break;
  1181.         }
  1182.         result = i;
  1183.         lWidth = level.width;
  1184.         lHeight = level.height;
  1185.         if (mWidth <= lWidth || mHeight <= lHeight) {
  1186.           break;
  1187.         }
  1188.       }
  1189.       return result;
  1190.     }
  1191.   }, {
  1192.     key: 'isLevelRestricted',
  1193.     value: function isLevelRestricted(level) {
  1194.       return this.restrictedLevels && this.restrictedLevels.indexOf(level) !== -1 ? true : false;
  1195.     }
  1196.   }, {
  1197.     key: 'contentScaleFactor',
  1198.     get: function get() {
  1199.       var pixelRatio = 1;
  1200.       try {
  1201.         pixelRatio = window.devicePixelRatio;
  1202.       } catch (e) {}
  1203.       return pixelRatio;
  1204.     }
  1205.   }, {
  1206.     key: 'mediaWidth',
  1207.     get: function get() {
  1208.       var width = void 0;
  1209.       if (this.media) {
  1210.         width = this.media.width || this.media.clientWidth || this.media.offsetWidth;
  1211.         width *= this.contentScaleFactor;
  1212.       }
  1213.       return width;
  1214.     }
  1215.   }, {
  1216.     key: 'mediaHeight',
  1217.     get: function get() {
  1218.       var height = void 0;
  1219.       if (this.media) {
  1220.         height = this.media.height || this.media.clientHeight || this.media.offsetHeight;
  1221.         height *= this.contentScaleFactor;
  1222.       }
  1223.       return height;
  1224.     }
  1225.   }]);
  1226.  
  1227.   return CapLevelController;
  1228. }(_eventHandler2.default);
  1229.  
  1230. exports.default = CapLevelController;
  1231.  
  1232. },{"../event-handler":22,"../events":23}],6:[function(require,module,exports){
  1233. 'use strict';
  1234.  
  1235. Object.defineProperty(exports, "__esModule", {
  1236.   value: true
  1237. });
  1238.  
  1239. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  1240.  
  1241. var _events = require('../events');
  1242.  
  1243. var _events2 = _interopRequireDefault(_events);
  1244.  
  1245. var _eventHandler = require('../event-handler');
  1246.  
  1247. var _eventHandler2 = _interopRequireDefault(_eventHandler);
  1248.  
  1249. var _logger = require('../utils/logger');
  1250.  
  1251. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  1252.  
  1253. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  1254.  
  1255. function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
  1256.  
  1257. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /*
  1258.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 * FPS Controller
  1259.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                */
  1260.  
  1261. var FPSController = function (_EventHandler) {
  1262.   _inherits(FPSController, _EventHandler);
  1263.  
  1264.   function FPSController(hls) {
  1265.     _classCallCheck(this, FPSController);
  1266.  
  1267.     return _possibleConstructorReturn(this, Object.getPrototypeOf(FPSController).call(this, hls, _events2.default.MEDIA_ATTACHING));
  1268.   }
  1269.  
  1270.   _createClass(FPSController, [{
  1271.     key: 'destroy',
  1272.     value: function destroy() {
  1273.       if (this.timer) {
  1274.         clearInterval(this.timer);
  1275.       }
  1276.       this.isVideoPlaybackQualityAvailable = false;
  1277.     }
  1278.   }, {
  1279.     key: 'onMediaAttaching',
  1280.     value: function onMediaAttaching(data) {
  1281.       if (this.hls.config.capLevelOnFPSDrop) {
  1282.         this.video = data.media instanceof HTMLVideoElement ? data.media : null;
  1283.         if (typeof this.video.getVideoPlaybackQuality === 'function') {
  1284.           this.isVideoPlaybackQualityAvailable = true;
  1285.         }
  1286.         clearInterval(this.timer);
  1287.         this.timer = setInterval(this.checkFPSInterval.bind(this), this.hls.config.fpsDroppedMonitoringPeriod);
  1288.       }
  1289.     }
  1290.   }, {
  1291.     key: 'checkFPS',
  1292.     value: function checkFPS(video, decodedFrames, droppedFrames) {
  1293.       var currentTime = performance.now();
  1294.       if (decodedFrames) {
  1295.         if (this.lastTime) {
  1296.           var currentPeriod = currentTime - this.lastTime,
  1297.               currentDropped = droppedFrames - this.lastDroppedFrames,
  1298.               currentDecoded = decodedFrames - this.lastDecodedFrames,
  1299.               droppedFPS = 1000 * currentDropped / currentPeriod;
  1300.           this.hls.trigger(_events2.default.FPS_DROP, { currentDropped: currentDropped, currentDecoded: currentDecoded, totalDroppedFrames: droppedFrames });
  1301.           if (droppedFPS > 0) {
  1302.             //logger.log('checkFPS : droppedFPS/decodedFPS:' + droppedFPS/(1000 * currentDecoded / currentPeriod));
  1303.             if (currentDropped > this.hls.config.fpsDroppedMonitoringThreshold * currentDecoded) {
  1304.               var currentLevel = this.hls.currentLevel;
  1305.               _logger.logger.warn('drop FPS ratio greater than max allowed value for currentLevel: ' + currentLevel);
  1306.               if (currentLevel > 0 && (this.hls.autoLevelCapping === -1 || this.hls.autoLevelCapping >= currentLevel)) {
  1307.                 currentLevel = currentLevel - 1;
  1308.                 this.hls.trigger(_events2.default.FPS_DROP_LEVEL_CAPPING, { level: currentLevel, droppedLevel: this.hls.currentLevel });
  1309.                 this.hls.autoLevelCapping = currentLevel;
  1310.                 this.hls.streamController.nextLevelSwitch();
  1311.               }
  1312.             }
  1313.           }
  1314.         }
  1315.         this.lastTime = currentTime;
  1316.         this.lastDroppedFrames = droppedFrames;
  1317.         this.lastDecodedFrames = decodedFrames;
  1318.       }
  1319.     }
  1320.   }, {
  1321.     key: 'checkFPSInterval',
  1322.     value: function checkFPSInterval() {
  1323.       if (this.video) {
  1324.         if (this.isVideoPlaybackQualityAvailable) {
  1325.           var videoPlaybackQuality = this.video.getVideoPlaybackQuality();
  1326.           this.checkFPS(this.video, videoPlaybackQuality.totalVideoFrames, videoPlaybackQuality.droppedVideoFrames);
  1327.         } else {
  1328.           this.checkFPS(this.video, this.video.webkitDecodedFrameCount, this.video.webkitDroppedFrameCount);
  1329.         }
  1330.       }
  1331.     }
  1332.   }]);
  1333.  
  1334.   return FPSController;
  1335. }(_eventHandler2.default);
  1336.  
  1337. exports.default = FPSController;
  1338.  
  1339. },{"../event-handler":22,"../events":23,"../utils/logger":39}],7:[function(require,module,exports){
  1340. 'use strict';
  1341.  
  1342. Object.defineProperty(exports, "__esModule", {
  1343.   value: true
  1344. });
  1345.  
  1346. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  1347.  
  1348. var _events = require('../events');
  1349.  
  1350. var _events2 = _interopRequireDefault(_events);
  1351.  
  1352. var _eventHandler = require('../event-handler');
  1353.  
  1354. var _eventHandler2 = _interopRequireDefault(_eventHandler);
  1355.  
  1356. var _logger = require('../utils/logger');
  1357.  
  1358. var _errors = require('../errors');
  1359.  
  1360. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  1361.  
  1362. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  1363.  
  1364. function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
  1365.  
  1366. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /*
  1367.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 * Level Controller
  1368.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                */
  1369.  
  1370. var LevelController = function (_EventHandler) {
  1371.   _inherits(LevelController, _EventHandler);
  1372.  
  1373.   function LevelController(hls) {
  1374.     _classCallCheck(this, LevelController);
  1375.  
  1376.     var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(LevelController).call(this, hls, _events2.default.MANIFEST_LOADED, _events2.default.LEVEL_LOADED, _events2.default.ERROR));
  1377.  
  1378.     _this.ontick = _this.tick.bind(_this);
  1379.     _this._manualLevel = _this._autoLevelCapping = -1;
  1380.     return _this;
  1381.   }
  1382.  
  1383.   _createClass(LevelController, [{
  1384.     key: 'destroy',
  1385.     value: function destroy() {
  1386.       if (this.timer) {
  1387.         clearTimeout(this.timer);
  1388.         this.timer = null;
  1389.       }
  1390.       this._manualLevel = -1;
  1391.     }
  1392.   }, {
  1393.     key: 'startLoad',
  1394.     value: function startLoad() {
  1395.       this.canload = true;
  1396.       // speed up live playlist refresh if timer exists
  1397.       if (this.timer) {
  1398.         this.tick();
  1399.       }
  1400.     }
  1401.   }, {
  1402.     key: 'stopLoad',
  1403.     value: function stopLoad() {
  1404.       this.canload = false;
  1405.     }
  1406.   }, {
  1407.     key: 'onManifestLoaded',
  1408.     value: function onManifestLoaded(data) {
  1409.       var levels0 = [],
  1410.           levels = [],
  1411.           bitrateStart,
  1412.           i,
  1413.           bitrateSet = {},
  1414.           videoCodecFound = false,
  1415.           audioCodecFound = false,
  1416.           hls = this.hls;
  1417.  
  1418.       // regroup redundant level together
  1419.       data.levels.forEach(function (level) {
  1420.         if (level.videoCodec) {
  1421.           videoCodecFound = true;
  1422.         }
  1423.         if (level.audioCodec) {
  1424.           audioCodecFound = true;
  1425.         }
  1426.         var redundantLevelId = bitrateSet[level.bitrate];
  1427.         if (redundantLevelId === undefined) {
  1428.           bitrateSet[level.bitrate] = levels0.length;
  1429.           level.url = [level.url];
  1430.           level.urlId = 0;
  1431.           levels0.push(level);
  1432.         } else {
  1433.           levels0[redundantLevelId].url.push(level.url);
  1434.         }
  1435.       });
  1436.  
  1437.       // remove audio-only level if we also have levels with audio+video codecs signalled
  1438.       if (videoCodecFound && audioCodecFound) {
  1439.         levels0.forEach(function (level) {
  1440.           if (level.videoCodec) {
  1441.             levels.push(level);
  1442.           }
  1443.         });
  1444.       } else {
  1445.         levels = levels0;
  1446.       }
  1447.  
  1448.       // only keep level with supported audio/video codecs
  1449.       levels = levels.filter(function (level) {
  1450.         var checkSupportedAudio = function checkSupportedAudio(codec) {
  1451.           return MediaSource.isTypeSupported('audio/mp4;codecs=' + codec);
  1452.         };
  1453.         var checkSupportedVideo = function checkSupportedVideo(codec) {
  1454.           return MediaSource.isTypeSupported('video/mp4;codecs=' + codec);
  1455.         };
  1456.         var audioCodec = level.audioCodec,
  1457.             videoCodec = level.videoCodec;
  1458.  
  1459.         return (!audioCodec || checkSupportedAudio(audioCodec)) && (!videoCodec || checkSupportedVideo(videoCodec));
  1460.       });
  1461.  
  1462.       if (levels.length) {
  1463.         // start bitrate is the first bitrate of the manifest
  1464.         bitrateStart = levels[0].bitrate;
  1465.         // sort level on bitrate
  1466.         levels.sort(function (a, b) {
  1467.           return a.bitrate - b.bitrate;
  1468.         });
  1469.         this._levels = levels;
  1470.         // find index of first level in sorted levels
  1471.         for (i = 0; i < levels.length; i++) {
  1472.           if (levels[i].bitrate === bitrateStart) {
  1473.             this._firstLevel = i;
  1474.             _logger.logger.log('manifest loaded,' + levels.length + ' level(s) found, first bitrate:' + bitrateStart);
  1475.             break;
  1476.           }
  1477.         }
  1478.         hls.trigger(_events2.default.MANIFEST_PARSED, { levels: this._levels, firstLevel: this._firstLevel, stats: data.stats });
  1479.       } else {
  1480.         hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.MANIFEST_INCOMPATIBLE_CODECS_ERROR, fatal: true, url: hls.url, reason: 'no level with compatible codecs found in manifest' });
  1481.       }
  1482.       return;
  1483.     }
  1484.   }, {
  1485.     key: 'setLevelInternal',
  1486.     value: function setLevelInternal(newLevel) {
  1487.       var levels = this._levels;
  1488.       // check if level idx is valid
  1489.       if (newLevel >= 0 && newLevel < levels.length) {
  1490.         // stopping live reloading timer if any
  1491.         if (this.timer) {
  1492.           clearTimeout(this.timer);
  1493.           this.timer = null;
  1494.         }
  1495.         this._level = newLevel;
  1496.         _logger.logger.log('switching to level ' + newLevel);
  1497.         this.hls.trigger(_events2.default.LEVEL_SWITCH, { level: newLevel });
  1498.         var level = levels[newLevel];
  1499.         // check if we need to load playlist for this level
  1500.         if (level.details === undefined || level.details.live === true) {
  1501.           // level not retrieved yet, or live playlist we need to (re)load it
  1502.           _logger.logger.log('(re)loading playlist for level ' + newLevel);
  1503.           var urlId = level.urlId;
  1504.           this.hls.trigger(_events2.default.LEVEL_LOADING, { url: level.url[urlId], level: newLevel, id: urlId });
  1505.         }
  1506.       } else {
  1507.         // invalid level id given, trigger error
  1508.         this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.OTHER_ERROR, details: _errors.ErrorDetails.LEVEL_SWITCH_ERROR, level: newLevel, fatal: false, reason: 'invalid level idx' });
  1509.       }
  1510.     }
  1511.   }, {
  1512.     key: 'onError',
  1513.     value: function onError(data) {
  1514.       if (data.fatal) {
  1515.         return;
  1516.       }
  1517.  
  1518.       var details = data.details,
  1519.           hls = this.hls,
  1520.           levelId = void 0,
  1521.           level = void 0,
  1522.           levelError = false;
  1523.       // try to recover not fatal errors
  1524.       switch (details) {
  1525.         case _errors.ErrorDetails.FRAG_LOAD_ERROR:
  1526.         case _errors.ErrorDetails.FRAG_LOAD_TIMEOUT:
  1527.         case _errors.ErrorDetails.FRAG_LOOP_LOADING_ERROR:
  1528.         case _errors.ErrorDetails.KEY_LOAD_ERROR:
  1529.         case _errors.ErrorDetails.KEY_LOAD_TIMEOUT:
  1530.           levelId = data.frag.level;
  1531.           break;
  1532.         case _errors.ErrorDetails.LEVEL_LOAD_ERROR:
  1533.         case _errors.ErrorDetails.LEVEL_LOAD_TIMEOUT:
  1534.           levelId = data.level;
  1535.           levelError = true;
  1536.           break;
  1537.         default:
  1538.           break;
  1539.       }
  1540.       /* try to switch to a redundant stream if any available.
  1541.        * if no redundant stream available, emergency switch down (if in auto mode and current level not 0)
  1542.        * otherwise, we cannot recover this network error ...
  1543.        * don't raise FRAG_LOAD_ERROR and FRAG_LOAD_TIMEOUT as fatal, as it is handled by mediaController
  1544.        */
  1545.       if (levelId !== undefined) {
  1546.         level = this._levels[levelId];
  1547.         if (level.urlId < level.url.length - 1) {
  1548.           level.urlId++;
  1549.           level.details = undefined;
  1550.           _logger.logger.warn('level controller,' + details + ' for level ' + levelId + ': switching to redundant stream id ' + level.urlId);
  1551.         } else {
  1552.           // we could try to recover if in auto mode and current level not lowest level (0)
  1553.           var recoverable = this._manualLevel === -1 && levelId;
  1554.           if (recoverable) {
  1555.             _logger.logger.warn('level controller,' + details + ': emergency switch-down for next fragment');
  1556.             hls.abrController.nextAutoLevel = 0;
  1557.           } else if (level && level.details && level.details.live) {
  1558.             _logger.logger.warn('level controller,' + details + ' on live stream, discard');
  1559.             if (levelError) {
  1560.               // reset this._level so that another call to set level() will retrigger a frag load
  1561.               this._level = undefined;
  1562.             }
  1563.             // FRAG_LOAD_ERROR and FRAG_LOAD_TIMEOUT are handled by mediaController
  1564.           } else if (details !== _errors.ErrorDetails.FRAG_LOAD_ERROR && details !== _errors.ErrorDetails.FRAG_LOAD_TIMEOUT) {
  1565.               _logger.logger.error('cannot recover ' + details + ' error');
  1566.               this._level = undefined;
  1567.               // stopping live reloading timer if any
  1568.               if (this.timer) {
  1569.                 clearTimeout(this.timer);
  1570.                 this.timer = null;
  1571.               }
  1572.               // redispatch same error but with fatal set to true
  1573.               data.fatal = true;
  1574.               hls.trigger(_events2.default.ERROR, data);
  1575.             }
  1576.         }
  1577.       }
  1578.     }
  1579.   }, {
  1580.     key: 'onLevelLoaded',
  1581.     value: function onLevelLoaded(data) {
  1582.       // only process level loaded events matching with expected level
  1583.       if (data.level === this._level) {
  1584.         var newDetails = data.details;
  1585.         // if current playlist is a live playlist, arm a timer to reload it
  1586.         if (newDetails.live) {
  1587.           var reloadInterval = 1000 * (newDetails.averagetargetduration ? newDetails.averagetargetduration : newDetails.targetduration),
  1588.               curLevel = this._levels[data.level],
  1589.               curDetails = curLevel.details;
  1590.           if (curDetails && newDetails.endSN === curDetails.endSN) {
  1591.             // follow HLS Spec, If the client reloads a Playlist file and finds that it has not
  1592.             // changed then it MUST wait for a period of one-half the target
  1593.             // duration before retrying.
  1594.             reloadInterval /= 2;
  1595.             _logger.logger.log('same live playlist, reload twice faster');
  1596.           }
  1597.           // decrement reloadInterval with level loading delay
  1598.           reloadInterval -= performance.now() - data.stats.trequest;
  1599.           // in any case, don't reload more than every second
  1600.           reloadInterval = Math.max(1000, Math.round(reloadInterval));
  1601.           _logger.logger.log('live playlist, reload in ' + reloadInterval + ' ms');
  1602.           this.timer = setTimeout(this.ontick, reloadInterval);
  1603.         } else {
  1604.           this.timer = null;
  1605.         }
  1606.       }
  1607.     }
  1608.   }, {
  1609.     key: 'tick',
  1610.     value: function tick() {
  1611.       var levelId = this._level;
  1612.       if (levelId !== undefined && this.canload) {
  1613.         var level = this._levels[levelId],
  1614.             urlId = level.urlId;
  1615.         this.hls.trigger(_events2.default.LEVEL_LOADING, { url: level.url[urlId], level: levelId, id: urlId });
  1616.       }
  1617.     }
  1618.   }, {
  1619.     key: 'levels',
  1620.     get: function get() {
  1621.       return this._levels;
  1622.     }
  1623.   }, {
  1624.     key: 'level',
  1625.     get: function get() {
  1626.       return this._level;
  1627.     },
  1628.     set: function set(newLevel) {
  1629.       var levels = this._levels;
  1630.       if (levels && levels.length > newLevel) {
  1631.         if (this._level !== newLevel || levels[newLevel].details === undefined) {
  1632.           this.setLevelInternal(newLevel);
  1633.         }
  1634.       }
  1635.     }
  1636.   }, {
  1637.     key: 'manualLevel',
  1638.     get: function get() {
  1639.       return this._manualLevel;
  1640.     },
  1641.     set: function set(newLevel) {
  1642.       this._manualLevel = newLevel;
  1643.       if (this._startLevel === undefined) {
  1644.         this._startLevel = newLevel;
  1645.       }
  1646.       if (newLevel !== -1) {
  1647.         this.level = newLevel;
  1648.       }
  1649.     }
  1650.   }, {
  1651.     key: 'firstLevel',
  1652.     get: function get() {
  1653.       return this._firstLevel;
  1654.     },
  1655.     set: function set(newLevel) {
  1656.       this._firstLevel = newLevel;
  1657.     }
  1658.   }, {
  1659.     key: 'startLevel',
  1660.     get: function get() {
  1661.       if (this._startLevel === undefined) {
  1662.         return this._firstLevel;
  1663.       } else {
  1664.         return this._startLevel;
  1665.       }
  1666.     },
  1667.     set: function set(newLevel) {
  1668.       this._startLevel = newLevel;
  1669.     }
  1670.   }, {
  1671.     key: 'nextLoadLevel',
  1672.     get: function get() {
  1673.       if (this._manualLevel !== -1) {
  1674.         return this._manualLevel;
  1675.       } else {
  1676.         return this.hls.abrController.nextAutoLevel;
  1677.       }
  1678.     },
  1679.     set: function set(nextLevel) {
  1680.       this.level = nextLevel;
  1681.       if (this._manualLevel === -1) {
  1682.         this.hls.abrController.nextAutoLevel = nextLevel;
  1683.       }
  1684.     }
  1685.   }]);
  1686.  
  1687.   return LevelController;
  1688. }(_eventHandler2.default);
  1689.  
  1690. exports.default = LevelController;
  1691.  
  1692. },{"../errors":21,"../event-handler":22,"../events":23,"../utils/logger":39}],8:[function(require,module,exports){
  1693. 'use strict';
  1694.  
  1695. Object.defineProperty(exports, "__esModule", {
  1696.   value: true
  1697. });
  1698.  
  1699. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  1700.  
  1701. var _demuxer = require('../demux/demuxer');
  1702.  
  1703. var _demuxer2 = _interopRequireDefault(_demuxer);
  1704.  
  1705. var _events = require('../events');
  1706.  
  1707. var _events2 = _interopRequireDefault(_events);
  1708.  
  1709. var _eventHandler = require('../event-handler');
  1710.  
  1711. var _eventHandler2 = _interopRequireDefault(_eventHandler);
  1712.  
  1713. var _logger = require('../utils/logger');
  1714.  
  1715. var _binarySearch = require('../utils/binary-search');
  1716.  
  1717. var _binarySearch2 = _interopRequireDefault(_binarySearch);
  1718.  
  1719. var _bufferHelper = require('../helper/buffer-helper');
  1720.  
  1721. var _bufferHelper2 = _interopRequireDefault(_bufferHelper);
  1722.  
  1723. var _levelHelper = require('../helper/level-helper');
  1724.  
  1725. var _levelHelper2 = _interopRequireDefault(_levelHelper);
  1726.  
  1727. var _errors = require('../errors');
  1728.  
  1729. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  1730.  
  1731. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  1732.  
  1733. function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
  1734.  
  1735. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /*
  1736.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 * Stream Controller
  1737.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                */
  1738.  
  1739. var State = {
  1740.   STOPPED: 'STOPPED',
  1741.   STARTING: 'STARTING',
  1742.   IDLE: 'IDLE',
  1743.   PAUSED: 'PAUSED',
  1744.   KEY_LOADING: 'KEY_LOADING',
  1745.   FRAG_LOADING: 'FRAG_LOADING',
  1746.   FRAG_LOADING_WAITING_RETRY: 'FRAG_LOADING_WAITING_RETRY',
  1747.   WAITING_LEVEL: 'WAITING_LEVEL',
  1748.   PARSING: 'PARSING',
  1749.   PARSED: 'PARSED',
  1750.   ENDED: 'ENDED',
  1751.   ERROR: 'ERROR'
  1752. };
  1753.  
  1754. var StreamController = function (_EventHandler) {
  1755.   _inherits(StreamController, _EventHandler);
  1756.  
  1757.   function StreamController(hls) {
  1758.     _classCallCheck(this, StreamController);
  1759.  
  1760.     var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(StreamController).call(this, hls, _events2.default.MEDIA_ATTACHED, _events2.default.MEDIA_DETACHING, _events2.default.MANIFEST_LOADING, _events2.default.MANIFEST_PARSED, _events2.default.LEVEL_LOADED, _events2.default.KEY_LOADED, _events2.default.FRAG_LOADED, _events2.default.FRAG_LOAD_EMERGENCY_ABORTED, _events2.default.FRAG_PARSING_INIT_SEGMENT, _events2.default.FRAG_PARSING_DATA, _events2.default.FRAG_PARSED, _events2.default.ERROR, _events2.default.BUFFER_APPENDED, _events2.default.BUFFER_FLUSHED));
  1761.  
  1762.     _this.config = hls.config;
  1763.     _this.audioCodecSwap = false;
  1764.     _this.ticks = 0;
  1765.     _this.ontick = _this.tick.bind(_this);
  1766.     return _this;
  1767.   }
  1768.  
  1769.   _createClass(StreamController, [{
  1770.     key: 'destroy',
  1771.     value: function destroy() {
  1772.       this.stopLoad();
  1773.       if (this.timer) {
  1774.         clearInterval(this.timer);
  1775.         this.timer = null;
  1776.       }
  1777.       _eventHandler2.default.prototype.destroy.call(this);
  1778.       this.state = State.STOPPED;
  1779.     }
  1780.   }, {
  1781.     key: 'startLoad',
  1782.     value: function startLoad() {
  1783.       var startPosition = arguments.length <= 0 || arguments[0] === undefined ? 0 : arguments[0];
  1784.  
  1785.       if (this.levels) {
  1786.         var media = this.media,
  1787.             lastCurrentTime = this.lastCurrentTime;
  1788.         this.stopLoad();
  1789.         this.demuxer = new _demuxer2.default(this.hls);
  1790.         if (!this.timer) {
  1791.           this.timer = setInterval(this.ontick, 100);
  1792.         }
  1793.         this.level = -1;
  1794.         this.fragLoadError = 0;
  1795.         if (media && lastCurrentTime) {
  1796.           _logger.logger.log('configure startPosition @' + lastCurrentTime);
  1797.           if (!this.lastPaused) {
  1798.             _logger.logger.log('resuming video');
  1799.             media.play();
  1800.           }
  1801.           this.state = State.IDLE;
  1802.         } else {
  1803.           this.lastCurrentTime = this.startPosition ? this.startPosition : startPosition;
  1804.           this.state = State.STARTING;
  1805.         }
  1806.         this.nextLoadPosition = this.startPosition = this.lastCurrentTime;
  1807.         this.tick();
  1808.       } else {
  1809.         _logger.logger.warn('cannot start loading as manifest not parsed yet');
  1810.         this.state = State.STOPPED;
  1811.       }
  1812.     }
  1813.   }, {
  1814.     key: 'stopLoad',
  1815.     value: function stopLoad() {
  1816.       var frag = this.fragCurrent;
  1817.       if (frag) {
  1818.         if (frag.loader) {
  1819.           frag.loader.abort();
  1820.         }
  1821.         this.fragCurrent = null;
  1822.       }
  1823.       this.fragPrevious = null;
  1824.       if (this.demuxer) {
  1825.         this.demuxer.destroy();
  1826.         this.demuxer = null;
  1827.       }
  1828.       this.state = State.STOPPED;
  1829.     }
  1830.   }, {
  1831.     key: 'tick',
  1832.     value: function tick() {
  1833.       this.ticks++;
  1834.       if (this.ticks === 1) {
  1835.         this.doTick();
  1836.         if (this.ticks > 1) {
  1837.           setTimeout(this.tick, 1);
  1838.         }
  1839.         this.ticks = 0;
  1840.       }
  1841.     }
  1842.   }, {
  1843.     key: 'doTick',
  1844.     value: function doTick() {
  1845.       switch (this.state) {
  1846.         case State.STARTING:
  1847.           var hls = this.hls;
  1848.           // determine load level
  1849.           var startLevel = hls.startLevel;
  1850.           if (startLevel === -1) {
  1851.             // -1 : guess start Level by doing a bitrate test by loading first fragment of lowest quality level
  1852.             startLevel = 0;
  1853.             this.fragBitrateTest = true;
  1854.           }
  1855.           // set new level to playlist loader : this will trigger start level load
  1856.           // hls.nextLoadLevel remains until it is set to a new value or until a new frag is successfully loaded
  1857.           this.level = hls.nextLoadLevel = startLevel;
  1858.           this.state = State.WAITING_LEVEL;
  1859.           this.loadedmetadata = false;
  1860.           break;
  1861.         case State.IDLE:
  1862.           // when this returns false there was an error and we shall return immediatly
  1863.           // from current tick
  1864.           if (!this._doTickIdle()) {
  1865.             return;
  1866.           }
  1867.           break;
  1868.         case State.WAITING_LEVEL:
  1869.           var level = this.levels[this.level];
  1870.           // check if playlist is already loaded
  1871.           if (level && level.details) {
  1872.             this.state = State.IDLE;
  1873.           }
  1874.           break;
  1875.         case State.FRAG_LOADING_WAITING_RETRY:
  1876.           var now = performance.now();
  1877.           var retryDate = this.retryDate;
  1878.           var media = this.media;
  1879.           var isSeeking = media && media.seeking;
  1880.           // if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading
  1881.           if (!retryDate || now >= retryDate || isSeeking) {
  1882.             _logger.logger.log('mediaController: retryDate reached, switch back to IDLE state');
  1883.             this.state = State.IDLE;
  1884.           }
  1885.           break;
  1886.         case State.ERROR:
  1887.         case State.PAUSED:
  1888.         case State.STOPPED:
  1889.         case State.FRAG_LOADING:
  1890.         case State.PARSING:
  1891.         case State.PARSED:
  1892.         case State.ENDED:
  1893.           break;
  1894.         default:
  1895.           break;
  1896.       }
  1897.       // check buffer
  1898.       this._checkBuffer();
  1899.       // check/update current fragment
  1900.       this._checkFragmentChanged();
  1901.     }
  1902.  
  1903.     // Ironically the "idle" state is the on we do the most logic in it seems ....
  1904.     // NOTE: Maybe we could rather schedule a check for buffer length after half of the currently
  1905.     //       played segment, or on pause/play/seek instead of naively checking every 100ms?
  1906.  
  1907.   }, {
  1908.     key: '_doTickIdle',
  1909.     value: function _doTickIdle() {
  1910.       var hls = this.hls,
  1911.           config = hls.config;
  1912.  
  1913.       // if video not attached AND
  1914.       // start fragment already requested OR start frag prefetch disable
  1915.       // exit loop
  1916.       // => if media not attached but start frag prefetch is enabled and start frag not requested yet, we will not exit loop
  1917.       if (!this.media && (this.startFragRequested || !config.startFragPrefetch)) {
  1918.         return true;
  1919.       }
  1920.  
  1921.       // if we have not yet loaded any fragment, start loading from start position
  1922.       var pos = void 0;
  1923.       if (this.loadedmetadata) {
  1924.         pos = this.media.currentTime;
  1925.       } else {
  1926.         pos = this.nextLoadPosition;
  1927.       }
  1928.       // determine next load level
  1929.       var level = hls.nextLoadLevel;
  1930.  
  1931.       // 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
  1932.       var maxBufLen = void 0;
  1933.       if (this.levels[level].hasOwnProperty('bitrate')) {
  1934.         maxBufLen = Math.max(8 * config.maxBufferSize / this.levels[level].bitrate, config.maxBufferLength);
  1935.         maxBufLen = Math.min(maxBufLen, config.maxMaxBufferLength);
  1936.       } else {
  1937.         maxBufLen = config.maxBufferLength;
  1938.       }
  1939.  
  1940.       // determine next candidate fragment to be loaded, based on current position and end of buffer position
  1941.       // ensure up to `config.maxMaxBufferLength` of buffer upfront
  1942.  
  1943.       var bufferInfo = _bufferHelper2.default.bufferInfo(this.media, pos, config.maxBufferHole),
  1944.           bufferLen = bufferInfo.len;
  1945.       // Stay idle if we are still with buffer margins
  1946.       if (bufferLen >= maxBufLen) {
  1947.         return true;
  1948.       }
  1949.  
  1950.       // if buffer length is less than maxBufLen try to load a new fragment ...
  1951.       _logger.logger.trace('buffer length of ' + bufferLen.toFixed(3) + ' is below max of ' + maxBufLen.toFixed(3) + '. checking for more payload ...');
  1952.  
  1953.       // set next load level : this will trigger a playlist load if needed
  1954.       hls.nextLoadLevel = level;
  1955.       this.level = level;
  1956.  
  1957.       var levelDetails = this.levels[level].details;
  1958.       // if level info not retrieved yet, switch state and wait for level retrieval
  1959.       // if live playlist, ensure that new playlist has been refreshed to avoid loading/try to load
  1960.       // a useless and outdated fragment (that might even introduce load error if it is already out of the live playlist)
  1961.       if (typeof levelDetails === 'undefined' || levelDetails.live && this.levelLastLoaded !== level) {
  1962.         this.state = State.WAITING_LEVEL;
  1963.         return true;
  1964.       }
  1965.  
  1966.       // if we have the levelDetails for the selected variant, lets continue enrichen our stream (load keys/fragments or trigger EOS, etc..)
  1967.       return this._fetchPayloadOrEos({ pos: pos, bufferInfo: bufferInfo, levelDetails: levelDetails });
  1968.     }
  1969.   }, {
  1970.     key: '_fetchPayloadOrEos',
  1971.     value: function _fetchPayloadOrEos(_ref) {
  1972.       var pos = _ref.pos;
  1973.       var bufferInfo = _ref.bufferInfo;
  1974.       var levelDetails = _ref.levelDetails;
  1975.  
  1976.       var fragPrevious = this.fragPrevious,
  1977.           level = this.level;
  1978.  
  1979.       // find fragment index, contiguous with end of buffer position
  1980.       var fragments = levelDetails.fragments,
  1981.           fragLen = fragments.length,
  1982.           start = fragments[0].start,
  1983.           end = fragments[fragLen - 1].start + fragments[fragLen - 1].duration,
  1984.           bufferEnd = bufferInfo.end,
  1985.           frag = void 0;
  1986.  
  1987.       // in case of live playlist we need to ensure that requested position is not located before playlist start
  1988.       if (levelDetails.live) {
  1989.         frag = this._ensureFragmentAtLivePoint({ levelDetails: levelDetails, bufferEnd: bufferEnd, start: start, end: end, fragPrevious: fragPrevious, fragments: fragments, fragLen: fragLen });
  1990.         // if it explicitely returns null don't load any fragment and exit function now
  1991.         if (frag === null) {
  1992.           return false;
  1993.         }
  1994.       } else {
  1995.         // VoD playlist: if bufferEnd before start of playlist, load first fragment
  1996.         if (bufferEnd < start) {
  1997.           frag = fragments[0];
  1998.         }
  1999.       }
  2000.       if (!frag) {
  2001.         frag = this._findFragment({ start: start, fragPrevious: fragPrevious, fragLen: fragLen, fragments: fragments, bufferEnd: bufferEnd, end: end, levelDetails: levelDetails });
  2002.       }
  2003.       if (frag) {
  2004.         return this._loadFragmentOrKey({ frag: frag, level: level, levelDetails: levelDetails, pos: pos, bufferEnd: bufferEnd });
  2005.       }
  2006.       return true;
  2007.     }
  2008.   }, {
  2009.     key: '_ensureFragmentAtLivePoint',
  2010.     value: function _ensureFragmentAtLivePoint(_ref2) {
  2011.       var levelDetails = _ref2.levelDetails;
  2012.       var bufferEnd = _ref2.bufferEnd;
  2013.       var start = _ref2.start;
  2014.       var end = _ref2.end;
  2015.       var fragPrevious = _ref2.fragPrevious;
  2016.       var fragments = _ref2.fragments;
  2017.       var fragLen = _ref2.fragLen;
  2018.  
  2019.       var config = this.hls.config;
  2020.  
  2021.       var frag = void 0;
  2022.  
  2023.       // check if requested position is within seekable boundaries :
  2024.       //logger.log(`start/pos/bufEnd/seeking:${start.toFixed(3)}/${pos.toFixed(3)}/${bufferEnd.toFixed(3)}/${this.media.seeking}`);
  2025.       var maxLatency = config.liveMaxLatencyDuration !== undefined ? config.liveMaxLatencyDuration : config.liveMaxLatencyDurationCount * levelDetails.targetduration;
  2026.  
  2027.       if (bufferEnd < Math.max(start, end - maxLatency)) {
  2028.         var targetLatency = config.liveSyncDuration !== undefined ? config.liveSyncDuration : config.liveSyncDurationCount * levelDetails.targetduration;
  2029.         this.seekAfterBuffered = start + Math.max(0, levelDetails.totalduration - targetLatency);
  2030.         _logger.logger.log('buffer end: ' + bufferEnd + ' is located too far from the end of live sliding playlist, media position will be reseted to: ' + this.seekAfterBuffered.toFixed(3));
  2031.         bufferEnd = this.seekAfterBuffered;
  2032.       }
  2033.  
  2034.       // if end of buffer greater than live edge, don't load any fragment
  2035.       // this could happen if live playlist intermittently slides in the past.
  2036.       // level 1 loaded [182580161,182580167]
  2037.       // level 1 loaded [182580162,182580169]
  2038.       // Loading 182580168 of [182580162 ,182580169],level 1 ..
  2039.       // Loading 182580169 of [182580162 ,182580169],level 1 ..
  2040.       // level 1 loaded [182580162,182580168] <============= here we should have bufferEnd > end. in that case break to avoid reloading 182580168
  2041.       // level 1 loaded [182580164,182580171]
  2042.       //
  2043.       if (levelDetails.PTSKnown && bufferEnd > end) {
  2044.         return null;
  2045.       }
  2046.  
  2047.       if (this.startFragRequested && !levelDetails.PTSKnown) {
  2048.         /* we are switching level on live playlist, but we don't have any PTS info for that quality level ...
  2049.            try to load frag matching with next SN.
  2050.            even if SN are not synchronized between playlists, loading this frag will help us
  2051.            compute playlist sliding and find the right one after in case it was not the right consecutive one */
  2052.         if (fragPrevious) {
  2053.           var targetSN = fragPrevious.sn + 1;
  2054.           if (targetSN >= levelDetails.startSN && targetSN <= levelDetails.endSN) {
  2055.             frag = fragments[targetSN - levelDetails.startSN];
  2056.             _logger.logger.log('live playlist, switching playlist, load frag with next SN: ' + frag.sn);
  2057.           }
  2058.         }
  2059.         if (!frag) {
  2060.           /* we have no idea about which fragment should be loaded.
  2061.              so let's load mid fragment. it will help computing playlist sliding and find the right one
  2062.           */
  2063.           frag = fragments[Math.min(fragLen - 1, Math.round(fragLen / 2))];
  2064.           _logger.logger.log('live playlist, switching playlist, unknown, load middle frag : ' + frag.sn);
  2065.         }
  2066.       }
  2067.       return frag;
  2068.     }
  2069.   }, {
  2070.     key: '_findFragment',
  2071.     value: function _findFragment(_ref3) {
  2072.       var start = _ref3.start;
  2073.       var fragPrevious = _ref3.fragPrevious;
  2074.       var fragLen = _ref3.fragLen;
  2075.       var fragments = _ref3.fragments;
  2076.       var bufferEnd = _ref3.bufferEnd;
  2077.       var end = _ref3.end;
  2078.       var levelDetails = _ref3.levelDetails;
  2079.  
  2080.       var config = this.hls.config;
  2081.  
  2082.       var frag = void 0,
  2083.           foundFrag = void 0,
  2084.           maxFragLookUpTolerance = config.maxFragLookUpTolerance;
  2085.  
  2086.       if (bufferEnd < end) {
  2087.         if (bufferEnd > end - maxFragLookUpTolerance) {
  2088.           maxFragLookUpTolerance = 0;
  2089.         }
  2090.         foundFrag = _binarySearch2.default.search(fragments, function (candidate) {
  2091.           // offset should be within fragment boundary - config.maxFragLookUpTolerance
  2092.           // this is to cope with situations like
  2093.           // bufferEnd = 9.991
  2094.           // frag[Ø] : [0,10]
  2095.           // frag[1] : [10,20]
  2096.           // bufferEnd is within frag[0] range ... although what we are expecting is to return frag[1] here
  2097.           //              frag start               frag start+duration
  2098.           //                  |-----------------------------|
  2099.           //              <--->                         <--->
  2100.           //  ...--------><-----------------------------><---------....
  2101.           // previous frag         matching fragment         next frag
  2102.           //  return -1             return 0                 return 1
  2103.           //logger.log(`level/sn/start/end/bufEnd:${level}/${candidate.sn}/${candidate.start}/${(candidate.start+candidate.duration)}/${bufferEnd}`);
  2104.           if (candidate.start + candidate.duration - maxFragLookUpTolerance <= bufferEnd) {
  2105.             return 1;
  2106.           } else if (candidate.start - maxFragLookUpTolerance > bufferEnd) {
  2107.             return -1;
  2108.           }
  2109.           return 0;
  2110.         });
  2111.       } else {
  2112.         // reach end of playlist
  2113.         foundFrag = fragments[fragLen - 1];
  2114.       }
  2115.       if (foundFrag) {
  2116.         frag = foundFrag;
  2117.         start = foundFrag.start;
  2118.         //logger.log('find SN matching with pos:' +  bufferEnd + ':' + frag.sn);
  2119.         if (fragPrevious && frag.level === fragPrevious.level && frag.sn === fragPrevious.sn) {
  2120.           if (frag.sn < levelDetails.endSN) {
  2121.             frag = fragments[frag.sn + 1 - levelDetails.startSN];
  2122.             _logger.logger.log('SN just loaded, load next one: ' + frag.sn);
  2123.           } else {
  2124.             // have we reached end of VOD playlist ?
  2125.             if (!levelDetails.live) {
  2126.               // Finalize the media stream
  2127.               this.hls.trigger(_events2.default.BUFFER_EOS);
  2128.               // We might be loading the last fragment but actually the media
  2129.               // is currently processing a seek command and waiting for new data to resume at another point.
  2130.               // Going to ended state while media is seeking can spawn an infinite buffering broken state.
  2131.               if (!this.media.seeking) {
  2132.                 this.state = State.ENDED;
  2133.               }
  2134.             }
  2135.             frag = null;
  2136.           }
  2137.         }
  2138.       }
  2139.       return frag;
  2140.     }
  2141.   }, {
  2142.     key: '_loadFragmentOrKey',
  2143.     value: function _loadFragmentOrKey(_ref4) {
  2144.       var frag = _ref4.frag;
  2145.       var level = _ref4.level;
  2146.       var levelDetails = _ref4.levelDetails;
  2147.       var pos = _ref4.pos;
  2148.       var bufferEnd = _ref4.bufferEnd;
  2149.  
  2150.       var hls = this.hls,
  2151.           config = hls.config;
  2152.  
  2153.       //logger.log('loading frag ' + i +',pos/bufEnd:' + pos.toFixed(3) + '/' + bufferEnd.toFixed(3));
  2154.       if (frag.decryptdata.uri != null && frag.decryptdata.key == null) {
  2155.         _logger.logger.log('Loading key for ' + frag.sn + ' of [' + levelDetails.startSN + ' ,' + levelDetails.endSN + '],level ' + level);
  2156.         this.state = State.KEY_LOADING;
  2157.         hls.trigger(_events2.default.KEY_LOADING, { frag: frag });
  2158.       } else {
  2159.         _logger.logger.log('Loading ' + frag.sn + ' of [' + levelDetails.startSN + ' ,' + levelDetails.endSN + '],level ' + level + ', currentTime:' + pos + ',bufferEnd:' + bufferEnd.toFixed(3));
  2160.         frag.autoLevel = hls.autoLevelEnabled;
  2161.         if (this.levels.length > 1) {
  2162.           frag.expectedLen = Math.round(frag.duration * this.levels[level].bitrate / 8);
  2163.           frag.trequest = performance.now();
  2164.         }
  2165.         // ensure that we are not reloading the same fragments in loop ...
  2166.         if (this.fragLoadIdx !== undefined) {
  2167.           this.fragLoadIdx++;
  2168.         } else {
  2169.           this.fragLoadIdx = 0;
  2170.         }
  2171.         if (frag.loadCounter) {
  2172.           frag.loadCounter++;
  2173.           var maxThreshold = config.fragLoadingLoopThreshold;
  2174.           // if this frag has already been loaded 3 times, and if it has been reloaded recently
  2175.           if (frag.loadCounter > maxThreshold && Math.abs(this.fragLoadIdx - frag.loadIdx) < maxThreshold) {
  2176.             hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.FRAG_LOOP_LOADING_ERROR, fatal: false, frag: frag });
  2177.             return false;
  2178.           }
  2179.         } else {
  2180.           frag.loadCounter = 1;
  2181.         }
  2182.         frag.loadIdx = this.fragLoadIdx;
  2183.         this.fragCurrent = frag;
  2184.         this.startFragRequested = true;
  2185.         hls.trigger(_events2.default.FRAG_LOADING, { frag: frag });
  2186.         this.state = State.FRAG_LOADING;
  2187.         return true;
  2188.       }
  2189.     }
  2190.   }, {
  2191.     key: 'getBufferRange',
  2192.     value: function getBufferRange(position) {
  2193.       var i,
  2194.           range,
  2195.           bufferRange = this.bufferRange;
  2196.       if (bufferRange) {
  2197.         for (i = bufferRange.length - 1; i >= 0; i--) {
  2198.           range = bufferRange[i];
  2199.           if (position >= range.start && position <= range.end) {
  2200.             return range;
  2201.           }
  2202.         }
  2203.       }
  2204.       return null;
  2205.     }
  2206.   }, {
  2207.     key: 'followingBufferRange',
  2208.     value: function followingBufferRange(range) {
  2209.       if (range) {
  2210.         // try to get range of next fragment (500ms after this range)
  2211.         return this.getBufferRange(range.end + 0.5);
  2212.       }
  2213.       return null;
  2214.     }
  2215.   }, {
  2216.     key: 'isBuffered',
  2217.     value: function isBuffered(position) {
  2218.       var media = this.media;
  2219.       if (media) {
  2220.         var buffered = media.buffered;
  2221.         for (var i = 0; i < buffered.length; i++) {
  2222.           if (position >= buffered.start(i) && position <= buffered.end(i)) {
  2223.             return true;
  2224.           }
  2225.         }
  2226.       }
  2227.       return false;
  2228.     }
  2229.   }, {
  2230.     key: '_checkFragmentChanged',
  2231.     value: function _checkFragmentChanged() {
  2232.       var rangeCurrent,
  2233.           currentTime,
  2234.           video = this.media;
  2235.       if (video && video.seeking === false) {
  2236.         currentTime = video.currentTime;
  2237.         /* if video element is in seeked state, currentTime can only increase.
  2238.           (assuming that playback rate is positive ...)
  2239.           As sometimes currentTime jumps back to zero after a
  2240.           media decode error, check this, to avoid seeking back to
  2241.           wrong position after a media decode error
  2242.         */
  2243.         if (currentTime > video.playbackRate * this.lastCurrentTime) {
  2244.           this.lastCurrentTime = currentTime;
  2245.         }
  2246.         if (this.isBuffered(currentTime)) {
  2247.           rangeCurrent = this.getBufferRange(currentTime);
  2248.         } else if (this.isBuffered(currentTime + 0.1)) {
  2249.           /* ensure that FRAG_CHANGED event is triggered at startup,
  2250.             when first video frame is displayed and playback is paused.
  2251.             add a tolerance of 100ms, in case current position is not buffered,
  2252.             check if current pos+100ms is buffered and use that buffer range
  2253.             for FRAG_CHANGED event reporting */
  2254.           rangeCurrent = this.getBufferRange(currentTime + 0.1);
  2255.         }
  2256.         if (rangeCurrent) {
  2257.           var fragPlaying = rangeCurrent.frag;
  2258.           if (fragPlaying !== this.fragPlaying) {
  2259.             this.fragPlaying = fragPlaying;
  2260.             this.hls.trigger(_events2.default.FRAG_CHANGED, { frag: fragPlaying });
  2261.           }
  2262.         }
  2263.       }
  2264.     }
  2265.  
  2266.     /*
  2267.       on immediate level switch :
  2268.        - pause playback if playing
  2269.        - cancel any pending load request
  2270.        - and trigger a buffer flush
  2271.     */
  2272.  
  2273.   }, {
  2274.     key: 'immediateLevelSwitch',
  2275.     value: function immediateLevelSwitch() {
  2276.       _logger.logger.log('immediateLevelSwitch');
  2277.       if (!this.immediateSwitch) {
  2278.         this.immediateSwitch = true;
  2279.         this.previouslyPaused = this.media.paused;
  2280.         this.media.pause();
  2281.       }
  2282.       var fragCurrent = this.fragCurrent;
  2283.       if (fragCurrent && fragCurrent.loader) {
  2284.         fragCurrent.loader.abort();
  2285.       }
  2286.       this.fragCurrent = null;
  2287.       // increase fragment load Index to avoid frag loop loading error after buffer flush
  2288.       this.fragLoadIdx += 2 * this.config.fragLoadingLoopThreshold;
  2289.       this.state = State.PAUSED;
  2290.       // flush everything
  2291.       this.hls.trigger(_events2.default.BUFFER_FLUSHING, { startOffset: 0, endOffset: Number.POSITIVE_INFINITY });
  2292.     }
  2293.  
  2294.     /*
  2295.        on immediate level switch end, after new fragment has been buffered :
  2296.         - nudge video decoder by slightly adjusting video currentTime
  2297.         - resume the playback if needed
  2298.     */
  2299.  
  2300.   }, {
  2301.     key: 'immediateLevelSwitchEnd',
  2302.     value: function immediateLevelSwitchEnd() {
  2303.       this.immediateSwitch = false;
  2304.       var media = this.media;
  2305.       if (media && media.readyState) {
  2306.         media.currentTime -= 0.0001;
  2307.         if (!this.previouslyPaused) {
  2308.           media.play();
  2309.         }
  2310.       }
  2311.     }
  2312.   }, {
  2313.     key: 'nextLevelSwitch',
  2314.     value: function nextLevelSwitch() {
  2315.       /* try to switch ASAP without breaking video playback :
  2316.          in order to ensure smooth but quick level switching,
  2317.         we need to find the next flushable buffer range
  2318.         we should take into account new segment fetch time
  2319.       */
  2320.       var media = this.media;
  2321.       // ensure that media is defined and that metadata are available (to retrieve currentTime)
  2322.       if (media && media.readyState) {
  2323.         var fetchdelay = void 0,
  2324.             currentRange = void 0,
  2325.             nextRange = void 0;
  2326.         // increase fragment load Index to avoid frag loop loading error after buffer flush
  2327.         this.fragLoadIdx += 2 * this.config.fragLoadingLoopThreshold;
  2328.         currentRange = this.getBufferRange(media.currentTime);
  2329.         if (currentRange && currentRange.start > 1) {
  2330.           // flush buffer preceding current fragment (flush until current fragment start offset)
  2331.           // minus 1s to avoid video freezing, that could happen if we flush keyframe of current video ...
  2332.           this.state = State.PAUSED;
  2333.           this.hls.trigger(_events2.default.BUFFER_FLUSHING, { startOffset: 0, endOffset: currentRange.start - 1 });
  2334.         }
  2335.         if (!media.paused) {
  2336.           // add a safety delay of 1s
  2337.           var nextLevelId = this.hls.nextLoadLevel,
  2338.               nextLevel = this.levels[nextLevelId],
  2339.               fragLastKbps = this.fragLastKbps;
  2340.           if (fragLastKbps && this.fragCurrent) {
  2341.             fetchdelay = this.fragCurrent.duration * nextLevel.bitrate / (1000 * fragLastKbps) + 1;
  2342.           } else {
  2343.             fetchdelay = 0;
  2344.           }
  2345.         } else {
  2346.           fetchdelay = 0;
  2347.         }
  2348.         //logger.log('fetchdelay:'+fetchdelay);
  2349.         // find buffer range that will be reached once new fragment will be fetched
  2350.         nextRange = this.getBufferRange(media.currentTime + fetchdelay);
  2351.         if (nextRange) {
  2352.           // we can flush buffer range following this one without stalling playback
  2353.           nextRange = this.followingBufferRange(nextRange);
  2354.           if (nextRange) {
  2355.             // if we are here, we can also cancel any loading/demuxing in progress, as they are useless
  2356.             var fragCurrent = this.fragCurrent;
  2357.             if (fragCurrent && fragCurrent.loader) {
  2358.               fragCurrent.loader.abort();
  2359.             }
  2360.             this.fragCurrent = null;
  2361.             // flush position is the start position of this new buffer
  2362.             this.state = State.PAUSED;
  2363.             this.hls.trigger(_events2.default.BUFFER_FLUSHING, { startOffset: nextRange.start, endOffset: Number.POSITIVE_INFINITY });
  2364.           }
  2365.         }
  2366.       }
  2367.     }
  2368.   }, {
  2369.     key: 'onMediaAttached',
  2370.     value: function onMediaAttached(data) {
  2371.       var media = this.media = data.media;
  2372.       this.onvseeking = this.onMediaSeeking.bind(this);
  2373.       this.onvseeked = this.onMediaSeeked.bind(this);
  2374.       this.onvended = this.onMediaEnded.bind(this);
  2375.       media.addEventListener('seeking', this.onvseeking);
  2376.       media.addEventListener('seeked', this.onvseeked);
  2377.       media.addEventListener('ended', this.onvended);
  2378.       if (this.levels && this.config.autoStartLoad) {
  2379.         this.hls.startLoad();
  2380.       }
  2381.     }
  2382.   }, {
  2383.     key: 'onMediaDetaching',
  2384.     value: function onMediaDetaching() {
  2385.       var media = this.media;
  2386.       if (media && media.ended) {
  2387.         _logger.logger.log('MSE detaching and video ended, reset startPosition');
  2388.         this.startPosition = this.lastCurrentTime = 0;
  2389.       }
  2390.  
  2391.       // reset fragment loading counter on MSE detaching to avoid reporting FRAG_LOOP_LOADING_ERROR after error recovery
  2392.       var levels = this.levels;
  2393.       if (levels) {
  2394.         // reset fragment load counter
  2395.         levels.forEach(function (level) {
  2396.           if (level.details) {
  2397.             level.details.fragments.forEach(function (fragment) {
  2398.               fragment.loadCounter = undefined;
  2399.             });
  2400.           }
  2401.         });
  2402.       }
  2403.       // remove video listeners
  2404.       if (media) {
  2405.         media.removeEventListener('seeking', this.onvseeking);
  2406.         media.removeEventListener('seeked', this.onvseeked);
  2407.         media.removeEventListener('ended', this.onvended);
  2408.         this.onvseeking = this.onvseeked = this.onvended = null;
  2409.       }
  2410.       this.media = null;
  2411.       this.loadedmetadata = false;
  2412.       this.stopLoad();
  2413.     }
  2414.   }, {
  2415.     key: 'onMediaSeeking',
  2416.     value: function onMediaSeeking() {
  2417.       _logger.logger.log('media seeking to ' + this.media.currentTime);
  2418.       if (this.state === State.FRAG_LOADING) {
  2419.         // check if currently loaded fragment is inside buffer.
  2420.         //if outside, cancel fragment loading, otherwise do nothing
  2421.         if (_bufferHelper2.default.bufferInfo(this.media, this.media.currentTime, this.config.maxBufferHole).len === 0) {
  2422.           _logger.logger.log('seeking outside of buffer while fragment load in progress, cancel fragment load');
  2423.           var fragCurrent = this.fragCurrent;
  2424.           if (fragCurrent) {
  2425.             if (fragCurrent.loader) {
  2426.               fragCurrent.loader.abort();
  2427.             }
  2428.             this.fragCurrent = null;
  2429.           }
  2430.           this.fragPrevious = null;
  2431.           // switch to IDLE state to load new fragment
  2432.           this.state = State.IDLE;
  2433.         }
  2434.       } else if (this.state === State.ENDED) {
  2435.         // switch to IDLE state to check for potential new fragment
  2436.         this.state = State.IDLE;
  2437.       }
  2438.       if (this.media) {
  2439.         this.lastCurrentTime = this.media.currentTime;
  2440.       }
  2441.       // avoid reporting fragment loop loading error in case user is seeking several times on same position
  2442.       if (this.fragLoadIdx !== undefined) {
  2443.         this.fragLoadIdx += 2 * this.config.fragLoadingLoopThreshold;
  2444.       }
  2445.       // tick to speed up processing
  2446.       this.tick();
  2447.     }
  2448.   }, {
  2449.     key: 'onMediaSeeked',
  2450.     value: function onMediaSeeked() {
  2451.       _logger.logger.log('media seeked to ' + this.media.currentTime);
  2452.       // tick to speed up FRAGMENT_PLAYING triggering
  2453.       this.tick();
  2454.     }
  2455.   }, {
  2456.     key: 'onMediaEnded',
  2457.     value: function onMediaEnded() {
  2458.       _logger.logger.log('media ended');
  2459.       // reset startPosition and lastCurrentTime to restart playback @ stream beginning
  2460.       this.startPosition = this.lastCurrentTime = 0;
  2461.     }
  2462.   }, {
  2463.     key: 'onManifestLoading',
  2464.     value: function onManifestLoading() {
  2465.       // reset buffer on manifest loading
  2466.       _logger.logger.log('trigger BUFFER_RESET');
  2467.       this.hls.trigger(_events2.default.BUFFER_RESET);
  2468.       this.bufferRange = [];
  2469.       this.stalled = false;
  2470.     }
  2471.   }, {
  2472.     key: 'onManifestParsed',
  2473.     value: function onManifestParsed(data) {
  2474.       var aac = false,
  2475.           heaac = false,
  2476.           codec;
  2477.       data.levels.forEach(function (level) {
  2478.         // detect if we have different kind of audio codecs used amongst playlists
  2479.         codec = level.audioCodec;
  2480.         if (codec) {
  2481.           if (codec.indexOf('mp4a.40.2') !== -1) {
  2482.             aac = true;
  2483.           }
  2484.           if (codec.indexOf('mp4a.40.5') !== -1) {
  2485.             heaac = true;
  2486.           }
  2487.         }
  2488.       });
  2489.       this.audioCodecSwitch = aac && heaac;
  2490.       if (this.audioCodecSwitch) {
  2491.         _logger.logger.log('both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC');
  2492.       }
  2493.       this.levels = data.levels;
  2494.       this.startLevelLoaded = false;
  2495.       this.startFragRequested = false;
  2496.       if (this.config.autoStartLoad) {
  2497.         this.hls.startLoad();
  2498.       }
  2499.     }
  2500.   }, {
  2501.     key: 'onLevelLoaded',
  2502.     value: function onLevelLoaded(data) {
  2503.       var newDetails = data.details,
  2504.           newLevelId = data.level,
  2505.           curLevel = this.levels[newLevelId],
  2506.           duration = newDetails.totalduration,
  2507.           sliding = 0;
  2508.  
  2509.       _logger.logger.log('level ' + newLevelId + ' loaded [' + newDetails.startSN + ',' + newDetails.endSN + '],duration:' + duration);
  2510.       this.levelLastLoaded = newLevelId;
  2511.  
  2512.       if (newDetails.live) {
  2513.         var curDetails = curLevel.details;
  2514.         if (curDetails) {
  2515.           // we already have details for that level, merge them
  2516.           _levelHelper2.default.mergeDetails(curDetails, newDetails);
  2517.           sliding = newDetails.fragments[0].start;
  2518.           if (newDetails.PTSKnown) {
  2519.             _logger.logger.log('live playlist sliding:' + sliding.toFixed(3));
  2520.           } else {
  2521.             _logger.logger.log('live playlist - outdated PTS, unknown sliding');
  2522.           }
  2523.         } else {
  2524.           newDetails.PTSKnown = false;
  2525.           _logger.logger.log('live playlist - first load, unknown sliding');
  2526.         }
  2527.       } else {
  2528.         newDetails.PTSKnown = false;
  2529.       }
  2530.       // override level info
  2531.       curLevel.details = newDetails;
  2532.       this.hls.trigger(_events2.default.LEVEL_UPDATED, { details: newDetails, level: newLevelId });
  2533.  
  2534.       // compute start position
  2535.       if (this.startFragRequested === false) {
  2536.         // if live playlist, set start position to be fragment N-this.config.liveSyncDurationCount (usually 3)
  2537.         if (newDetails.live) {
  2538.           var targetLatency = this.config.liveSyncDuration !== undefined ? this.config.liveSyncDuration : this.config.liveSyncDurationCount * newDetails.targetduration;
  2539.           this.startPosition = Math.max(0, sliding + duration - targetLatency);
  2540.         }
  2541.         this.nextLoadPosition = this.startPosition;
  2542.       }
  2543.       // only switch batck to IDLE state if we were waiting for level to start downloading a new fragment
  2544.       if (this.state === State.WAITING_LEVEL) {
  2545.         this.state = State.IDLE;
  2546.       }
  2547.       //trigger handler right now
  2548.       this.tick();
  2549.     }
  2550.   }, {
  2551.     key: 'onKeyLoaded',
  2552.     value: function onKeyLoaded() {
  2553.       if (this.state === State.KEY_LOADING) {
  2554.         this.state = State.IDLE;
  2555.         this.tick();
  2556.       }
  2557.     }
  2558.   }, {
  2559.     key: 'onFragLoaded',
  2560.     value: function onFragLoaded(data) {
  2561.       var fragCurrent = this.fragCurrent;
  2562.       if (this.state === State.FRAG_LOADING && fragCurrent && data.frag.level === fragCurrent.level && data.frag.sn === fragCurrent.sn) {
  2563.         _logger.logger.log('Loaded  ' + fragCurrent.sn + ' of level ' + fragCurrent.level);
  2564.         if (this.fragBitrateTest === true) {
  2565.           // switch back to IDLE state ... we just loaded a fragment to determine adequate start bitrate and initialize autoswitch algo
  2566.           this.state = State.IDLE;
  2567.           this.fragBitrateTest = false;
  2568.           this.startFragRequested = false;
  2569.           data.stats.tparsed = data.stats.tbuffered = performance.now();
  2570.           this.hls.trigger(_events2.default.FRAG_BUFFERED, { stats: data.stats, frag: fragCurrent });
  2571.         } else {
  2572.           this.state = State.PARSING;
  2573.           // transmux the MPEG-TS data to ISO-BMFF segments
  2574.           this.stats = data.stats;
  2575.           var currentLevel = this.levels[this.level],
  2576.               details = currentLevel.details,
  2577.               duration = details.totalduration,
  2578.               start = fragCurrent.start,
  2579.               level = fragCurrent.level,
  2580.               sn = fragCurrent.sn,
  2581.               audioCodec = this.config.defaultAudioCodec || currentLevel.audioCodec;
  2582.           if (this.audioCodecSwap) {
  2583.             _logger.logger.log('swapping playlist audio codec');
  2584.             if (audioCodec === undefined) {
  2585.               audioCodec = this.lastAudioCodec;
  2586.             }
  2587.             if (audioCodec) {
  2588.               if (audioCodec.indexOf('mp4a.40.5') !== -1) {
  2589.                 audioCodec = 'mp4a.40.2';
  2590.               } else {
  2591.                 audioCodec = 'mp4a.40.5';
  2592.               }
  2593.             }
  2594.           }
  2595.           this.pendingAppending = 0;
  2596.           _logger.logger.log('Demuxing ' + sn + ' of [' + details.startSN + ' ,' + details.endSN + '],level ' + level);
  2597.           var demuxer = this.demuxer;
  2598.           if (demuxer) {
  2599.             demuxer.push(data.payload, audioCodec, currentLevel.videoCodec, start, fragCurrent.cc, level, sn, duration, fragCurrent.decryptdata);
  2600.           }
  2601.         }
  2602.       }
  2603.       this.fragLoadError = 0;
  2604.     }
  2605.   }, {
  2606.     key: 'onFragParsingInitSegment',
  2607.     value: function onFragParsingInitSegment(data) {
  2608.       if (this.state === State.PARSING) {
  2609.         var tracks = data.tracks,
  2610.             trackName,
  2611.             track;
  2612.  
  2613.         // include levelCodec in audio and video tracks
  2614.         track = tracks.audio;
  2615.         if (track) {
  2616.           var audioCodec = this.levels[this.level].audioCodec,
  2617.               ua = navigator.userAgent.toLowerCase();
  2618.           if (audioCodec && this.audioCodecSwap) {
  2619.             _logger.logger.log('swapping playlist audio codec');
  2620.             if (audioCodec.indexOf('mp4a.40.5') !== -1) {
  2621.               audioCodec = 'mp4a.40.2';
  2622.             } else {
  2623.               audioCodec = 'mp4a.40.5';
  2624.             }
  2625.           }
  2626.           // in case AAC and HE-AAC audio codecs are signalled in manifest
  2627.           // force HE-AAC , as it seems that most browsers prefers that way,
  2628.           // except for mono streams OR on FF
  2629.           // these conditions might need to be reviewed ...
  2630.           if (this.audioCodecSwitch) {
  2631.             // don't force HE-AAC if mono stream
  2632.             if (track.metadata.channelCount !== 1 &&
  2633.             // don't force HE-AAC if firefox
  2634.             ua.indexOf('firefox') === -1) {
  2635.               audioCodec = 'mp4a.40.5';
  2636.             }
  2637.           }
  2638.           // HE-AAC is broken on Android, always signal audio codec as AAC even if variant manifest states otherwise
  2639.           if (ua.indexOf('android') !== -1) {
  2640.             audioCodec = 'mp4a.40.2';
  2641.             _logger.logger.log('Android: force audio codec to' + audioCodec);
  2642.           }
  2643.           track.levelCodec = audioCodec;
  2644.         }
  2645.         track = tracks.video;
  2646.         if (track) {
  2647.           track.levelCodec = this.levels[this.level].videoCodec;
  2648.         }
  2649.  
  2650.         // if remuxer specify that a unique track needs to generated,
  2651.         // let's merge all tracks together
  2652.         if (data.unique) {
  2653.           var mergedTrack = {
  2654.             codec: '',
  2655.             levelCodec: ''
  2656.           };
  2657.           for (trackName in data.tracks) {
  2658.             track = tracks[trackName];
  2659.             mergedTrack.container = track.container;
  2660.             if (mergedTrack.codec) {
  2661.               mergedTrack.codec += ',';
  2662.               mergedTrack.levelCodec += ',';
  2663.             }
  2664.             if (track.codec) {
  2665.               mergedTrack.codec += track.codec;
  2666.             }
  2667.             if (track.levelCodec) {
  2668.               mergedTrack.levelCodec += track.levelCodec;
  2669.             }
  2670.           }
  2671.           tracks = { audiovideo: mergedTrack };
  2672.         }
  2673.         this.hls.trigger(_events2.default.BUFFER_CODECS, tracks);
  2674.         // loop through tracks that are going to be provided to bufferController
  2675.         for (trackName in tracks) {
  2676.           track = tracks[trackName];
  2677.           _logger.logger.log('track:' + trackName + ',container:' + track.container + ',codecs[level/parsed]=[' + track.levelCodec + '/' + track.codec + ']');
  2678.           var initSegment = track.initSegment;
  2679.           if (initSegment) {
  2680.             this.pendingAppending++;
  2681.             this.hls.trigger(_events2.default.BUFFER_APPENDING, { type: trackName, data: initSegment });
  2682.           }
  2683.         }
  2684.         //trigger handler right now
  2685.         this.tick();
  2686.       }
  2687.     }
  2688.   }, {
  2689.     key: 'onFragParsingData',
  2690.     value: function onFragParsingData(data) {
  2691.       var _this2 = this;
  2692.  
  2693.       if (this.state === State.PARSING) {
  2694.         this.tparse2 = Date.now();
  2695.         var level = this.levels[this.level],
  2696.             frag = this.fragCurrent;
  2697.  
  2698.         _logger.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);
  2699.  
  2700.         var drift = _levelHelper2.default.updateFragPTS(level.details, frag.sn, data.startPTS, data.endPTS),
  2701.             hls = this.hls;
  2702.         hls.trigger(_events2.default.LEVEL_PTS_UPDATED, { details: level.details, level: this.level, drift: drift });
  2703.  
  2704.         [data.data1, data.data2].forEach(function (buffer) {
  2705.           if (buffer) {
  2706.             _this2.pendingAppending++;
  2707.             hls.trigger(_events2.default.BUFFER_APPENDING, { type: data.type, data: buffer });
  2708.           }
  2709.         });
  2710.  
  2711.         this.nextLoadPosition = data.endPTS;
  2712.         this.bufferRange.push({ type: data.type, start: data.startPTS, end: data.endPTS, frag: frag });
  2713.  
  2714.         //trigger handler right now
  2715.         this.tick();
  2716.       } else {
  2717.         _logger.logger.warn('not in PARSING state but ' + this.state + ', ignoring FRAG_PARSING_DATA event');
  2718.       }
  2719.     }
  2720.   }, {
  2721.     key: 'onFragParsed',
  2722.     value: function onFragParsed() {
  2723.       if (this.state === State.PARSING) {
  2724.         this.stats.tparsed = performance.now();
  2725.         this.state = State.PARSED;
  2726.         this._checkAppendedParsed();
  2727.       }
  2728.     }
  2729.   }, {
  2730.     key: 'onBufferAppended',
  2731.     value: function onBufferAppended() {
  2732.       switch (this.state) {
  2733.         case State.PARSING:
  2734.         case State.PARSED:
  2735.           this.pendingAppending--;
  2736.           this._checkAppendedParsed();
  2737.           break;
  2738.         default:
  2739.           break;
  2740.       }
  2741.     }
  2742.   }, {
  2743.     key: '_checkAppendedParsed',
  2744.     value: function _checkAppendedParsed() {
  2745.       //trigger handler right now
  2746.       if (this.state === State.PARSED && this.pendingAppending === 0) {
  2747.         var frag = this.fragCurrent,
  2748.             stats = this.stats;
  2749.         if (frag) {
  2750.           this.fragPrevious = frag;
  2751.           stats.tbuffered = performance.now();
  2752.           this.fragLastKbps = Math.round(8 * stats.length / (stats.tbuffered - stats.tfirst));
  2753.           this.hls.trigger(_events2.default.FRAG_BUFFERED, { stats: stats, frag: frag });
  2754.           _logger.logger.log('media buffered : ' + this.timeRangesToString(this.media.buffered));
  2755.           this.state = State.IDLE;
  2756.         }
  2757.         this.tick();
  2758.       }
  2759.     }
  2760.   }, {
  2761.     key: 'onError',
  2762.     value: function onError(data) {
  2763.       switch (data.details) {
  2764.         case _errors.ErrorDetails.FRAG_LOAD_ERROR:
  2765.         case _errors.ErrorDetails.FRAG_LOAD_TIMEOUT:
  2766.           if (!data.fatal) {
  2767.             var loadError = this.fragLoadError;
  2768.             if (loadError) {
  2769.               loadError++;
  2770.             } else {
  2771.               loadError = 1;
  2772.             }
  2773.             if (loadError <= this.config.fragLoadingMaxRetry) {
  2774.               this.fragLoadError = loadError;
  2775.               // reset load counter to avoid frag loop loading error
  2776.               data.frag.loadCounter = 0;
  2777.               // exponential backoff capped to 64s
  2778.               var delay = Math.min(Math.pow(2, loadError - 1) * this.config.fragLoadingRetryDelay, 64000);
  2779.               _logger.logger.warn('mediaController: frag loading failed, retry in ' + delay + ' ms');
  2780.               this.retryDate = performance.now() + delay;
  2781.               // retry loading state
  2782.               this.state = State.FRAG_LOADING_WAITING_RETRY;
  2783.             } else {
  2784.               _logger.logger.error('mediaController: ' + data.details + ' reaches max retry, redispatch as fatal ...');
  2785.               // redispatch same error but with fatal set to true
  2786.               data.fatal = true;
  2787.               this.hls.trigger(_events2.default.ERROR, data);
  2788.               this.state = State.ERROR;
  2789.             }
  2790.           }
  2791.           break;
  2792.         case _errors.ErrorDetails.FRAG_LOOP_LOADING_ERROR:
  2793.         case _errors.ErrorDetails.LEVEL_LOAD_ERROR:
  2794.         case _errors.ErrorDetails.LEVEL_LOAD_TIMEOUT:
  2795.         case _errors.ErrorDetails.KEY_LOAD_ERROR:
  2796.         case _errors.ErrorDetails.KEY_LOAD_TIMEOUT:
  2797.           //  when in ERROR state, don't switch back to IDLE state in case a non-fatal error is received
  2798.           if (this.state !== State.ERROR) {
  2799.             // if fatal error, stop processing, otherwise move to IDLE to retry loading
  2800.             this.state = data.fatal ? State.ERROR : State.IDLE;
  2801.             _logger.logger.warn('mediaController: ' + data.details + ' while loading frag,switch to ' + this.state + ' state ...');
  2802.           }
  2803.           break;
  2804.         case _errors.ErrorDetails.BUFFER_FULL_ERROR:
  2805.           // trigger a smooth level switch to empty buffers
  2806.           // also reduce max buffer length as it might be too high. we do this to avoid loop flushing ...
  2807.           this.config.maxMaxBufferLength /= 2;
  2808.           _logger.logger.warn('reduce max buffer length to ' + this.config.maxMaxBufferLength + 's and trigger a nextLevelSwitch to flush old buffer and fix QuotaExceededError');
  2809.           this.nextLevelSwitch();
  2810.           break;
  2811.         default:
  2812.           break;
  2813.       }
  2814.     }
  2815.   }, {
  2816.     key: '_checkBuffer',
  2817.     value: function _checkBuffer() {
  2818.       var media = this.media;
  2819.       if (media) {
  2820.         // compare readyState
  2821.         var readyState = media.readyState;
  2822.         // if ready state different from HAVE_NOTHING (numeric value 0), we are allowed to seek
  2823.         if (readyState) {
  2824.           var targetSeekPosition, currentTime;
  2825.           // if seek after buffered defined, let's seek if within acceptable range
  2826.           var seekAfterBuffered = this.seekAfterBuffered;
  2827.           if (seekAfterBuffered) {
  2828.             if (media.duration >= seekAfterBuffered) {
  2829.               targetSeekPosition = seekAfterBuffered;
  2830.               this.seekAfterBuffered = undefined;
  2831.             }
  2832.           } else {
  2833.             currentTime = media.currentTime;
  2834.             var loadedmetadata = this.loadedmetadata;
  2835.  
  2836.             // adjust currentTime to start position on loaded metadata
  2837.             if (!loadedmetadata && media.buffered.length) {
  2838.               this.loadedmetadata = true;
  2839.               // only adjust currentTime if not equal to 0
  2840.               if (!currentTime && currentTime !== this.startPosition) {
  2841.                 targetSeekPosition = this.startPosition;
  2842.               }
  2843.             }
  2844.           }
  2845.           if (targetSeekPosition) {
  2846.             currentTime = targetSeekPosition;
  2847.             _logger.logger.log('target seek position:' + targetSeekPosition);
  2848.           }
  2849.           var bufferInfo = _bufferHelper2.default.bufferInfo(media, currentTime, 0),
  2850.               expectedPlaying = !(media.paused || media.ended || media.seeking || readyState < 2),
  2851.               jumpThreshold = 0.4,
  2852.               // tolerance needed as some browsers stalls playback before reaching buffered range end
  2853.           playheadMoving = currentTime > media.playbackRate * this.lastCurrentTime;
  2854.  
  2855.           if (this.stalled && playheadMoving) {
  2856.             this.stalled = false;
  2857.             _logger.logger.log('playback not stuck anymore @' + currentTime);
  2858.           }
  2859.           // check buffer upfront
  2860.           // if less than jumpThreshold second is buffered, and media is expected to play but playhead is not moving,
  2861.           // and we have a new buffer range available upfront, let's seek to that one
  2862.           if (expectedPlaying && bufferInfo.len <= jumpThreshold) {
  2863.             if (playheadMoving) {
  2864.               // playhead moving
  2865.               jumpThreshold = 0;
  2866.               this.seekHoleNudgeDuration = 0;
  2867.             } else {
  2868.               // playhead not moving AND media expected to play
  2869.               if (!this.stalled) {
  2870.                 this.seekHoleNudgeDuration = 0;
  2871.                 _logger.logger.log('playback seems stuck @' + currentTime);
  2872.                 this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.BUFFER_STALLED_ERROR, fatal: false });
  2873.                 this.stalled = true;
  2874.               } else {
  2875.                 this.seekHoleNudgeDuration += this.config.seekHoleNudgeDuration;
  2876.               }
  2877.             }
  2878.             // if we are below threshold, try to jump if next buffer range is close
  2879.             if (bufferInfo.len <= jumpThreshold) {
  2880.               // no buffer available @ currentTime, check if next buffer is close (within a config.maxSeekHole second range)
  2881.               var nextBufferStart = bufferInfo.nextStart,
  2882.                   delta = nextBufferStart - currentTime;
  2883.               if (nextBufferStart && delta < this.config.maxSeekHole && delta > 0 && !media.seeking) {
  2884.                 // next buffer is close ! adjust currentTime to nextBufferStart
  2885.                 // this will ensure effective video decoding
  2886.                 _logger.logger.log('adjust currentTime from ' + media.currentTime + ' to next buffered @ ' + nextBufferStart + ' + nudge ' + this.seekHoleNudgeDuration);
  2887.                 var hole = nextBufferStart + this.seekHoleNudgeDuration - media.currentTime;
  2888.                 media.currentTime = nextBufferStart + this.seekHoleNudgeDuration;
  2889.                 this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.BUFFER_SEEK_OVER_HOLE, fatal: false, hole: hole });
  2890.               }
  2891.             }
  2892.           } else {
  2893.             var _currentTime = media.currentTime;
  2894.             if (targetSeekPosition && _currentTime !== targetSeekPosition) {
  2895.               if (bufferInfo.len === 0) {
  2896.                 var nextStart = bufferInfo.nextStart;
  2897.                 if (nextStart !== undefined && nextStart - targetSeekPosition < this.config.maxSeekHole) {
  2898.                   targetSeekPosition = nextStart;
  2899.                   _logger.logger.log('target seek position not buffered, seek to next buffered ' + targetSeekPosition);
  2900.                 }
  2901.               }
  2902.               _logger.logger.log('adjust currentTime from ' + _currentTime + ' to ' + targetSeekPosition);
  2903.               media.currentTime = targetSeekPosition;
  2904.             }
  2905.           }
  2906.         }
  2907.       }
  2908.     }
  2909.   }, {
  2910.     key: 'onFragLoadEmergencyAborted',
  2911.     value: function onFragLoadEmergencyAborted() {
  2912.       this.state = State.IDLE;
  2913.       this.tick();
  2914.     }
  2915.   }, {
  2916.     key: 'onBufferFlushed',
  2917.     value: function onBufferFlushed() {
  2918.       /* after successful buffer flushing, rebuild buffer Range array
  2919.         loop through existing buffer range and check if
  2920.         corresponding range is still buffered. only push to new array already buffered range
  2921.       */
  2922.       var newRange = [],
  2923.           range,
  2924.           i;
  2925.       for (i = 0; i < this.bufferRange.length; i++) {
  2926.         range = this.bufferRange[i];
  2927.         if (this.isBuffered((range.start + range.end) / 2)) {
  2928.           newRange.push(range);
  2929.         }
  2930.       }
  2931.       this.bufferRange = newRange;
  2932.  
  2933.       // handle end of immediate switching if needed
  2934.       if (this.immediateSwitch) {
  2935.         this.immediateLevelSwitchEnd();
  2936.       }
  2937.       // move to IDLE once flush complete. this should trigger new fragment loading
  2938.       this.state = State.IDLE;
  2939.       // reset reference to frag
  2940.       this.fragPrevious = null;
  2941.     }
  2942.   }, {
  2943.     key: 'swapAudioCodec',
  2944.     value: function swapAudioCodec() {
  2945.       this.audioCodecSwap = !this.audioCodecSwap;
  2946.     }
  2947.   }, {
  2948.     key: 'timeRangesToString',
  2949.     value: function timeRangesToString(r) {
  2950.       var log = '',
  2951.           len = r.length;
  2952.       for (var i = 0; i < len; i++) {
  2953.         log += '[' + r.start(i) + ',' + r.end(i) + ']';
  2954.       }
  2955.       return log;
  2956.     }
  2957.   }, {
  2958.     key: 'state',
  2959.     set: function set(nextState) {
  2960.       if (this.state !== nextState) {
  2961.         var previousState = this.state;
  2962.         this._state = nextState;
  2963.         _logger.logger.log('engine state transition from ' + previousState + ' to ' + nextState);
  2964.         this.hls.trigger(State.STREAM_STATE_TRANSITION, { previousState: previousState, nextState: nextState });
  2965.       }
  2966.     },
  2967.     get: function get() {
  2968.       return this._state;
  2969.     }
  2970.   }, {
  2971.     key: 'currentLevel',
  2972.     get: function get() {
  2973.       if (this.media) {
  2974.         var range = this.getBufferRange(this.media.currentTime);
  2975.         if (range) {
  2976.           return range.frag.level;
  2977.         }
  2978.       }
  2979.       return -1;
  2980.     }
  2981.   }, {
  2982.     key: 'nextBufferRange',
  2983.     get: function get() {
  2984.       if (this.media) {
  2985.         // first get end range of current fragment
  2986.         return this.followingBufferRange(this.getBufferRange(this.media.currentTime));
  2987.       } else {
  2988.         return null;
  2989.       }
  2990.     }
  2991.   }, {
  2992.     key: 'nextLevel',
  2993.     get: function get() {
  2994.       var range = this.nextBufferRange;
  2995.       if (range) {
  2996.         return range.frag.level;
  2997.       } else {
  2998.         return -1;
  2999.       }
  3000.     }
  3001.   }]);
  3002.  
  3003.   return StreamController;
  3004. }(_eventHandler2.default);
  3005.  
  3006. exports.default = StreamController;
  3007.  
  3008. },{"../demux/demuxer":17,"../errors":21,"../event-handler":22,"../events":23,"../helper/buffer-helper":25,"../helper/level-helper":26,"../utils/binary-search":36,"../utils/logger":39}],9:[function(require,module,exports){
  3009. 'use strict';
  3010.  
  3011. Object.defineProperty(exports, "__esModule", {
  3012.   value: true
  3013. });
  3014.  
  3015. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  3016.  
  3017. var _events = require('../events');
  3018.  
  3019. var _events2 = _interopRequireDefault(_events);
  3020.  
  3021. var _eventHandler = require('../event-handler');
  3022.  
  3023. var _eventHandler2 = _interopRequireDefault(_eventHandler);
  3024.  
  3025. var _cea608Parser = require('../utils/cea-608-parser');
  3026.  
  3027. var _cea608Parser2 = _interopRequireDefault(_cea608Parser);
  3028.  
  3029. var _cues = require('../utils/cues');
  3030.  
  3031. var _cues2 = _interopRequireDefault(_cues);
  3032.  
  3033. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  3034.  
  3035. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  3036.  
  3037. function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
  3038.  
  3039. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /*
  3040.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 * Timeline Controller
  3041.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                */
  3042.  
  3043. var TimelineController = function (_EventHandler) {
  3044.   _inherits(TimelineController, _EventHandler);
  3045.  
  3046.   function TimelineController(hls) {
  3047.     _classCallCheck(this, TimelineController);
  3048.  
  3049.     var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(TimelineController).call(this, hls, _events2.default.MEDIA_ATTACHING, _events2.default.MEDIA_DETACHING, _events2.default.FRAG_PARSING_USERDATA, _events2.default.MANIFEST_LOADING, _events2.default.FRAG_LOADED, _events2.default.LEVEL_SWITCH));
  3050.  
  3051.     _this.hls = hls;
  3052.     _this.config = hls.config;
  3053.     _this.enabled = true;
  3054.  
  3055.     if (_this.config.enableCEA708Captions) {
  3056.       var self = _this;
  3057.  
  3058.       var channel1 = {
  3059.         'newCue': function newCue(startTime, endTime, screen) {
  3060.           if (!self.textTrack1) {
  3061.             self.textTrack1 = self.createTextTrack('captions', 'Unknown CC1', 'en');
  3062.             //            self.textTrack1.mode = 'showing';
  3063.           }
  3064.  
  3065.           _cues2.default.newCue(self.textTrack1, startTime, endTime, screen);
  3066.         }
  3067.       };
  3068.  
  3069.       var channel2 = {
  3070.         'newCue': function newCue(startTime, endTime, screen) {
  3071.           if (!self.textTrack2) {
  3072.             self.textTrack2 = self.createTextTrack('captions', 'Unknown CC2', 'es');
  3073.           }
  3074.  
  3075.           _cues2.default.newCue(self.textTrack2, startTime, endTime, screen);
  3076.         }
  3077.       };
  3078.  
  3079.       _this.cea608Parser = new _cea608Parser2.default(0, channel1, channel2);
  3080.     }
  3081.     return _this;
  3082.   }
  3083.  
  3084.   _createClass(TimelineController, [{
  3085.     key: 'clearCurrentCues',
  3086.     value: function clearCurrentCues(track) {
  3087.       if (track && track.cues) {
  3088.         while (track.cues.length > 0) {
  3089.           track.removeCue(track.cues[0]);
  3090.         }
  3091.       }
  3092.     }
  3093.   }, {
  3094.     key: 'createTextTrack',
  3095.     value: function createTextTrack(kind, label, lang) {
  3096.       if (this.media) {
  3097.         return this.media.addTextTrack(kind, label, lang);
  3098.       }
  3099.     }
  3100.   }, {
  3101.     key: 'destroy',
  3102.     value: function destroy() {
  3103.       _eventHandler2.default.prototype.destroy.call(this);
  3104.     }
  3105.   }, {
  3106.     key: 'onMediaAttaching',
  3107.     value: function onMediaAttaching(data) {
  3108.       this.media = data.media;
  3109.     }
  3110.   }, {
  3111.     key: 'onMediaDetaching',
  3112.     value: function onMediaDetaching() {}
  3113.   }, {
  3114.     key: 'onManifestLoading',
  3115.     value: function onManifestLoading() {
  3116.       this.lastPts = Number.NEGATIVE_INFINITY;
  3117.     }
  3118.   }, {
  3119.     key: 'onLevelSwitch',
  3120.     value: function onLevelSwitch() {
  3121.       if (this.hls.currentLevel.closedCaptions === 'NONE') {
  3122.         this.enabled = false;
  3123.       } else {
  3124.         this.enabled = true;
  3125.       }
  3126.     }
  3127.   }, {
  3128.     key: 'onFragLoaded',
  3129.     value: function onFragLoaded(data) {
  3130.       var pts = data.frag.start;
  3131.  
  3132.       // if this is a frag for a previously loaded timerange, remove all captions
  3133.       // TODO: consider just removing captions for the timerange
  3134.       if (pts <= this.lastPts) {
  3135.         this.clearCurrentCues(this.textTrack1);
  3136.         this.clearCurrentCues(this.textTrack2);
  3137.       }
  3138.  
  3139.       this.lastPts = pts;
  3140.     }
  3141.   }, {
  3142.     key: 'onFragParsingUserdata',
  3143.     value: function onFragParsingUserdata(data) {
  3144.       // push all of the CEA-708 messages into the interpreter
  3145.       // immediately. It will create the proper timestamps based on our PTS value
  3146.       if (this.enabled) {
  3147.         for (var i = 0; i < data.samples.length; i++) {
  3148.           var ccdatas = this.extractCea608Data(data.samples[i].bytes);
  3149.           this.cea608Parser.addData(data.samples[i].pts, ccdatas);
  3150.         }
  3151.       }
  3152.     }
  3153.   }, {
  3154.     key: 'extractCea608Data',
  3155.     value: function extractCea608Data(byteArray) {
  3156.       var count = byteArray[0] & 31;
  3157.       var position = 2;
  3158.       var tmpByte, ccbyte1, ccbyte2, ccValid, ccType;
  3159.       var actualCCBytes = [];
  3160.  
  3161.       for (var j = 0; j < count; j++) {
  3162.         tmpByte = byteArray[position++];
  3163.         ccbyte1 = 0x7F & byteArray[position++];
  3164.         ccbyte2 = 0x7F & byteArray[position++];
  3165.         ccValid = (4 & tmpByte) === 0 ? false : true;
  3166.         ccType = 3 & tmpByte;
  3167.  
  3168.         if (ccbyte1 === 0 && ccbyte2 === 0) {
  3169.           continue;
  3170.         }
  3171.  
  3172.         if (ccValid) {
  3173.           if (ccType === 0) // || ccType === 1
  3174.             {
  3175.               actualCCBytes.push(ccbyte1);
  3176.               actualCCBytes.push(ccbyte2);
  3177.             }
  3178.         }
  3179.       }
  3180.       return actualCCBytes;
  3181.     }
  3182.   }]);
  3183.  
  3184.   return TimelineController;
  3185. }(_eventHandler2.default);
  3186.  
  3187. exports.default = TimelineController;
  3188.  
  3189. },{"../event-handler":22,"../events":23,"../utils/cea-608-parser":37,"../utils/cues":38}],10:[function(require,module,exports){
  3190. 'use strict';
  3191.  
  3192. Object.defineProperty(exports, "__esModule", {
  3193.   value: true
  3194. });
  3195.  
  3196. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  3197.  
  3198. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  3199.  
  3200. /*
  3201.  *
  3202.  * This file contains an adaptation of the AES decryption algorithm
  3203.  * from the Standford Javascript Cryptography Library. That work is
  3204.  * covered by the following copyright and permissions notice:
  3205.  *
  3206.  * Copyright 2009-2010 Emily Stark, Mike Hamburg, Dan Boneh.
  3207.  * All rights reserved.
  3208.  *
  3209.  * Redistribution and use in source and binary forms, with or without
  3210.  * modification, are permitted provided that the following conditions are
  3211.  * met:
  3212.  *
  3213.  * 1. Redistributions of source code must retain the above copyright
  3214.  *    notice, this list of conditions and the following disclaimer.
  3215.  *
  3216.  * 2. Redistributions in binary form must reproduce the above
  3217.  *    copyright notice, this list of conditions and the following
  3218.  *    disclaimer in the documentation and/or other materials provided
  3219.  *    with the distribution.
  3220.  *
  3221.  * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
  3222.  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  3223.  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  3224.  * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> OR CONTRIBUTORS BE
  3225.  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  3226.  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  3227.  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
  3228.  * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  3229.  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
  3230.  * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
  3231.  * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  3232.  *
  3233.  * The views and conclusions contained in the software and documentation
  3234.  * are those of the authors and should not be interpreted as representing
  3235.  * official policies, either expressed or implied, of the authors.
  3236.  */
  3237.  
  3238. var AES = function () {
  3239.  
  3240.   /**
  3241.    * Schedule out an AES key for both encryption and decryption. This
  3242.    * is a low-level class. Use a cipher mode to do bulk encryption.
  3243.    *
  3244.    * @constructor
  3245.    * @param key {Array} The key as an array of 4, 6 or 8 words.
  3246.    */
  3247.  
  3248.   function AES(key) {
  3249.     _classCallCheck(this, AES);
  3250.  
  3251.     /**
  3252.      * The expanded S-box and inverse S-box tables. These will be computed
  3253.      * on the client so that we don't have to send them down the wire.
  3254.      *
  3255.      * There are two tables, _tables[0] is for encryption and
  3256.      * _tables[1] is for decryption.
  3257.      *
  3258.      * The first 4 sub-tables are the expanded S-box with MixColumns. The
  3259.      * last (_tables[01][4]) is the S-box itself.
  3260.      *
  3261.      * @private
  3262.      */
  3263.     this._tables = [[[], [], [], [], []], [[], [], [], [], []]];
  3264.  
  3265.     this._precompute();
  3266.  
  3267.     var i,
  3268.         j,
  3269.         tmp,
  3270.         encKey,
  3271.         decKey,
  3272.         sbox = this._tables[0][4],
  3273.         decTable = this._tables[1],
  3274.         keyLen = key.length,
  3275.         rcon = 1;
  3276.  
  3277.     if (keyLen !== 4 && keyLen !== 6 && keyLen !== 8) {
  3278.       throw new Error('Invalid aes key size=' + keyLen);
  3279.     }
  3280.  
  3281.     encKey = key.slice(0);
  3282.     decKey = [];
  3283.     this._key = [encKey, decKey];
  3284.  
  3285.     // schedule encryption keys
  3286.     for (i = keyLen; i < 4 * keyLen + 28; i++) {
  3287.       tmp = encKey[i - 1];
  3288.  
  3289.       // apply sbox
  3290.       if (i % keyLen === 0 || keyLen === 8 && i % keyLen === 4) {
  3291.         tmp = sbox[tmp >>> 24] << 24 ^ sbox[tmp >> 16 & 255] << 16 ^ sbox[tmp >> 8 & 255] << 8 ^ sbox[tmp & 255];
  3292.  
  3293.         // shift rows and add rcon
  3294.         if (i % keyLen === 0) {
  3295.           tmp = tmp << 8 ^ tmp >>> 24 ^ rcon << 24;
  3296.           rcon = rcon << 1 ^ (rcon >> 7) * 283;
  3297.         }
  3298.       }
  3299.  
  3300.       encKey[i] = encKey[i - keyLen] ^ tmp;
  3301.     }
  3302.  
  3303.     // schedule decryption keys
  3304.     for (j = 0; i; j++, i--) {
  3305.       tmp = encKey[j & 3 ? i : i - 4];
  3306.       if (i <= 4 || j < 4) {
  3307.         decKey[j] = tmp;
  3308.       } else {
  3309.         decKey[j] = decTable[0][sbox[tmp >>> 24]] ^ decTable[1][sbox[tmp >> 16 & 255]] ^ decTable[2][sbox[tmp >> 8 & 255]] ^ decTable[3][sbox[tmp & 255]];
  3310.       }
  3311.     }
  3312.   }
  3313.  
  3314.   /**
  3315.    * Expand the S-box tables.
  3316.    *
  3317.    * @private
  3318.    */
  3319.  
  3320.  
  3321.   _createClass(AES, [{
  3322.     key: '_precompute',
  3323.     value: function _precompute() {
  3324.       var encTable = this._tables[0],
  3325.           decTable = this._tables[1],
  3326.           sbox = encTable[4],
  3327.           sboxInv = decTable[4],
  3328.           i,
  3329.           x,
  3330.           xInv,
  3331.           d = [],
  3332.           th = [],
  3333.           x2,
  3334.           x4,
  3335.           x8,
  3336.           s,
  3337.           tEnc,
  3338.           tDec;
  3339.  
  3340.       // Compute double and third tables
  3341.       for (i = 0; i < 256; i++) {
  3342.         th[(d[i] = i << 1 ^ (i >> 7) * 283) ^ i] = i;
  3343.       }
  3344.  
  3345.       for (x = xInv = 0; !sbox[x]; x ^= x2 || 1, xInv = th[xInv] || 1) {
  3346.         // Compute sbox
  3347.         s = xInv ^ xInv << 1 ^ xInv << 2 ^ xInv << 3 ^ xInv << 4;
  3348.         s = s >> 8 ^ s & 255 ^ 99;
  3349.         sbox[x] = s;
  3350.         sboxInv[s] = x;
  3351.  
  3352.         // Compute MixColumns
  3353.         x8 = d[x4 = d[x2 = d[x]]];
  3354.         tDec = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100;
  3355.         tEnc = d[s] * 0x101 ^ s * 0x1010100;
  3356.  
  3357.         for (i = 0; i < 4; i++) {
  3358.           encTable[i][x] = tEnc = tEnc << 24 ^ tEnc >>> 8;
  3359.           decTable[i][s] = tDec = tDec << 24 ^ tDec >>> 8;
  3360.         }
  3361.       }
  3362.  
  3363.       // Compactify. Considerable speedup on Firefox.
  3364.       for (i = 0; i < 5; i++) {
  3365.         encTable[i] = encTable[i].slice(0);
  3366.         decTable[i] = decTable[i].slice(0);
  3367.       }
  3368.     }
  3369.  
  3370.     /**
  3371.      * Decrypt 16 bytes, specified as four 32-bit words.
  3372.      * @param encrypted0 {number} the first word to decrypt
  3373.      * @param encrypted1 {number} the second word to decrypt
  3374.      * @param encrypted2 {number} the third word to decrypt
  3375.      * @param encrypted3 {number} the fourth word to decrypt
  3376.      * @param out {Int32Array} the array to write the decrypted words
  3377.      * into
  3378.      * @param offset {number} the offset into the output array to start
  3379.      * writing results
  3380.      * @return {Array} The plaintext.
  3381.      */
  3382.  
  3383.   }, {
  3384.     key: 'decrypt',
  3385.     value: function decrypt(encrypted0, encrypted1, encrypted2, encrypted3, out, offset) {
  3386.       var key = this._key[1],
  3387.  
  3388.       // state variables a,b,c,d are loaded with pre-whitened data
  3389.       a = encrypted0 ^ key[0],
  3390.           b = encrypted3 ^ key[1],
  3391.           c = encrypted2 ^ key[2],
  3392.           d = encrypted1 ^ key[3],
  3393.           a2,
  3394.           b2,
  3395.           c2,
  3396.           nInnerRounds = key.length / 4 - 2,
  3397.           // key.length === 2 ?
  3398.       i,
  3399.           kIndex = 4,
  3400.           table = this._tables[1],
  3401.  
  3402.  
  3403.       // load up the tables
  3404.       table0 = table[0],
  3405.           table1 = table[1],
  3406.           table2 = table[2],
  3407.           table3 = table[3],
  3408.           sbox = table[4];
  3409.  
  3410.       // Inner rounds. Cribbed from OpenSSL.
  3411.       for (i = 0; i < nInnerRounds; i++) {
  3412.         a2 = table0[a >>> 24] ^ table1[b >> 16 & 255] ^ table2[c >> 8 & 255] ^ table3[d & 255] ^ key[kIndex];
  3413.         b2 = table0[b >>> 24] ^ table1[c >> 16 & 255] ^ table2[d >> 8 & 255] ^ table3[a & 255] ^ key[kIndex + 1];
  3414.         c2 = table0[c >>> 24] ^ table1[d >> 16 & 255] ^ table2[a >> 8 & 255] ^ table3[b & 255] ^ key[kIndex + 2];
  3415.         d = table0[d >>> 24] ^ table1[a >> 16 & 255] ^ table2[b >> 8 & 255] ^ table3[c & 255] ^ key[kIndex + 3];
  3416.         kIndex += 4;
  3417.         a = a2;b = b2;c = c2;
  3418.       }
  3419.  
  3420.       // Last round.
  3421.       for (i = 0; i < 4; i++) {
  3422.         out[(3 & -i) + offset] = sbox[a >>> 24] << 24 ^ sbox[b >> 16 & 255] << 16 ^ sbox[c >> 8 & 255] << 8 ^ sbox[d & 255] ^ key[kIndex++];
  3423.         a2 = a;a = b;b = c;c = d;d = a2;
  3424.       }
  3425.     }
  3426.   }]);
  3427.  
  3428.   return AES;
  3429. }();
  3430.  
  3431. exports.default = AES;
  3432.  
  3433. },{}],11:[function(require,module,exports){
  3434. 'use strict';
  3435.  
  3436. Object.defineProperty(exports, "__esModule", {
  3437.   value: true
  3438. });
  3439.  
  3440. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /*
  3441.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       *
  3442.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       * This file contains an adaptation of the AES decryption algorithm
  3443.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       * from the Standford Javascript Cryptography Library. That work is
  3444.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       * covered by the following copyright and permissions notice:
  3445.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       *
  3446.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       * Copyright 2009-2010 Emily Stark, Mike Hamburg, Dan Boneh.
  3447.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       * All rights reserved.
  3448.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       *
  3449.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       * Redistribution and use in source and binary forms, with or without
  3450.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       * modification, are permitted provided that the following conditions are
  3451.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       * met:
  3452.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       *
  3453.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       * 1. Redistributions of source code must retain the above copyright
  3454.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       *    notice, this list of conditions and the following disclaimer.
  3455.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       *
  3456.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       * 2. Redistributions in binary form must reproduce the above
  3457.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       *    copyright notice, this list of conditions and the following
  3458.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       *    disclaimer in the documentation and/or other materials provided
  3459.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       *    with the distribution.
  3460.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       *
  3461.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
  3462.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  3463.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  3464.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> OR CONTRIBUTORS BE
  3465.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  3466.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  3467.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
  3468.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  3469.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
  3470.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
  3471.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  3472.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       *
  3473.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       * The views and conclusions contained in the software and documentation
  3474.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       * are those of the authors and should not be interpreted as representing
  3475.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       * official policies, either expressed or implied, of the authors.
  3476.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       */
  3477.  
  3478. var _aes = require('./aes');
  3479.  
  3480. var _aes2 = _interopRequireDefault(_aes);
  3481.  
  3482. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  3483.  
  3484. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  3485.  
  3486. var AES128Decrypter = function () {
  3487.   function AES128Decrypter(key, initVector) {
  3488.     _classCallCheck(this, AES128Decrypter);
  3489.  
  3490.     this.key = key;
  3491.     this.iv = initVector;
  3492.   }
  3493.  
  3494.   /**
  3495.    * Convert network-order (big-endian) bytes into their little-endian
  3496.    * representation.
  3497.    */
  3498.  
  3499.  
  3500.   _createClass(AES128Decrypter, [{
  3501.     key: 'ntoh',
  3502.     value: function ntoh(word) {
  3503.       return word << 24 | (word & 0xff00) << 8 | (word & 0xff0000) >> 8 | word >>> 24;
  3504.     }
  3505.  
  3506.     /**
  3507.      * Decrypt bytes using AES-128 with CBC and PKCS#7 padding.
  3508.      * @param encrypted {Uint8Array} the encrypted bytes
  3509.      * @param key {Uint32Array} the bytes of the decryption key
  3510.      * @param initVector {Uint32Array} the initialization vector (IV) to
  3511.      * use for the first round of CBC.
  3512.      * @return {Uint8Array} the decrypted bytes
  3513.      *
  3514.      * @see http://en.wikipedia.org/wiki/Advanced_Encryption_Standard
  3515.      * @see http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Cipher_Block_Chaining_.28CBC.29
  3516.      * @see https://tools.ietf.org/html/rfc2315
  3517.      */
  3518.  
  3519.   }, {
  3520.     key: 'doDecrypt',
  3521.     value: function doDecrypt(encrypted, key, initVector) {
  3522.       var
  3523.       // word-level access to the encrypted bytes
  3524.       encrypted32 = new Int32Array(encrypted.buffer, encrypted.byteOffset, encrypted.byteLength >> 2),
  3525.           decipher = new _aes2.default(Array.prototype.slice.call(key)),
  3526.  
  3527.  
  3528.       // byte and word-level access for the decrypted output
  3529.       decrypted = new Uint8Array(encrypted.byteLength),
  3530.           decrypted32 = new Int32Array(decrypted.buffer),
  3531.  
  3532.  
  3533.       // temporary variables for working with the IV, encrypted, and
  3534.       // decrypted data
  3535.       init0,
  3536.           init1,
  3537.           init2,
  3538.           init3,
  3539.           encrypted0,
  3540.           encrypted1,
  3541.           encrypted2,
  3542.           encrypted3,
  3543.  
  3544.  
  3545.       // iteration variable
  3546.       wordIx;
  3547.  
  3548.       // pull out the words of the IV to ensure we don't modify the
  3549.       // passed-in reference and easier access
  3550.       init0 = ~ ~initVector[0];
  3551.       init1 = ~ ~initVector[1];
  3552.       init2 = ~ ~initVector[2];
  3553.       init3 = ~ ~initVector[3];
  3554.  
  3555.       // decrypt four word sequences, applying cipher-block chaining (CBC)
  3556.       // to each decrypted block
  3557.       for (wordIx = 0; wordIx < encrypted32.length; wordIx += 4) {
  3558.         // convert big-endian (network order) words into little-endian
  3559.         // (javascript order)
  3560.         encrypted0 = ~ ~this.ntoh(encrypted32[wordIx]);
  3561.         encrypted1 = ~ ~this.ntoh(encrypted32[wordIx + 1]);
  3562.         encrypted2 = ~ ~this.ntoh(encrypted32[wordIx + 2]);
  3563.         encrypted3 = ~ ~this.ntoh(encrypted32[wordIx + 3]);
  3564.  
  3565.         // decrypt the block
  3566.         decipher.decrypt(encrypted0, encrypted1, encrypted2, encrypted3, decrypted32, wordIx);
  3567.  
  3568.         // XOR with the IV, and restore network byte-order to obtain the
  3569.         // plaintext
  3570.         decrypted32[wordIx] = this.ntoh(decrypted32[wordIx] ^ init0);
  3571.         decrypted32[wordIx + 1] = this.ntoh(decrypted32[wordIx + 1] ^ init1);
  3572.         decrypted32[wordIx + 2] = this.ntoh(decrypted32[wordIx + 2] ^ init2);
  3573.         decrypted32[wordIx + 3] = this.ntoh(decrypted32[wordIx + 3] ^ init3);
  3574.  
  3575.         // setup the IV for the next round
  3576.         init0 = encrypted0;
  3577.         init1 = encrypted1;
  3578.         init2 = encrypted2;
  3579.         init3 = encrypted3;
  3580.       }
  3581.  
  3582.       return decrypted;
  3583.     }
  3584.   }, {
  3585.     key: 'localDecrypt',
  3586.     value: function localDecrypt(encrypted, key, initVector, decrypted) {
  3587.       var bytes = this.doDecrypt(encrypted, key, initVector);
  3588.       decrypted.set(bytes, encrypted.byteOffset);
  3589.     }
  3590.   }, {
  3591.     key: 'decrypt',
  3592.     value: function decrypt(encrypted) {
  3593.       var step = 4 * 8000,
  3594.  
  3595.       //encrypted32 = new Int32Array(encrypted.buffer),
  3596.       encrypted32 = new Int32Array(encrypted),
  3597.           decrypted = new Uint8Array(encrypted.byteLength),
  3598.           i = 0;
  3599.  
  3600.       // split up the encryption job and do the individual chunks asynchronously
  3601.       var key = this.key;
  3602.       var initVector = this.iv;
  3603.       this.localDecrypt(encrypted32.subarray(i, i + step), key, initVector, decrypted);
  3604.  
  3605.       for (i = step; i < encrypted32.length; i += step) {
  3606.         initVector = new Uint32Array([this.ntoh(encrypted32[i - 4]), this.ntoh(encrypted32[i - 3]), this.ntoh(encrypted32[i - 2]), this.ntoh(encrypted32[i - 1])]);
  3607.         this.localDecrypt(encrypted32.subarray(i, i + step), key, initVector, decrypted);
  3608.       }
  3609.  
  3610.       return decrypted;
  3611.     }
  3612.   }]);
  3613.  
  3614.   return AES128Decrypter;
  3615. }();
  3616.  
  3617. exports.default = AES128Decrypter;
  3618.  
  3619. },{"./aes":10}],12:[function(require,module,exports){
  3620. 'use strict';
  3621.  
  3622. Object.defineProperty(exports, "__esModule", {
  3623.   value: true
  3624. });
  3625.  
  3626. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /*
  3627.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       * AES128 decryption.
  3628.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       */
  3629.  
  3630. var _aes128Decrypter = require('./aes128-decrypter');
  3631.  
  3632. var _aes128Decrypter2 = _interopRequireDefault(_aes128Decrypter);
  3633.  
  3634. var _errors = require('../errors');
  3635.  
  3636. var _logger = require('../utils/logger');
  3637.  
  3638. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  3639.  
  3640. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  3641.  
  3642. var Decrypter = function () {
  3643.   function Decrypter(hls) {
  3644.     _classCallCheck(this, Decrypter);
  3645.  
  3646.     this.hls = hls;
  3647.     try {
  3648.       var browserCrypto = window ? window.crypto : crypto;
  3649.       this.subtle = browserCrypto.subtle || browserCrypto.webkitSubtle;
  3650.       this.disableWebCrypto = !this.subtle;
  3651.     } catch (e) {
  3652.       this.disableWebCrypto = true;
  3653.     }
  3654.   }
  3655.  
  3656.   _createClass(Decrypter, [{
  3657.     key: 'destroy',
  3658.     value: function destroy() {}
  3659.   }, {
  3660.     key: 'decrypt',
  3661.     value: function decrypt(data, key, iv, callback) {
  3662.       if (this.disableWebCrypto && this.hls.config.enableSoftwareAES) {
  3663.         this.decryptBySoftware(data, key, iv, callback);
  3664.       } else {
  3665.         this.decryptByWebCrypto(data, key, iv, callback);
  3666.       }
  3667.     }
  3668.   }, {
  3669.     key: 'decryptByWebCrypto',
  3670.     value: function decryptByWebCrypto(data, key, iv, callback) {
  3671.       var _this = this;
  3672.  
  3673.       _logger.logger.log('decrypting by WebCrypto API');
  3674.  
  3675.       this.subtle.importKey('raw', key, { name: 'AES-CBC', length: 128 }, false, ['decrypt']).then(function (importedKey) {
  3676.         _this.subtle.decrypt({ name: 'AES-CBC', iv: iv.buffer }, importedKey, data).then(callback).catch(function (err) {
  3677.           _this.onWebCryptoError(err, data, key, iv, callback);
  3678.         });
  3679.       }).catch(function (err) {
  3680.         _this.onWebCryptoError(err, data, key, iv, callback);
  3681.       });
  3682.     }
  3683.   }, {
  3684.     key: 'decryptBySoftware',
  3685.     value: function decryptBySoftware(data, key8, iv8, callback) {
  3686.       _logger.logger.log('decrypting by JavaScript Implementation');
  3687.  
  3688.       var view = new DataView(key8.buffer);
  3689.       var key = new Uint32Array([view.getUint32(0), view.getUint32(4), view.getUint32(8), view.getUint32(12)]);
  3690.  
  3691.       view = new DataView(iv8.buffer);
  3692.       var iv = new Uint32Array([view.getUint32(0), view.getUint32(4), view.getUint32(8), view.getUint32(12)]);
  3693.  
  3694.       var decrypter = new _aes128Decrypter2.default(key, iv);
  3695.       callback(decrypter.decrypt(data).buffer);
  3696.     }
  3697.   }, {
  3698.     key: 'onWebCryptoError',
  3699.     value: function onWebCryptoError(err, data, key, iv, callback) {
  3700.       if (this.hls.config.enableSoftwareAES) {
  3701.         _logger.logger.log('disabling to use WebCrypto API');
  3702.         this.disableWebCrypto = true;
  3703.         this.decryptBySoftware(data, key, iv, callback);
  3704.       } else {
  3705.         _logger.logger.error('decrypting error : ' + err.message);
  3706.         this.hls.trigger(Event.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.FRAG_DECRYPT_ERROR, fatal: true, reason: err.message });
  3707.       }
  3708.     }
  3709.   }]);
  3710.  
  3711.   return Decrypter;
  3712. }();
  3713.  
  3714. exports.default = Decrypter;
  3715.  
  3716. },{"../errors":21,"../utils/logger":39,"./aes128-decrypter":11}],13:[function(require,module,exports){
  3717. 'use strict';
  3718.  
  3719. Object.defineProperty(exports, "__esModule", {
  3720.   value: true
  3721. });
  3722.  
  3723. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /**
  3724.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       * AAC demuxer
  3725.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       */
  3726.  
  3727.  
  3728. var _adts = require('./adts');
  3729.  
  3730. var _adts2 = _interopRequireDefault(_adts);
  3731.  
  3732. var _logger = require('../utils/logger');
  3733.  
  3734. var _id = require('../demux/id3');
  3735.  
  3736. var _id2 = _interopRequireDefault(_id);
  3737.  
  3738. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  3739.  
  3740. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  3741.  
  3742. var AACDemuxer = function () {
  3743.   function AACDemuxer(observer, remuxerClass, config) {
  3744.     _classCallCheck(this, AACDemuxer);
  3745.  
  3746.     this.observer = observer;
  3747.     this.remuxerClass = remuxerClass;
  3748.     this.config = config;
  3749.     this.remuxer = new this.remuxerClass(observer, config);
  3750.     this._aacTrack = { container: 'audio/adts', type: 'audio', id: -1, sequenceNumber: 0, samples: [], len: 0 };
  3751.   }
  3752.  
  3753.   _createClass(AACDemuxer, [{
  3754.     key: 'push',
  3755.  
  3756.  
  3757.     // feed incoming data to the front of the parsing pipeline
  3758.     value: function push(data, audioCodec, videoCodec, timeOffset, cc, level, sn, duration) {
  3759.       var track = this._aacTrack,
  3760.           id3 = new _id2.default(data),
  3761.           pts = 90 * id3.timeStamp,
  3762.           config,
  3763.           frameLength,
  3764.           frameDuration,
  3765.           frameIndex,
  3766.           offset,
  3767.           headerLength,
  3768.           stamp,
  3769.           len,
  3770.           aacSample;
  3771.       // look for ADTS header (0xFFFx)
  3772.       for (offset = id3.length, len = data.length; offset < len - 1; offset++) {
  3773.         if (data[offset] === 0xff && (data[offset + 1] & 0xf0) === 0xf0) {
  3774.           break;
  3775.         }
  3776.       }
  3777.  
  3778.       if (!track.audiosamplerate) {
  3779.         config = _adts2.default.getAudioConfig(this.observer, data, offset, audioCodec);
  3780.         track.config = config.config;
  3781.         track.audiosamplerate = config.samplerate;
  3782.         track.channelCount = config.channelCount;
  3783.         track.codec = config.codec;
  3784.         track.duration = duration;
  3785.         _logger.logger.log('parsed codec:' + track.codec + ',rate:' + config.samplerate + ',nb channel:' + config.channelCount);
  3786.       }
  3787.       frameIndex = 0;
  3788.       frameDuration = 1024 * 90000 / track.audiosamplerate;
  3789.       while (offset + 5 < len) {
  3790.         // The protection skip bit tells us if we have 2 bytes of CRC data at the end of the ADTS header
  3791.         headerLength = !!(data[offset + 1] & 0x01) ? 7 : 9;
  3792.         // retrieve frame size
  3793.         frameLength = (data[offset + 3] & 0x03) << 11 | data[offset + 4] << 3 | (data[offset + 5] & 0xE0) >>> 5;
  3794.         frameLength -= headerLength;
  3795.         //stamp = pes.pts;
  3796.  
  3797.         if (frameLength > 0 && offset + headerLength + frameLength <= len) {
  3798.           stamp = pts + frameIndex * frameDuration;
  3799.           //logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}/${(stamp/90).toFixed(0)}`);
  3800.           aacSample = { unit: data.subarray(offset + headerLength, offset + headerLength + frameLength), pts: stamp, dts: stamp };
  3801.           track.samples.push(aacSample);
  3802.           track.len += frameLength;
  3803.           offset += frameLength + headerLength;
  3804.           frameIndex++;
  3805.           // look for ADTS header (0xFFFx)
  3806.           for (; offset < len - 1; offset++) {
  3807.             if (data[offset] === 0xff && (data[offset + 1] & 0xf0) === 0xf0) {
  3808.               break;
  3809.             }
  3810.           }
  3811.         } else {
  3812.           break;
  3813.         }
  3814.       }
  3815.       this.remuxer.remux(this._aacTrack, { samples: [] }, { samples: [{ pts: pts, dts: pts, unit: id3.payload }] }, { samples: [] }, timeOffset);
  3816.     }
  3817.   }, {
  3818.     key: 'destroy',
  3819.     value: function destroy() {}
  3820.   }], [{
  3821.     key: 'probe',
  3822.     value: function probe(data) {
  3823.       // check if data contains ID3 timestamp and ADTS sync worc
  3824.       var id3 = new _id2.default(data),
  3825.           offset,
  3826.           len;
  3827.       if (id3.hasTimeStamp) {
  3828.         // look for ADTS header (0xFFFx)
  3829.         for (offset = id3.length, len = data.length; offset < len - 1; offset++) {
  3830.           if (data[offset] === 0xff && (data[offset + 1] & 0xf0) === 0xf0) {
  3831.             //logger.log('ADTS sync word found !');
  3832.             return true;
  3833.           }
  3834.         }
  3835.       }
  3836.       return false;
  3837.     }
  3838.   }]);
  3839.  
  3840.   return AACDemuxer;
  3841. }();
  3842.  
  3843. exports.default = AACDemuxer;
  3844.  
  3845. },{"../demux/id3":19,"../utils/logger":39,"./adts":14}],14:[function(require,module,exports){
  3846. 'use strict';
  3847.  
  3848. Object.defineProperty(exports, "__esModule", {
  3849.   value: true
  3850. });
  3851.  
  3852. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /**
  3853.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       *  ADTS parser helper
  3854.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       */
  3855.  
  3856.  
  3857. var _logger = require('../utils/logger');
  3858.  
  3859. var _errors = require('../errors');
  3860.  
  3861. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  3862.  
  3863. var ADTS = function () {
  3864.   function ADTS() {
  3865.     _classCallCheck(this, ADTS);
  3866.   }
  3867.  
  3868.   _createClass(ADTS, null, [{
  3869.     key: 'getAudioConfig',
  3870.     value: function getAudioConfig(observer, data, offset, audioCodec) {
  3871.       var adtsObjectType,
  3872.           // :int
  3873.       adtsSampleingIndex,
  3874.           // :int
  3875.       adtsExtensionSampleingIndex,
  3876.           // :int
  3877.       adtsChanelConfig,
  3878.           // :int
  3879.       config,
  3880.           userAgent = navigator.userAgent.toLowerCase(),
  3881.           adtsSampleingRates = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
  3882.       // byte 2
  3883.       adtsObjectType = ((data[offset + 2] & 0xC0) >>> 6) + 1;
  3884.       adtsSampleingIndex = (data[offset + 2] & 0x3C) >>> 2;
  3885.       if (adtsSampleingIndex > adtsSampleingRates.length - 1) {
  3886.         observer.trigger(Event.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.FRAG_PARSING_ERROR, fatal: true, reason: 'invalid ADTS sampling index:' + adtsSampleingIndex });
  3887.         return;
  3888.       }
  3889.       adtsChanelConfig = (data[offset + 2] & 0x01) << 2;
  3890.       // byte 3
  3891.       adtsChanelConfig |= (data[offset + 3] & 0xC0) >>> 6;
  3892.       _logger.logger.log('manifest codec:' + audioCodec + ',ADTS data:type:' + adtsObjectType + ',sampleingIndex:' + adtsSampleingIndex + '[' + adtsSampleingRates[adtsSampleingIndex] + 'Hz],channelConfig:' + adtsChanelConfig);
  3893.       // firefox: freq less than 24kHz = AAC SBR (HE-AAC)
  3894.       if (userAgent.indexOf('firefox') !== -1) {
  3895.         if (adtsSampleingIndex >= 6) {
  3896.           adtsObjectType = 5;
  3897.           config = new Array(4);
  3898.           // HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies
  3899.           // there is a factor 2 between frame sample rate and output sample rate
  3900.           // multiply frequency by 2 (see table below, equivalent to substract 3)
  3901.           adtsExtensionSampleingIndex = adtsSampleingIndex - 3;
  3902.         } else {
  3903.           adtsObjectType = 2;
  3904.           config = new Array(2);
  3905.           adtsExtensionSampleingIndex = adtsSampleingIndex;
  3906.         }
  3907.         // Android : always use AAC
  3908.       } else if (userAgent.indexOf('android') !== -1) {
  3909.           adtsObjectType = 2;
  3910.           config = new Array(2);
  3911.           adtsExtensionSampleingIndex = adtsSampleingIndex;
  3912.         } else {
  3913.           /*  for other browsers (chrome ...)
  3914.               always force audio type to be HE-AAC SBR, as some browsers do not support audio codec switch properly (like Chrome ...)
  3915.           */
  3916.           adtsObjectType = 5;
  3917.           config = new Array(4);
  3918.           // if (manifest codec is HE-AAC or HE-AACv2) OR (manifest codec not specified AND frequency less than 24kHz)
  3919.           if (audioCodec && (audioCodec.indexOf('mp4a.40.29') !== -1 || audioCodec.indexOf('mp4a.40.5') !== -1) || !audioCodec && adtsSampleingIndex >= 6) {
  3920.             // HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies
  3921.             // there is a factor 2 between frame sample rate and output sample rate
  3922.             // multiply frequency by 2 (see table below, equivalent to substract 3)
  3923.             adtsExtensionSampleingIndex = adtsSampleingIndex - 3;
  3924.           } else {
  3925.             // if (manifest codec is AAC) AND (frequency less than 24kHz AND nb channel is 1) OR (manifest codec not specified and mono audio)
  3926.             // Chrome fails to play back with low frequency AAC LC mono when initialized with HE-AAC.  This is not a problem with stereo.
  3927.             if (audioCodec && audioCodec.indexOf('mp4a.40.2') !== -1 && adtsSampleingIndex >= 6 && adtsChanelConfig === 1 || !audioCodec && adtsChanelConfig === 1) {
  3928.               adtsObjectType = 2;
  3929.               config = new Array(2);
  3930.             }
  3931.             adtsExtensionSampleingIndex = adtsSampleingIndex;
  3932.           }
  3933.         }
  3934.       /* refer to http://wiki.multimedia.cx/index.php?title=MPEG-4_Audio#Audio_Specific_Config
  3935.           ISO 14496-3 (AAC).pdf - Table 1.13 — Syntax of AudioSpecificConfig()
  3936.         Audio Profile / Audio Object Type
  3937.         0: Null
  3938.         1: AAC Main
  3939.         2: AAC LC (Low Complexity)
  3940.         3: AAC SSR (Scalable Sample Rate)
  3941.         4: AAC LTP (Long Term Prediction)
  3942.         5: SBR (Spectral Band Replication)
  3943.         6: AAC Scalable
  3944.        sampling freq
  3945.         0: 96000 Hz
  3946.         1: 88200 Hz
  3947.         2: 64000 Hz
  3948.         3: 48000 Hz
  3949.         4: 44100 Hz
  3950.         5: 32000 Hz
  3951.         6: 24000 Hz
  3952.         7: 22050 Hz
  3953.         8: 16000 Hz
  3954.         9: 12000 Hz
  3955.         10: 11025 Hz
  3956.         11: 8000 Hz
  3957.         12: 7350 Hz
  3958.         13: Reserved
  3959.         14: Reserved
  3960.         15: frequency is written explictly
  3961.         Channel Configurations
  3962.         These are the channel configurations:
  3963.         0: Defined in AOT Specifc Config
  3964.         1: 1 channel: front-center
  3965.         2: 2 channels: front-left, front-right
  3966.       */
  3967.       // audioObjectType = profile => profile, the MPEG-4 Audio Object Type minus 1
  3968.       config[0] = adtsObjectType << 3;
  3969.       // samplingFrequencyIndex
  3970.       config[0] |= (adtsSampleingIndex & 0x0E) >> 1;
  3971.       config[1] |= (adtsSampleingIndex & 0x01) << 7;
  3972.       // channelConfiguration
  3973.       config[1] |= adtsChanelConfig << 3;
  3974.       if (adtsObjectType === 5) {
  3975.         // adtsExtensionSampleingIndex
  3976.         config[1] |= (adtsExtensionSampleingIndex & 0x0E) >> 1;
  3977.         config[2] = (adtsExtensionSampleingIndex & 0x01) << 7;
  3978.         // adtsObjectType (force to 2, chrome is checking that object type is less than 5 ???
  3979.         //    https://chromium.googlesource.com/chromium/src.git/+/master/media/formats/mp4/aac.cc
  3980.         config[2] |= 2 << 2;
  3981.         config[3] = 0;
  3982.       }
  3983.       return { config: config, samplerate: adtsSampleingRates[adtsSampleingIndex], channelCount: adtsChanelConfig, codec: 'mp4a.40.' + adtsObjectType };
  3984.     }
  3985.   }]);
  3986.  
  3987.   return ADTS;
  3988. }();
  3989.  
  3990. exports.default = ADTS;
  3991.  
  3992. },{"../errors":21,"../utils/logger":39}],15:[function(require,module,exports){
  3993. 'use strict';
  3994.  
  3995. Object.defineProperty(exports, "__esModule", {
  3996.   value: true
  3997. });
  3998.  
  3999. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /*  inline demuxer.
  4000.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       *   probe fragments and instantiate appropriate demuxer depending on content type (TSDemuxer, AACDemuxer, ...)
  4001.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       */
  4002.  
  4003. var _events = require('../events');
  4004.  
  4005. var _events2 = _interopRequireDefault(_events);
  4006.  
  4007. var _errors = require('../errors');
  4008.  
  4009. var _aacdemuxer = require('../demux/aacdemuxer');
  4010.  
  4011. var _aacdemuxer2 = _interopRequireDefault(_aacdemuxer);
  4012.  
  4013. var _tsdemuxer = require('../demux/tsdemuxer');
  4014.  
  4015. var _tsdemuxer2 = _interopRequireDefault(_tsdemuxer);
  4016.  
  4017. var _mp4Remuxer = require('../remux/mp4-remuxer');
  4018.  
  4019. var _mp4Remuxer2 = _interopRequireDefault(_mp4Remuxer);
  4020.  
  4021. var _passthroughRemuxer = require('../remux/passthrough-remuxer');
  4022.  
  4023. var _passthroughRemuxer2 = _interopRequireDefault(_passthroughRemuxer);
  4024.  
  4025. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  4026.  
  4027. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  4028.  
  4029. var DemuxerInline = function () {
  4030.   function DemuxerInline(hls, typeSupported) {
  4031.     var config = arguments.length <= 2 || arguments[2] === undefined ? null : arguments[2];
  4032.  
  4033.     _classCallCheck(this, DemuxerInline);
  4034.  
  4035.     this.hls = hls;
  4036.     this.config = this.hls.config || config;
  4037.     this.typeSupported = typeSupported;
  4038.   }
  4039.  
  4040.   _createClass(DemuxerInline, [{
  4041.     key: 'destroy',
  4042.     value: function destroy() {
  4043.       var demuxer = this.demuxer;
  4044.       if (demuxer) {
  4045.         demuxer.destroy();
  4046.       }
  4047.     }
  4048.   }, {
  4049.     key: 'push',
  4050.     value: function push(data, audioCodec, videoCodec, timeOffset, cc, level, sn, duration) {
  4051.       var demuxer = this.demuxer;
  4052.       if (!demuxer) {
  4053.         var hls = this.hls;
  4054.         // probe for content type
  4055.         if (_tsdemuxer2.default.probe(data)) {
  4056.           if (this.typeSupported.mp2t === true) {
  4057.             demuxer = new _tsdemuxer2.default(hls, _passthroughRemuxer2.default, this.config);
  4058.           } else {
  4059.             demuxer = new _tsdemuxer2.default(hls, _mp4Remuxer2.default, this.config);
  4060.           }
  4061.         } else if (_aacdemuxer2.default.probe(data)) {
  4062.           demuxer = new _aacdemuxer2.default(hls, _mp4Remuxer2.default, this.config);
  4063.         } else {
  4064.           hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.FRAG_PARSING_ERROR, fatal: true, reason: 'no demux matching with content found' });
  4065.           return;
  4066.         }
  4067.         this.demuxer = demuxer;
  4068.       }
  4069.       demuxer.push(data, audioCodec, videoCodec, timeOffset, cc, level, sn, duration);
  4070.     }
  4071.   }]);
  4072.  
  4073.   return DemuxerInline;
  4074. }();
  4075.  
  4076. exports.default = DemuxerInline;
  4077.  
  4078. },{"../demux/aacdemuxer":13,"../demux/tsdemuxer":20,"../errors":21,"../events":23,"../remux/mp4-remuxer":33,"../remux/passthrough-remuxer":34}],16:[function(require,module,exports){
  4079. 'use strict';
  4080.  
  4081. Object.defineProperty(exports, "__esModule", {
  4082.   value: true
  4083. });
  4084.  
  4085. var _demuxerInline = require('../demux/demuxer-inline');
  4086.  
  4087. var _demuxerInline2 = _interopRequireDefault(_demuxerInline);
  4088.  
  4089. var _events = require('../events');
  4090.  
  4091. var _events2 = _interopRequireDefault(_events);
  4092.  
  4093. var _events3 = require('events');
  4094.  
  4095. var _events4 = _interopRequireDefault(_events3);
  4096.  
  4097. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  4098.  
  4099. var DemuxerWorker = function DemuxerWorker(self) {
  4100.   // observer setup
  4101.   var observer = new _events4.default();
  4102.   observer.trigger = function trigger(event) {
  4103.     for (var _len = arguments.length, data = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  4104.       data[_key - 1] = arguments[_key];
  4105.     }
  4106.  
  4107.     observer.emit.apply(observer, [event, event].concat(data));
  4108.   };
  4109.  
  4110.   observer.off = function off(event) {
  4111.     for (var _len2 = arguments.length, data = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
  4112.       data[_key2 - 1] = arguments[_key2];
  4113.     }
  4114.  
  4115.     observer.removeListener.apply(observer, [event].concat(data));
  4116.   };
  4117.   self.addEventListener('message', function (ev) {
  4118.     var data = ev.data;
  4119.     //console.log('demuxer cmd:' + data.cmd);
  4120.     switch (data.cmd) {
  4121.       case 'init':
  4122.         self.demuxer = new _demuxerInline2.default(observer, data.typeSupported, JSON.parse(data.config));
  4123.         break;
  4124.       case 'demux':
  4125.         self.demuxer.push(new Uint8Array(data.data), data.audioCodec, data.videoCodec, data.timeOffset, data.cc, data.level, data.sn, data.duration);
  4126.         break;
  4127.       default:
  4128.         break;
  4129.     }
  4130.   });
  4131.  
  4132.   // listen to events triggered by Demuxer
  4133.   observer.on(_events2.default.FRAG_PARSING_INIT_SEGMENT, function (ev, data) {
  4134.     self.postMessage({ event: ev, tracks: data.tracks, unique: data.unique });
  4135.   });
  4136.  
  4137.   observer.on(_events2.default.FRAG_PARSING_DATA, function (ev, data) {
  4138.     var objData = { event: ev, type: data.type, startPTS: data.startPTS, endPTS: data.endPTS, startDTS: data.startDTS, endDTS: data.endDTS, data1: data.data1.buffer, data2: data.data2.buffer, nb: data.nb };
  4139.     // pass data1/data2 as transferable object (no copy)
  4140.     self.postMessage(objData, [objData.data1, objData.data2]);
  4141.   });
  4142.  
  4143.   observer.on(_events2.default.FRAG_PARSED, function (event) {
  4144.     self.postMessage({ event: event });
  4145.   });
  4146.  
  4147.   observer.on(_events2.default.ERROR, function (event, data) {
  4148.     self.postMessage({ event: event, data: data });
  4149.   });
  4150.  
  4151.   observer.on(_events2.default.FRAG_PARSING_METADATA, function (event, data) {
  4152.     var objData = { event: event, samples: data.samples };
  4153.     self.postMessage(objData);
  4154.   });
  4155.  
  4156.   observer.on(_events2.default.FRAG_PARSING_USERDATA, function (event, data) {
  4157.     var objData = { event: event, samples: data.samples };
  4158.     self.postMessage(objData);
  4159.   });
  4160. }; /* demuxer web worker.
  4161.     *  - listen to worker message, and trigger DemuxerInline upon reception of Fragments.
  4162.     *  - 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.
  4163.     */
  4164.  
  4165. exports.default = DemuxerWorker;
  4166.  
  4167. },{"../demux/demuxer-inline":15,"../events":23,"events":1}],17:[function(require,module,exports){
  4168. 'use strict';
  4169.  
  4170. Object.defineProperty(exports, "__esModule", {
  4171.   value: true
  4172. });
  4173.  
  4174. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  4175.  
  4176. var _events = require('../events');
  4177.  
  4178. var _events2 = _interopRequireDefault(_events);
  4179.  
  4180. var _demuxerInline = require('../demux/demuxer-inline');
  4181.  
  4182. var _demuxerInline2 = _interopRequireDefault(_demuxerInline);
  4183.  
  4184. var _demuxerWorker = require('../demux/demuxer-worker');
  4185.  
  4186. var _demuxerWorker2 = _interopRequireDefault(_demuxerWorker);
  4187.  
  4188. var _logger = require('../utils/logger');
  4189.  
  4190. var _decrypter = require('../crypt/decrypter');
  4191.  
  4192. var _decrypter2 = _interopRequireDefault(_decrypter);
  4193.  
  4194. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  4195.  
  4196. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  4197.  
  4198. var Demuxer = function () {
  4199.   function Demuxer(hls) {
  4200.     _classCallCheck(this, Demuxer);
  4201.  
  4202.     this.hls = hls;
  4203.     var typeSupported = {
  4204.       mp4: MediaSource.isTypeSupported('video/mp4'),
  4205.       mp2t: hls.config.enableMP2TPassThrough && MediaSource.isTypeSupported('video/mp2t')
  4206.     };
  4207.     if (hls.config.enableWorker && typeof Worker !== 'undefined') {
  4208.       _logger.logger.log('demuxing in webworker');
  4209.       try {
  4210.         var work = require('webworkify');
  4211.         this.w = work(_demuxerWorker2.default);
  4212.         this.onwmsg = this.onWorkerMessage.bind(this);
  4213.         this.w.addEventListener('message', this.onwmsg);
  4214.         this.w.postMessage({ cmd: 'init', typeSupported: typeSupported, config: JSON.stringify(hls.config) });
  4215.       } catch (err) {
  4216.         _logger.logger.error('error while initializing DemuxerWorker, fallback on DemuxerInline');
  4217.         this.demuxer = new _demuxerInline2.default(hls, typeSupported);
  4218.       }
  4219.     } else {
  4220.       this.demuxer = new _demuxerInline2.default(hls, typeSupported);
  4221.     }
  4222.     this.demuxInitialized = true;
  4223.   }
  4224.  
  4225.   _createClass(Demuxer, [{
  4226.     key: 'destroy',
  4227.     value: function destroy() {
  4228.       if (this.w) {
  4229.         this.w.removeEventListener('message', this.onwmsg);
  4230.         this.w.terminate();
  4231.         this.w = null;
  4232.       } else {
  4233.         this.demuxer.destroy();
  4234.         this.demuxer = null;
  4235.       }
  4236.       if (this.decrypter) {
  4237.         this.decrypter.destroy();
  4238.         this.decrypter = null;
  4239.       }
  4240.     }
  4241.   }, {
  4242.     key: 'pushDecrypted',
  4243.     value: function pushDecrypted(data, audioCodec, videoCodec, timeOffset, cc, level, sn, duration) {
  4244.       if (this.w) {
  4245.         // post fragment payload as transferable objects (no copy)
  4246.         this.w.postMessage({ cmd: 'demux', data: data, audioCodec: audioCodec, videoCodec: videoCodec, timeOffset: timeOffset, cc: cc, level: level, sn: sn, duration: duration }, [data]);
  4247.       } else {
  4248.         this.demuxer.push(new Uint8Array(data), audioCodec, videoCodec, timeOffset, cc, level, sn, duration);
  4249.       }
  4250.     }
  4251.   }, {
  4252.     key: 'push',
  4253.     value: function push(data, audioCodec, videoCodec, timeOffset, cc, level, sn, duration, decryptdata) {
  4254.       if (data.byteLength > 0 && decryptdata != null && decryptdata.key != null && decryptdata.method === 'AES-128') {
  4255.         if (this.decrypter == null) {
  4256.           this.decrypter = new _decrypter2.default(this.hls);
  4257.         }
  4258.  
  4259.         var localthis = this;
  4260.         this.decrypter.decrypt(data, decryptdata.key, decryptdata.iv, function (decryptedData) {
  4261.           localthis.pushDecrypted(decryptedData, audioCodec, videoCodec, timeOffset, cc, level, sn, duration);
  4262.         });
  4263.       } else {
  4264.         this.pushDecrypted(data, audioCodec, videoCodec, timeOffset, cc, level, sn, duration);
  4265.       }
  4266.     }
  4267.   }, {
  4268.     key: 'onWorkerMessage',
  4269.     value: function onWorkerMessage(ev) {
  4270.       var data = ev.data;
  4271.       //console.log('onWorkerMessage:' + data.event);
  4272.       switch (data.event) {
  4273.         case _events2.default.FRAG_PARSING_INIT_SEGMENT:
  4274.           var obj = {};
  4275.           obj.tracks = data.tracks;
  4276.           obj.unique = data.unique;
  4277.           this.hls.trigger(_events2.default.FRAG_PARSING_INIT_SEGMENT, obj);
  4278.           break;
  4279.         case _events2.default.FRAG_PARSING_DATA:
  4280.           this.hls.trigger(_events2.default.FRAG_PARSING_DATA, {
  4281.             data1: new Uint8Array(data.data1),
  4282.             data2: new Uint8Array(data.data2),
  4283.             startPTS: data.startPTS,
  4284.             endPTS: data.endPTS,
  4285.             startDTS: data.startDTS,
  4286.             endDTS: data.endDTS,
  4287.             type: data.type,
  4288.             nb: data.nb
  4289.           });
  4290.           break;
  4291.         case _events2.default.FRAG_PARSING_METADATA:
  4292.           this.hls.trigger(_events2.default.FRAG_PARSING_METADATA, {
  4293.             samples: data.samples
  4294.           });
  4295.           break;
  4296.         case _events2.default.FRAG_PARSING_USERDATA:
  4297.           this.hls.trigger(_events2.default.FRAG_PARSING_USERDATA, {
  4298.             samples: data.samples
  4299.           });
  4300.           break;
  4301.         default:
  4302.           this.hls.trigger(data.event, data.data);
  4303.           break;
  4304.       }
  4305.     }
  4306.   }]);
  4307.  
  4308.   return Demuxer;
  4309. }();
  4310.  
  4311. exports.default = Demuxer;
  4312.  
  4313. },{"../crypt/decrypter":12,"../demux/demuxer-inline":15,"../demux/demuxer-worker":16,"../events":23,"../utils/logger":39,"webworkify":2}],18:[function(require,module,exports){
  4314. 'use strict';
  4315.  
  4316. Object.defineProperty(exports, "__esModule", {
  4317.   value: true
  4318. });
  4319.  
  4320. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /**
  4321.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       * Parser for exponential Golomb codes, a variable-bitwidth number encoding scheme used by h264.
  4322.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      */
  4323.  
  4324. var _logger = require('../utils/logger');
  4325.  
  4326. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  4327.  
  4328. var ExpGolomb = function () {
  4329.   function ExpGolomb(data) {
  4330.     _classCallCheck(this, ExpGolomb);
  4331.  
  4332.     this.data = data;
  4333.     // the number of bytes left to examine in this.data
  4334.     this.bytesAvailable = this.data.byteLength;
  4335.     // the current word being examined
  4336.     this.word = 0; // :uint
  4337.     // the number of bits left to examine in the current word
  4338.     this.bitsAvailable = 0; // :uint
  4339.   }
  4340.  
  4341.   // ():void
  4342.  
  4343.  
  4344.   _createClass(ExpGolomb, [{
  4345.     key: 'loadWord',
  4346.     value: function loadWord() {
  4347.       var position = this.data.byteLength - this.bytesAvailable,
  4348.           workingBytes = new Uint8Array(4),
  4349.           availableBytes = Math.min(4, this.bytesAvailable);
  4350.       if (availableBytes === 0) {
  4351.         throw new Error('no bytes available');
  4352.       }
  4353.       workingBytes.set(this.data.subarray(position, position + availableBytes));
  4354.       this.word = new DataView(workingBytes.buffer).getUint32(0);
  4355.       // track the amount of this.data that has been processed
  4356.       this.bitsAvailable = availableBytes * 8;
  4357.       this.bytesAvailable -= availableBytes;
  4358.     }
  4359.  
  4360.     // (count:int):void
  4361.  
  4362.   }, {
  4363.     key: 'skipBits',
  4364.     value: function skipBits(count) {
  4365.       var skipBytes; // :int
  4366.       if (this.bitsAvailable > count) {
  4367.         this.word <<= count;
  4368.         this.bitsAvailable -= count;
  4369.       } else {
  4370.         count -= this.bitsAvailable;
  4371.         skipBytes = count >> 3;
  4372.         count -= skipBytes >> 3;
  4373.         this.bytesAvailable -= skipBytes;
  4374.         this.loadWord();
  4375.         this.word <<= count;
  4376.         this.bitsAvailable -= count;
  4377.       }
  4378.     }
  4379.  
  4380.     // (size:int):uint
  4381.  
  4382.   }, {
  4383.     key: 'readBits',
  4384.     value: function readBits(size) {
  4385.       var bits = Math.min(this.bitsAvailable, size),
  4386.           // :uint
  4387.       valu = this.word >>> 32 - bits; // :uint
  4388.       if (size > 32) {
  4389.         _logger.logger.error('Cannot read more than 32 bits at a time');
  4390.       }
  4391.       this.bitsAvailable -= bits;
  4392.       if (this.bitsAvailable > 0) {
  4393.         this.word <<= bits;
  4394.       } else if (this.bytesAvailable > 0) {
  4395.         this.loadWord();
  4396.       }
  4397.       bits = size - bits;
  4398.       if (bits > 0) {
  4399.         return valu << bits | this.readBits(bits);
  4400.       } else {
  4401.         return valu;
  4402.       }
  4403.     }
  4404.  
  4405.     // ():uint
  4406.  
  4407.   }, {
  4408.     key: 'skipLZ',
  4409.     value: function skipLZ() {
  4410.       var leadingZeroCount; // :uint
  4411.       for (leadingZeroCount = 0; leadingZeroCount < this.bitsAvailable; ++leadingZeroCount) {
  4412.         if (0 !== (this.word & 0x80000000 >>> leadingZeroCount)) {
  4413.           // the first bit of working word is 1
  4414.           this.word <<= leadingZeroCount;
  4415.           this.bitsAvailable -= leadingZeroCount;
  4416.           return leadingZeroCount;
  4417.         }
  4418.       }
  4419.       // we exhausted word and still have not found a 1
  4420.       this.loadWord();
  4421.       return leadingZeroCount + this.skipLZ();
  4422.     }
  4423.  
  4424.     // ():void
  4425.  
  4426.   }, {
  4427.     key: 'skipUEG',
  4428.     value: function skipUEG() {
  4429.       this.skipBits(1 + this.skipLZ());
  4430.     }
  4431.  
  4432.     // ():void
  4433.  
  4434.   }, {
  4435.     key: 'skipEG',
  4436.     value: function skipEG() {
  4437.       this.skipBits(1 + this.skipLZ());
  4438.     }
  4439.  
  4440.     // ():uint
  4441.  
  4442.   }, {
  4443.     key: 'readUEG',
  4444.     value: function readUEG() {
  4445.       var clz = this.skipLZ(); // :uint
  4446.       return this.readBits(clz + 1) - 1;
  4447.     }
  4448.  
  4449.     // ():int
  4450.  
  4451.   }, {
  4452.     key: 'readEG',
  4453.     value: function readEG() {
  4454.       var valu = this.readUEG(); // :int
  4455.       if (0x01 & valu) {
  4456.         // the number is odd if the low order bit is set
  4457.         return 1 + valu >>> 1; // add 1 to make it even, and divide by 2
  4458.       } else {
  4459.           return -1 * (valu >>> 1); // divide by two then make it negative
  4460.         }
  4461.     }
  4462.  
  4463.     // Some convenience functions
  4464.     // :Boolean
  4465.  
  4466.   }, {
  4467.     key: 'readBoolean',
  4468.     value: function readBoolean() {
  4469.       return 1 === this.readBits(1);
  4470.     }
  4471.  
  4472.     // ():int
  4473.  
  4474.   }, {
  4475.     key: 'readUByte',
  4476.     value: function readUByte() {
  4477.       return this.readBits(8);
  4478.     }
  4479.  
  4480.     // ():int
  4481.  
  4482.   }, {
  4483.     key: 'readUShort',
  4484.     value: function readUShort() {
  4485.       return this.readBits(16);
  4486.     }
  4487.     // ():int
  4488.  
  4489.   }, {
  4490.     key: 'readUInt',
  4491.     value: function readUInt() {
  4492.       return this.readBits(32);
  4493.     }
  4494.  
  4495.     /**
  4496.      * Advance the ExpGolomb decoder past a scaling list. The scaling
  4497.      * list is optionally transmitted as part of a sequence parameter
  4498.      * set and is not relevant to transmuxing.
  4499.      * @param count {number} the number of entries in this scaling list
  4500.      * @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1
  4501.      */
  4502.  
  4503.   }, {
  4504.     key: 'skipScalingList',
  4505.     value: function skipScalingList(count) {
  4506.       var lastScale = 8,
  4507.           nextScale = 8,
  4508.           j,
  4509.           deltaScale;
  4510.       for (j = 0; j < count; j++) {
  4511.         if (nextScale !== 0) {
  4512.           deltaScale = this.readEG();
  4513.           nextScale = (lastScale + deltaScale + 256) % 256;
  4514.         }
  4515.         lastScale = nextScale === 0 ? lastScale : nextScale;
  4516.       }
  4517.     }
  4518.  
  4519.     /**
  4520.      * Read a sequence parameter set and return some interesting video
  4521.      * properties. A sequence parameter set is the H264 metadata that
  4522.      * describes the properties of upcoming video frames.
  4523.      * @param data {Uint8Array} the bytes of a sequence parameter set
  4524.      * @return {object} an object with configuration parsed from the
  4525.      * sequence parameter set, including the dimensions of the
  4526.      * associated video frames.
  4527.      */
  4528.  
  4529.   }, {
  4530.     key: 'readSPS',
  4531.     value: function readSPS() {
  4532.       var frameCropLeftOffset = 0,
  4533.           frameCropRightOffset = 0,
  4534.           frameCropTopOffset = 0,
  4535.           frameCropBottomOffset = 0,
  4536.           sarScale = 1,
  4537.           profileIdc,
  4538.           profileCompat,
  4539.           levelIdc,
  4540.           numRefFramesInPicOrderCntCycle,
  4541.           picWidthInMbsMinus1,
  4542.           picHeightInMapUnitsMinus1,
  4543.           frameMbsOnlyFlag,
  4544.           scalingListCount,
  4545.           i;
  4546.       this.readUByte();
  4547.       profileIdc = this.readUByte(); // profile_idc
  4548.       profileCompat = this.readBits(5); // constraint_set[0-4]_flag, u(5)
  4549.       this.skipBits(3); // reserved_zero_3bits u(3),
  4550.       levelIdc = this.readUByte(); //level_idc u(8)
  4551.       this.skipUEG(); // seq_parameter_set_id
  4552.       // some profiles have more optional data we don't need
  4553.       if (profileIdc === 100 || profileIdc === 110 || profileIdc === 122 || profileIdc === 244 || profileIdc === 44 || profileIdc === 83 || profileIdc === 86 || profileIdc === 118 || profileIdc === 128) {
  4554.         var chromaFormatIdc = this.readUEG();
  4555.         if (chromaFormatIdc === 3) {
  4556.           this.skipBits(1); // separate_colour_plane_flag
  4557.         }
  4558.         this.skipUEG(); // bit_depth_luma_minus8
  4559.         this.skipUEG(); // bit_depth_chroma_minus8
  4560.         this.skipBits(1); // qpprime_y_zero_transform_bypass_flag
  4561.         if (this.readBoolean()) {
  4562.           // seq_scaling_matrix_present_flag
  4563.           scalingListCount = chromaFormatIdc !== 3 ? 8 : 12;
  4564.           for (i = 0; i < scalingListCount; i++) {
  4565.             if (this.readBoolean()) {
  4566.               // seq_scaling_list_present_flag[ i ]
  4567.               if (i < 6) {
  4568.                 this.skipScalingList(16);
  4569.               } else {
  4570.                 this.skipScalingList(64);
  4571.               }
  4572.             }
  4573.           }
  4574.         }
  4575.       }
  4576.       this.skipUEG(); // log2_max_frame_num_minus4
  4577.       var picOrderCntType = this.readUEG();
  4578.       if (picOrderCntType === 0) {
  4579.         this.readUEG(); //log2_max_pic_order_cnt_lsb_minus4
  4580.       } else if (picOrderCntType === 1) {
  4581.           this.skipBits(1); // delta_pic_order_always_zero_flag
  4582.           this.skipEG(); // offset_for_non_ref_pic
  4583.           this.skipEG(); // offset_for_top_to_bottom_field
  4584.           numRefFramesInPicOrderCntCycle = this.readUEG();
  4585.           for (i = 0; i < numRefFramesInPicOrderCntCycle; i++) {
  4586.             this.skipEG(); // offset_for_ref_frame[ i ]
  4587.           }
  4588.         }
  4589.       this.skipUEG(); // max_num_ref_frames
  4590.       this.skipBits(1); // gaps_in_frame_num_value_allowed_flag
  4591.       picWidthInMbsMinus1 = this.readUEG();
  4592.       picHeightInMapUnitsMinus1 = this.readUEG();
  4593.       frameMbsOnlyFlag = this.readBits(1);
  4594.       if (frameMbsOnlyFlag === 0) {
  4595.         this.skipBits(1); // mb_adaptive_frame_field_flag
  4596.       }
  4597.       this.skipBits(1); // direct_8x8_inference_flag
  4598.       if (this.readBoolean()) {
  4599.         // frame_cropping_flag
  4600.         frameCropLeftOffset = this.readUEG();
  4601.         frameCropRightOffset = this.readUEG();
  4602.         frameCropTopOffset = this.readUEG();
  4603.         frameCropBottomOffset = this.readUEG();
  4604.       }
  4605.       if (this.readBoolean()) {
  4606.         // vui_parameters_present_flag
  4607.         if (this.readBoolean()) {
  4608.           // aspect_ratio_info_present_flag
  4609.           var sarRatio = void 0;
  4610.           var aspectRatioIdc = this.readUByte();
  4611.           switch (aspectRatioIdc) {
  4612.             case 1:
  4613.               sarRatio = [1, 1];break;
  4614.             case 2:
  4615.               sarRatio = [12, 11];break;
  4616.             case 3:
  4617.               sarRatio = [10, 11];break;
  4618.             case 4:
  4619.               sarRatio = [16, 11];break;
  4620.             case 5:
  4621.               sarRatio = [40, 33];break;
  4622.             case 6:
  4623.               sarRatio = [24, 11];break;
  4624.             case 7:
  4625.               sarRatio = [20, 11];break;
  4626.             case 8:
  4627.               sarRatio = [32, 11];break;
  4628.             case 9:
  4629.               sarRatio = [80, 33];break;
  4630.             case 10:
  4631.               sarRatio = [18, 11];break;
  4632.             case 11:
  4633.               sarRatio = [15, 11];break;
  4634.             case 12:
  4635.               sarRatio = [64, 33];break;
  4636.             case 13:
  4637.               sarRatio = [160, 99];break;
  4638.             case 14:
  4639.               sarRatio = [4, 3];break;
  4640.             case 15:
  4641.               sarRatio = [3, 2];break;
  4642.             case 16:
  4643.               sarRatio = [2, 1];break;
  4644.             case 255:
  4645.               {
  4646.                 sarRatio = [this.readUByte() << 8 | this.readUByte(), this.readUByte() << 8 | this.readUByte()];
  4647.                 break;
  4648.               }
  4649.           }
  4650.           if (sarRatio) {
  4651.             sarScale = sarRatio[0] / sarRatio[1];
  4652.           }
  4653.         }
  4654.       }
  4655.       return {
  4656.         width: Math.ceil(((picWidthInMbsMinus1 + 1) * 16 - frameCropLeftOffset * 2 - frameCropRightOffset * 2) * sarScale),
  4657.         height: (2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16 - (frameMbsOnlyFlag ? 2 : 4) * (frameCropTopOffset + frameCropBottomOffset)
  4658.       };
  4659.     }
  4660.   }, {
  4661.     key: 'readSliceType',
  4662.     value: function readSliceType() {
  4663.       // skip NALu type
  4664.       this.readUByte();
  4665.       // discard first_mb_in_slice
  4666.       this.readUEG();
  4667.       // return slice_type
  4668.       return this.readUEG();
  4669.     }
  4670.   }]);
  4671.  
  4672.   return ExpGolomb;
  4673. }();
  4674.  
  4675. exports.default = ExpGolomb;
  4676.  
  4677. },{"../utils/logger":39}],19:[function(require,module,exports){
  4678. 'use strict';
  4679.  
  4680. Object.defineProperty(exports, "__esModule", {
  4681.   value: true
  4682. });
  4683.  
  4684. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /**
  4685.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       * ID3 parser
  4686.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       */
  4687.  
  4688.  
  4689. var _logger = require('../utils/logger');
  4690.  
  4691. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  4692.  
  4693. //import Hex from '../utils/hex';
  4694.  
  4695. var ID3 = function () {
  4696.   function ID3(data) {
  4697.     _classCallCheck(this, ID3);
  4698.  
  4699.     this._hasTimeStamp = false;
  4700.     var offset = 0,
  4701.         byte1,
  4702.         byte2,
  4703.         byte3,
  4704.         byte4,
  4705.         tagSize,
  4706.         endPos,
  4707.         header,
  4708.         len;
  4709.     do {
  4710.       header = this.readUTF(data, offset, 3);
  4711.       offset += 3;
  4712.       // first check for ID3 header
  4713.       if (header === 'ID3') {
  4714.         // skip 24 bits
  4715.         offset += 3;
  4716.         // retrieve tag(s) length
  4717.         byte1 = data[offset++] & 0x7f;
  4718.         byte2 = data[offset++] & 0x7f;
  4719.         byte3 = data[offset++] & 0x7f;
  4720.         byte4 = data[offset++] & 0x7f;
  4721.         tagSize = (byte1 << 21) + (byte2 << 14) + (byte3 << 7) + byte4;
  4722.         endPos = offset + tagSize;
  4723.         //logger.log(`ID3 tag found, size/end: ${tagSize}/${endPos}`);
  4724.  
  4725.         // read ID3 tags
  4726.         this._parseID3Frames(data, offset, endPos);
  4727.         offset = endPos;
  4728.       } else if (header === '3DI') {
  4729.         // http://id3.org/id3v2.4.0-structure chapter 3.4.   ID3v2 footer
  4730.         offset += 7;
  4731.         _logger.logger.log('3DI footer found, end: ' + offset);
  4732.       } else {
  4733.         offset -= 3;
  4734.         len = offset;
  4735.         if (len) {
  4736.           //logger.log(`ID3 len: ${len}`);
  4737.           if (!this.hasTimeStamp) {
  4738.             _logger.logger.warn('ID3 tag found, but no timestamp');
  4739.           }
  4740.           this._length = len;
  4741.           this._payload = data.subarray(0, len);
  4742.         }
  4743.         return;
  4744.       }
  4745.     } while (true);
  4746.   }
  4747.  
  4748.   _createClass(ID3, [{
  4749.     key: 'readUTF',
  4750.     value: function readUTF(data, start, len) {
  4751.  
  4752.       var result = '',
  4753.           offset = start,
  4754.           end = start + len;
  4755.       do {
  4756.         result += String.fromCharCode(data[offset++]);
  4757.       } while (offset < end);
  4758.       return result;
  4759.     }
  4760.   }, {
  4761.     key: '_parseID3Frames',
  4762.     value: function _parseID3Frames(data, offset, endPos) {
  4763.       var tagId, tagLen, tagStart, tagFlags, timestamp;
  4764.       while (offset + 8 <= endPos) {
  4765.         tagId = this.readUTF(data, offset, 4);
  4766.         offset += 4;
  4767.  
  4768.         tagLen = data[offset++] << 24 + data[offset++] << 16 + data[offset++] << 8 + data[offset++];
  4769.  
  4770.         tagFlags = data[offset++] << 8 + data[offset++];
  4771.  
  4772.         tagStart = offset;
  4773.         //logger.log("ID3 tag id:" + tagId);
  4774.         switch (tagId) {
  4775.           case 'PRIV':
  4776.             //logger.log('parse frame:' + Hex.hexDump(data.subarray(offset,endPos)));
  4777.             // owner should be "com.apple.streaming.transportStreamTimestamp"
  4778.             if (this.readUTF(data, offset, 44) === 'com.apple.streaming.transportStreamTimestamp') {
  4779.               offset += 44;
  4780.               // smelling even better ! we found the right descriptor
  4781.               // skip null character (string end) + 3 first bytes
  4782.               offset += 4;
  4783.  
  4784.               // timestamp is 33 bit expressed as a big-endian eight-octet number, with the upper 31 bits set to zero.
  4785.               var pts33Bit = data[offset++] & 0x1;
  4786.               this._hasTimeStamp = true;
  4787.  
  4788.               timestamp = ((data[offset++] << 23) + (data[offset++] << 15) + (data[offset++] << 7) + data[offset++]) / 45;
  4789.  
  4790.               if (pts33Bit) {
  4791.                 timestamp += 47721858.84; // 2^32 / 90
  4792.               }
  4793.               timestamp = Math.round(timestamp);
  4794.               _logger.logger.trace('ID3 timestamp found: ' + timestamp);
  4795.               this._timeStamp = timestamp;
  4796.             }
  4797.             break;
  4798.           default:
  4799.             break;
  4800.         }
  4801.       }
  4802.     }
  4803.   }, {
  4804.     key: 'hasTimeStamp',
  4805.     get: function get() {
  4806.       return this._hasTimeStamp;
  4807.     }
  4808.   }, {
  4809.     key: 'timeStamp',
  4810.     get: function get() {
  4811.       return this._timeStamp;
  4812.     }
  4813.   }, {
  4814.     key: 'length',
  4815.     get: function get() {
  4816.       return this._length;
  4817.     }
  4818.   }, {
  4819.     key: 'payload',
  4820.     get: function get() {
  4821.       return this._payload;
  4822.     }
  4823.   }]);
  4824.  
  4825.   return ID3;
  4826. }();
  4827.  
  4828. exports.default = ID3;
  4829.  
  4830. },{"../utils/logger":39}],20:[function(require,module,exports){
  4831. 'use strict';
  4832.  
  4833. Object.defineProperty(exports, "__esModule", {
  4834.   value: true
  4835. });
  4836.  
  4837. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /**
  4838.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       * highly optimized TS demuxer:
  4839.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       * parse PAT, PMT
  4840.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       * extract PES packet from audio and video PIDs
  4841.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       * extract AVC/H264 NAL units and AAC/ADTS samples from PES packet
  4842.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       * trigger the remuxer upon parsing completion
  4843.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       * 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.
  4844.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       * it also controls the remuxing process :
  4845.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       * upon discontinuity or level switch detection, it will also notifies the remuxer so that it can reset its state.
  4846.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      */
  4847.  
  4848. // import Hex from '../utils/hex';
  4849.  
  4850.  
  4851. var _adts = require('./adts');
  4852.  
  4853. var _adts2 = _interopRequireDefault(_adts);
  4854.  
  4855. var _events = require('../events');
  4856.  
  4857. var _events2 = _interopRequireDefault(_events);
  4858.  
  4859. var _expGolomb = require('./exp-golomb');
  4860.  
  4861. var _expGolomb2 = _interopRequireDefault(_expGolomb);
  4862.  
  4863. var _logger = require('../utils/logger');
  4864.  
  4865. var _errors = require('../errors');
  4866.  
  4867. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  4868.  
  4869. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  4870.  
  4871. var TSDemuxer = function () {
  4872.   function TSDemuxer(observer, remuxerClass, config) {
  4873.     _classCallCheck(this, TSDemuxer);
  4874.  
  4875.     this.observer = observer;
  4876.     this.remuxerClass = remuxerClass;
  4877.     this.config = config;
  4878.     this.lastCC = 0;
  4879.     this.remuxer = new this.remuxerClass(observer, config);
  4880.   }
  4881.  
  4882.   _createClass(TSDemuxer, [{
  4883.     key: 'switchLevel',
  4884.     value: function switchLevel() {
  4885.       this.pmtParsed = false;
  4886.       this._pmtId = -1;
  4887.       this.lastAacPTS = null;
  4888.       this.aacOverFlow = null;
  4889.       this._avcTrack = { container: 'video/mp2t', type: 'video', id: -1, sequenceNumber: 0, samples: [], len: 0, nbNalu: 0 };
  4890.       this._aacTrack = { container: 'video/mp2t', type: 'audio', id: -1, sequenceNumber: 0, samples: [], len: 0 };
  4891.       this._id3Track = { type: 'id3', id: -1, sequenceNumber: 0, samples: [], len: 0 };
  4892.       this._txtTrack = { type: 'text', id: -1, sequenceNumber: 0, samples: [], len: 0 };
  4893.       this.remuxer.switchLevel();
  4894.     }
  4895.   }, {
  4896.     key: 'insertDiscontinuity',
  4897.     value: function insertDiscontinuity() {
  4898.       this.switchLevel();
  4899.       this.remuxer.insertDiscontinuity();
  4900.     }
  4901.  
  4902.     // feed incoming data to the front of the parsing pipeline
  4903.  
  4904.   }, {
  4905.     key: 'push',
  4906.     value: function push(data, audioCodec, videoCodec, timeOffset, cc, level, sn, duration) {
  4907.       var avcData,
  4908.           aacData,
  4909.           id3Data,
  4910.           start,
  4911.           len = data.length,
  4912.           stt,
  4913.           pid,
  4914.           atf,
  4915.           offset,
  4916.           codecsOnly = this.remuxer.passthrough;
  4917.  
  4918.       this.audioCodec = audioCodec;
  4919.       this.videoCodec = videoCodec;
  4920.       this.timeOffset = timeOffset;
  4921.       this._duration = duration;
  4922.       this.contiguous = false;
  4923.       if (cc !== this.lastCC) {
  4924.         _logger.logger.log('discontinuity detected');
  4925.         this.insertDiscontinuity();
  4926.         this.lastCC = cc;
  4927.       } else if (level !== this.lastLevel) {
  4928.         _logger.logger.log('level switch detected');
  4929.         this.switchLevel();
  4930.         this.lastLevel = level;
  4931.       } else if (sn === this.lastSN + 1) {
  4932.         this.contiguous = true;
  4933.       }
  4934.       this.lastSN = sn;
  4935.  
  4936.       if (!this.contiguous) {
  4937.         // flush any partial content
  4938.         this.aacOverFlow = null;
  4939.       }
  4940.  
  4941.       var pmtParsed = this.pmtParsed,
  4942.           avcId = this._avcTrack.id,
  4943.           aacId = this._aacTrack.id,
  4944.           id3Id = this._id3Track.id;
  4945.  
  4946.       // don't parse last TS packet if incomplete
  4947.       len -= len % 188;
  4948.       // loop through TS packets
  4949.       for (start = 0; start < len; start += 188) {
  4950.         if (data[start] === 0x47) {
  4951.           stt = !!(data[start + 1] & 0x40);
  4952.           // pid is a 13-bit field starting at the last bit of TS[1]
  4953.           pid = ((data[start + 1] & 0x1f) << 8) + data[start + 2];
  4954.           atf = (data[start + 3] & 0x30) >> 4;
  4955.           // if an adaption field is present, its length is specified by the fifth byte of the TS packet header.
  4956.           if (atf > 1) {
  4957.             offset = start + 5 + data[start + 4];
  4958.             // continue if there is only adaptation field
  4959.             if (offset === start + 188) {
  4960.               continue;
  4961.             }
  4962.           } else {
  4963.             offset = start + 4;
  4964.           }
  4965.           if (pmtParsed) {
  4966.             if (pid === avcId) {
  4967.               if (stt) {
  4968.                 if (avcData) {
  4969.                   this._parseAVCPES(this._parsePES(avcData));
  4970.                   if (codecsOnly) {
  4971.                     // if we have video codec info AND
  4972.                     // if audio PID is undefined OR if we have audio codec info,
  4973.                     // we have all codec info !
  4974.                     if (this._avcTrack.codec && (aacId === -1 || this._aacTrack.codec)) {
  4975.                       this.remux(data);
  4976.                       return;
  4977.                     }
  4978.                   }
  4979.                 }
  4980.                 avcData = { data: [], size: 0 };
  4981.               }
  4982.               if (avcData) {
  4983.                 avcData.data.push(data.subarray(offset, start + 188));
  4984.                 avcData.size += start + 188 - offset;
  4985.               }
  4986.             } else if (pid === aacId) {
  4987.               if (stt) {
  4988.                 if (aacData) {
  4989.                   this._parseAACPES(this._parsePES(aacData));
  4990.                   if (codecsOnly) {
  4991.                     // here we now that we have audio codec info
  4992.                     // if video PID is undefined OR if we have video codec info,
  4993.                     // we have all codec infos !
  4994.                     if (this._aacTrack.codec && (avcId === -1 || this._avcTrack.codec)) {
  4995.                       this.remux(data);
  4996.                       return;
  4997.                     }
  4998.                   }
  4999.                 }
  5000.                 aacData = { data: [], size: 0 };
  5001.               }
  5002.               if (aacData) {
  5003.                 aacData.data.push(data.subarray(offset, start + 188));
  5004.                 aacData.size += start + 188 - offset;
  5005.               }
  5006.             } else if (pid === id3Id) {
  5007.               if (stt) {
  5008.                 if (id3Data) {
  5009.                   this._parseID3PES(this._parsePES(id3Data));
  5010.                 }
  5011.                 id3Data = { data: [], size: 0 };
  5012.               }
  5013.               if (id3Data) {
  5014.                 id3Data.data.push(data.subarray(offset, start + 188));
  5015.                 id3Data.size += start + 188 - offset;
  5016.               }
  5017.             }
  5018.           } else {
  5019.             if (stt) {
  5020.               offset += data[offset] + 1;
  5021.             }
  5022.             if (pid === 0) {
  5023.               this._parsePAT(data, offset);
  5024.             } else if (pid === this._pmtId) {
  5025.               this._parsePMT(data, offset);
  5026.               pmtParsed = this.pmtParsed = true;
  5027.               avcId = this._avcTrack.id;
  5028.               aacId = this._aacTrack.id;
  5029.               id3Id = this._id3Track.id;
  5030.             }
  5031.           }
  5032.         } else {
  5033.           this.observer.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.FRAG_PARSING_ERROR, fatal: false, reason: 'TS packet did not start with 0x47' });
  5034.         }
  5035.       }
  5036.       // parse last PES packet
  5037.       if (avcData) {
  5038.         this._parseAVCPES(this._parsePES(avcData));
  5039.       }
  5040.       if (aacData) {
  5041.         this._parseAACPES(this._parsePES(aacData));
  5042.       }
  5043.       if (id3Data) {
  5044.         this._parseID3PES(this._parsePES(id3Data));
  5045.       }
  5046.       this.remux(null);
  5047.     }
  5048.   }, {
  5049.     key: 'remux',
  5050.     value: function remux(data) {
  5051.       this.remuxer.remux(this._aacTrack, this._avcTrack, this._id3Track, this._txtTrack, this.timeOffset, this.contiguous, data);
  5052.     }
  5053.   }, {
  5054.     key: 'destroy',
  5055.     value: function destroy() {
  5056.       this.switchLevel();
  5057.       this._initPTS = this._initDTS = undefined;
  5058.       this._duration = 0;
  5059.     }
  5060.   }, {
  5061.     key: '_parsePAT',
  5062.     value: function _parsePAT(data, offset) {
  5063.       // skip the PSI header and parse the first PMT entry
  5064.       this._pmtId = (data[offset + 10] & 0x1F) << 8 | data[offset + 11];
  5065.       //logger.log('PMT PID:'  + this._pmtId);
  5066.     }
  5067.   }, {
  5068.     key: '_parsePMT',
  5069.     value: function _parsePMT(data, offset) {
  5070.       var sectionLength, tableEnd, programInfoLength, pid;
  5071.       sectionLength = (data[offset + 1] & 0x0f) << 8 | data[offset + 2];
  5072.       tableEnd = offset + 3 + sectionLength - 4;
  5073.       // to determine where the table is, we have to figure out how
  5074.       // long the program info descriptors are
  5075.       programInfoLength = (data[offset + 10] & 0x0f) << 8 | data[offset + 11];
  5076.       // advance the offset to the first entry in the mapping table
  5077.       offset += 12 + programInfoLength;
  5078.       while (offset < tableEnd) {
  5079.         pid = (data[offset + 1] & 0x1F) << 8 | data[offset + 2];
  5080.         switch (data[offset]) {
  5081.           // ISO/IEC 13818-7 ADTS AAC (MPEG-2 lower bit-rate audio)
  5082.           case 0x0f:
  5083.             //logger.log('AAC PID:'  + pid);
  5084.             if (this._aacTrack.id === -1) {
  5085.               this._aacTrack.id = pid;
  5086.             }
  5087.             break;
  5088.           // Packetized metadata (ID3)
  5089.           case 0x15:
  5090.             //logger.log('ID3 PID:'  + pid);
  5091.             this._id3Track.id = pid;
  5092.             break;
  5093.           // ITU-T Rec. H.264 and ISO/IEC 14496-10 (lower bit-rate video)
  5094.           case 0x1b:
  5095.             //logger.log('AVC PID:'  + pid);
  5096.             if (this._avcTrack.id === -1) {
  5097.               this._avcTrack.id = pid;
  5098.             }
  5099.             break;
  5100.           default:
  5101.             _logger.logger.log('unkown stream type:' + data[offset]);
  5102.             break;
  5103.         }
  5104.         // move to the next table entry
  5105.         // skip past the elementary stream descriptors, if present
  5106.         offset += ((data[offset + 3] & 0x0F) << 8 | data[offset + 4]) + 5;
  5107.       }
  5108.     }
  5109.   }, {
  5110.     key: '_parsePES',
  5111.     value: function _parsePES(stream) {
  5112.       var i = 0,
  5113.           frag,
  5114.           pesFlags,
  5115.           pesPrefix,
  5116.           pesLen,
  5117.           pesHdrLen,
  5118.           pesData,
  5119.           pesPts,
  5120.           pesDts,
  5121.           payloadStartOffset,
  5122.           data = stream.data;
  5123.       //retrieve PTS/DTS from first fragment
  5124.       frag = data[0];
  5125.       pesPrefix = (frag[0] << 16) + (frag[1] << 8) + frag[2];
  5126.       if (pesPrefix === 1) {
  5127.         pesLen = (frag[4] << 8) + frag[5];
  5128.         pesFlags = frag[7];
  5129.         if (pesFlags & 0xC0) {
  5130.           /* PES header described here : http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
  5131.               as PTS / DTS is 33 bit we cannot use bitwise operator in JS,
  5132.               as Bitwise operators treat their operands as a sequence of 32 bits */
  5133.           pesPts = (frag[9] & 0x0E) * 536870912 + // 1 << 29
  5134.           (frag[10] & 0xFF) * 4194304 + // 1 << 22
  5135.           (frag[11] & 0xFE) * 16384 + // 1 << 14
  5136.           (frag[12] & 0xFF) * 128 + // 1 << 7
  5137.           (frag[13] & 0xFE) / 2;
  5138.           // check if greater than 2^32 -1
  5139.           if (pesPts > 4294967295) {
  5140.             // decrement 2^33
  5141.             pesPts -= 8589934592;
  5142.           }
  5143.           if (pesFlags & 0x40) {
  5144.             pesDts = (frag[14] & 0x0E) * 536870912 + // 1 << 29
  5145.             (frag[15] & 0xFF) * 4194304 + // 1 << 22
  5146.             (frag[16] & 0xFE) * 16384 + // 1 << 14
  5147.             (frag[17] & 0xFF) * 128 + // 1 << 7
  5148.             (frag[18] & 0xFE) / 2;
  5149.             // check if greater than 2^32 -1
  5150.             if (pesDts > 4294967295) {
  5151.               // decrement 2^33
  5152.               pesDts -= 8589934592;
  5153.             }
  5154.           } else {
  5155.             pesDts = pesPts;
  5156.           }
  5157.         }
  5158.         pesHdrLen = frag[8];
  5159.         payloadStartOffset = pesHdrLen + 9;
  5160.  
  5161.         stream.size -= payloadStartOffset;
  5162.         //reassemble PES packet
  5163.         pesData = new Uint8Array(stream.size);
  5164.         while (data.length) {
  5165.           frag = data.shift();
  5166.           var len = frag.byteLength;
  5167.           if (payloadStartOffset) {
  5168.             if (payloadStartOffset > len) {
  5169.               // trim full frag if PES header bigger than frag
  5170.               payloadStartOffset -= len;
  5171.               continue;
  5172.             } else {
  5173.               // trim partial frag if PES header smaller than frag
  5174.               frag = frag.subarray(payloadStartOffset);
  5175.               len -= payloadStartOffset;
  5176.               payloadStartOffset = 0;
  5177.             }
  5178.           }
  5179.           pesData.set(frag, i);
  5180.           i += len;
  5181.         }
  5182.         return { data: pesData, pts: pesPts, dts: pesDts, len: pesLen };
  5183.       } else {
  5184.         return null;
  5185.       }
  5186.     }
  5187.   }, {
  5188.     key: '_parseAVCPES',
  5189.     value: function _parseAVCPES(pes) {
  5190.       var _this = this;
  5191.  
  5192.       var track = this._avcTrack,
  5193.           samples = track.samples,
  5194.           units = this._parseAVCNALu(pes.data),
  5195.           units2 = [],
  5196.           debug = false,
  5197.           key = false,
  5198.           length = 0,
  5199.           expGolombDecoder,
  5200.           avcSample,
  5201.           push,
  5202.           i;
  5203.       // no NALu found
  5204.       if (units.length === 0 && samples.length > 0) {
  5205.         // append pes.data to previous NAL unit
  5206.         var lastavcSample = samples[samples.length - 1];
  5207.         var lastUnit = lastavcSample.units.units[lastavcSample.units.units.length - 1];
  5208.         var tmp = new Uint8Array(lastUnit.data.byteLength + pes.data.byteLength);
  5209.         tmp.set(lastUnit.data, 0);
  5210.         tmp.set(pes.data, lastUnit.data.byteLength);
  5211.         lastUnit.data = tmp;
  5212.         lastavcSample.units.length += pes.data.byteLength;
  5213.         track.len += pes.data.byteLength;
  5214.       }
  5215.       //free pes.data to save up some memory
  5216.       pes.data = null;
  5217.       var debugString = '';
  5218.  
  5219.       units.forEach(function (unit) {
  5220.         switch (unit.type) {
  5221.           //NDR
  5222.           case 1:
  5223.             push = true;
  5224.             if (debug) {
  5225.               debugString += 'NDR ';
  5226.             }
  5227.             break;
  5228.           //IDR
  5229.           case 5:
  5230.             push = true;
  5231.             if (debug) {
  5232.               debugString += 'IDR ';
  5233.             }
  5234.             key = true;
  5235.             break;
  5236.           //SEI
  5237.           case 6:
  5238.             push = true;
  5239.             if (debug) {
  5240.               debugString += 'SEI ';
  5241.             }
  5242.             unit.data = _this.discardEPB(unit.data);
  5243.             expGolombDecoder = new _expGolomb2.default(unit.data);
  5244.  
  5245.             // skip frameType
  5246.             expGolombDecoder.readUByte();
  5247.  
  5248.             var payloadType = 0;
  5249.             var payloadSize = 0;
  5250.             var endOfCaptions = false;
  5251.  
  5252.             while (!endOfCaptions && expGolombDecoder.bytesAvailable > 1) {
  5253.               payloadType = 0;
  5254.               do {
  5255.                 if (expGolombDecoder.bytesAvailable !== 0) {
  5256.                   payloadType += expGolombDecoder.readUByte();
  5257.                 }
  5258.               } while (payloadType === 0xFF);
  5259.  
  5260.               // Parse payload size.
  5261.               payloadSize = 0;
  5262.               do {
  5263.                 if (expGolombDecoder.bytesAvailable !== 0) {
  5264.                   payloadSize += expGolombDecoder.readUByte();
  5265.                 }
  5266.               } while (payloadSize === 0xFF);
  5267.  
  5268.               // TODO: there can be more than one payload in an SEI packet...
  5269.               // TODO: need to read type and size in a while loop to get them all
  5270.               if (payloadType === 4 && expGolombDecoder.bytesAvailable !== 0) {
  5271.  
  5272.                 endOfCaptions = true;
  5273.  
  5274.                 var countryCode = expGolombDecoder.readUByte();
  5275.  
  5276.                 if (countryCode === 181) {
  5277.                   var providerCode = expGolombDecoder.readUShort();
  5278.  
  5279.                   if (providerCode === 49) {
  5280.                     var userStructure = expGolombDecoder.readUInt();
  5281.  
  5282.                     if (userStructure === 0x47413934) {
  5283.                       var userDataType = expGolombDecoder.readUByte();
  5284.  
  5285.                       // Raw CEA-608 bytes wrapped in CEA-708 packet
  5286.                       if (userDataType === 3) {
  5287.                         var firstByte = expGolombDecoder.readUByte();
  5288.                         var secondByte = expGolombDecoder.readUByte();
  5289.  
  5290.                         var totalCCs = 31 & firstByte;
  5291.                         var byteArray = [firstByte, secondByte];
  5292.  
  5293.                         for (i = 0; i < totalCCs; i++) {
  5294.                           // 3 bytes per CC
  5295.                           byteArray.push(expGolombDecoder.readUByte());
  5296.                           byteArray.push(expGolombDecoder.readUByte());
  5297.                           byteArray.push(expGolombDecoder.readUByte());
  5298.                         }
  5299.  
  5300.                         _this._insertSampleInOrder(_this._txtTrack.samples, { type: 3, pts: pes.pts, bytes: byteArray });
  5301.                       }
  5302.                     }
  5303.                   }
  5304.                 }
  5305.               } else if (payloadSize < expGolombDecoder.bytesAvailable) {
  5306.                 for (i = 0; i < payloadSize; i++) {
  5307.                   expGolombDecoder.readUByte();
  5308.                 }
  5309.               }
  5310.             }
  5311.             break;
  5312.           //SPS
  5313.           case 7:
  5314.             push = true;
  5315.             if (debug) {
  5316.               debugString += 'SPS ';
  5317.             }
  5318.             if (!track.sps) {
  5319.               expGolombDecoder = new _expGolomb2.default(unit.data);
  5320.               var config = expGolombDecoder.readSPS();
  5321.               track.width = config.width;
  5322.               track.height = config.height;
  5323.               track.sps = [unit.data];
  5324.               track.duration = _this._duration;
  5325.               var codecarray = unit.data.subarray(1, 4);
  5326.               var codecstring = 'avc1.';
  5327.               for (i = 0; i < 3; i++) {
  5328.                 var h = codecarray[i].toString(16);
  5329.                 if (h.length < 2) {
  5330.                   h = '0' + h;
  5331.                 }
  5332.                 codecstring += h;
  5333.               }
  5334.               track.codec = codecstring;
  5335.             }
  5336.             break;
  5337.           //PPS
  5338.           case 8:
  5339.             push = true;
  5340.             if (debug) {
  5341.               debugString += 'PPS ';
  5342.             }
  5343.             if (!track.pps) {
  5344.               track.pps = [unit.data];
  5345.             }
  5346.             break;
  5347.           case 9:
  5348.             push = false;
  5349.             if (debug) {
  5350.               debugString += 'AUD ';
  5351.             }
  5352.             break;
  5353.           default:
  5354.             push = false;
  5355.             debugString += 'unknown NAL ' + unit.type + ' ';
  5356.             break;
  5357.         }
  5358.         if (push) {
  5359.           units2.push(unit);
  5360.           length += unit.data.byteLength;
  5361.         }
  5362.       });
  5363.       if (debug || debugString.length) {
  5364.         _logger.logger.log(debugString);
  5365.       }
  5366.       //build sample from PES
  5367.       // Annex B to MP4 conversion to be done
  5368.       if (units2.length) {
  5369.         // only push AVC sample if keyframe already found in this fragment OR
  5370.         //    keyframe found in last fragment (track.sps) AND
  5371.         //        samples already appended (we already found a keyframe in this fragment) OR fragment is contiguous
  5372.         if (key === true || track.sps && (samples.length || this.contiguous)) {
  5373.           avcSample = { units: { units: units2, length: length }, pts: pes.pts, dts: pes.dts, key: key };
  5374.           samples.push(avcSample);
  5375.           track.len += length;
  5376.           track.nbNalu += units2.length;
  5377.         }
  5378.       }
  5379.     }
  5380.   }, {
  5381.     key: '_insertSampleInOrder',
  5382.     value: function _insertSampleInOrder(arr, data) {
  5383.       var len = arr.length;
  5384.       if (len > 0) {
  5385.         if (data.pts >= arr[len - 1].pts) {
  5386.           arr.push(data);
  5387.         } else {
  5388.           for (var pos = len - 1; pos >= 0; pos--) {
  5389.             if (data.pts < arr[pos].pts) {
  5390.               arr.splice(pos, 0, data);
  5391.               break;
  5392.             }
  5393.           }
  5394.         }
  5395.       } else {
  5396.         arr.push(data);
  5397.       }
  5398.     }
  5399.   }, {
  5400.     key: '_parseAVCNALu',
  5401.     value: function _parseAVCNALu(array) {
  5402.       var i = 0,
  5403.           len = array.byteLength,
  5404.           value,
  5405.           overflow,
  5406.           state = 0;
  5407.       var units = [],
  5408.           unit,
  5409.           unitType,
  5410.           lastUnitStart,
  5411.           lastUnitType;
  5412.       //logger.log('PES:' + Hex.hexDump(array));
  5413.       while (i < len) {
  5414.         value = array[i++];
  5415.         // finding 3 or 4-byte start codes (00 00 01 OR 00 00 00 01)
  5416.         switch (state) {
  5417.           case 0:
  5418.             if (value === 0) {
  5419.               state = 1;
  5420.             }
  5421.             break;
  5422.           case 1:
  5423.             if (value === 0) {
  5424.               state = 2;
  5425.             } else {
  5426.               state = 0;
  5427.             }
  5428.             break;
  5429.           case 2:
  5430.           case 3:
  5431.             if (value === 0) {
  5432.               state = 3;
  5433.             } else if (value === 1 && i < len) {
  5434.               unitType = array[i] & 0x1f;
  5435.               //logger.log('find NALU @ offset:' + i + ',type:' + unitType);
  5436.               if (lastUnitStart) {
  5437.                 unit = { data: array.subarray(lastUnitStart, i - state - 1), type: lastUnitType };
  5438.                 //logger.log('pushing NALU, type/size:' + unit.type + '/' + unit.data.byteLength);
  5439.                 units.push(unit);
  5440.               } else {
  5441.                 // If NAL units are not starting right at the beginning of the PES packet, push preceding data into previous NAL unit.
  5442.                 overflow = i - state - 1;
  5443.                 if (overflow) {
  5444.                   var track = this._avcTrack,
  5445.                       samples = track.samples;
  5446.                   //logger.log('first NALU found with overflow:' + overflow);
  5447.                   if (samples.length) {
  5448.                     var lastavcSample = samples[samples.length - 1],
  5449.                         lastUnits = lastavcSample.units.units,
  5450.                         lastUnit = lastUnits[lastUnits.length - 1],
  5451.                         tmp = new Uint8Array(lastUnit.data.byteLength + overflow);
  5452.                     tmp.set(lastUnit.data, 0);
  5453.                     tmp.set(array.subarray(0, overflow), lastUnit.data.byteLength);
  5454.                     lastUnit.data = tmp;
  5455.                     lastavcSample.units.length += overflow;
  5456.                     track.len += overflow;
  5457.                   }
  5458.                 }
  5459.               }
  5460.               lastUnitStart = i;
  5461.               lastUnitType = unitType;
  5462.               state = 0;
  5463.             } else {
  5464.               state = 0;
  5465.             }
  5466.             break;
  5467.           default:
  5468.             break;
  5469.         }
  5470.       }
  5471.       if (lastUnitStart) {
  5472.         unit = { data: array.subarray(lastUnitStart, len), type: lastUnitType };
  5473.         units.push(unit);
  5474.         //logger.log('pushing NALU, type/size:' + unit.type + '/' + unit.data.byteLength);
  5475.       }
  5476.       return units;
  5477.     }
  5478.  
  5479.     /**
  5480.      * remove Emulation Prevention bytes from a RBSP
  5481.      */
  5482.  
  5483.   }, {
  5484.     key: 'discardEPB',
  5485.     value: function discardEPB(data) {
  5486.       var length = data.byteLength,
  5487.           EPBPositions = [],
  5488.           i = 1,
  5489.           newLength,
  5490.           newData;
  5491.  
  5492.       // Find all `Emulation Prevention Bytes`
  5493.       while (i < length - 2) {
  5494.         if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
  5495.           EPBPositions.push(i + 2);
  5496.           i += 2;
  5497.         } else {
  5498.           i++;
  5499.         }
  5500.       }
  5501.  
  5502.       // If no Emulation Prevention Bytes were found just return the original
  5503.       // array
  5504.       if (EPBPositions.length === 0) {
  5505.         return data;
  5506.       }
  5507.  
  5508.       // Create a new array to hold the NAL unit data
  5509.       newLength = length - EPBPositions.length;
  5510.       newData = new Uint8Array(newLength);
  5511.       var sourceIndex = 0;
  5512.  
  5513.       for (i = 0; i < newLength; sourceIndex++, i++) {
  5514.         if (sourceIndex === EPBPositions[0]) {
  5515.           // Skip this byte
  5516.           sourceIndex++;
  5517.           // Remove this position index
  5518.           EPBPositions.shift();
  5519.         }
  5520.         newData[i] = data[sourceIndex];
  5521.       }
  5522.       return newData;
  5523.     }
  5524.   }, {
  5525.     key: '_parseAACPES',
  5526.     value: function _parseAACPES(pes) {
  5527.       var track = this._aacTrack,
  5528.           data = pes.data,
  5529.           pts = pes.pts,
  5530.           startOffset = 0,
  5531.           duration = this._duration,
  5532.           audioCodec = this.audioCodec,
  5533.           aacOverFlow = this.aacOverFlow,
  5534.           lastAacPTS = this.lastAacPTS,
  5535.           config,
  5536.           frameLength,
  5537.           frameDuration,
  5538.           frameIndex,
  5539.           offset,
  5540.           headerLength,
  5541.           stamp,
  5542.           len,
  5543.           aacSample;
  5544.       if (aacOverFlow) {
  5545.         var tmp = new Uint8Array(aacOverFlow.byteLength + data.byteLength);
  5546.         tmp.set(aacOverFlow, 0);
  5547.         tmp.set(data, aacOverFlow.byteLength);
  5548.         //logger.log(`AAC: append overflowing ${aacOverFlow.byteLength} bytes to beginning of new PES`);
  5549.         data = tmp;
  5550.       }
  5551.       // look for ADTS header (0xFFFx)
  5552.       for (offset = startOffset, len = data.length; offset < len - 1; offset++) {
  5553.         if (data[offset] === 0xff && (data[offset + 1] & 0xf0) === 0xf0) {
  5554.           break;
  5555.         }
  5556.       }
  5557.       // if ADTS header does not start straight from the beginning of the PES payload, raise an error
  5558.       if (offset) {
  5559.         var reason, fatal;
  5560.         if (offset < len - 1) {
  5561.           reason = 'AAC PES did not start with ADTS header,offset:' + offset;
  5562.           fatal = false;
  5563.         } else {
  5564.           reason = 'no ADTS header found in AAC PES';
  5565.           fatal = true;
  5566.         }
  5567.         this.observer.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.FRAG_PARSING_ERROR, fatal: fatal, reason: reason });
  5568.         if (fatal) {
  5569.           return;
  5570.         }
  5571.       }
  5572.       if (!track.audiosamplerate) {
  5573.         config = _adts2.default.getAudioConfig(this.observer, data, offset, audioCodec);
  5574.         track.config = config.config;
  5575.         track.audiosamplerate = config.samplerate;
  5576.         track.channelCount = config.channelCount;
  5577.         track.codec = config.codec;
  5578.         track.duration = duration;
  5579.         _logger.logger.log('parsed codec:' + track.codec + ',rate:' + config.samplerate + ',nb channel:' + config.channelCount);
  5580.       }
  5581.       frameIndex = 0;
  5582.       frameDuration = 1024 * 90000 / track.audiosamplerate;
  5583.  
  5584.       // if last AAC frame is overflowing, we should ensure timestamps are contiguous:
  5585.       // first sample PTS should be equal to last sample PTS + frameDuration
  5586.       if (aacOverFlow && lastAacPTS) {
  5587.         var newPTS = lastAacPTS + frameDuration;
  5588.         if (Math.abs(newPTS - pts) > 1) {
  5589.           _logger.logger.log('AAC: align PTS for overlapping frames by ' + Math.round((newPTS - pts) / 90));
  5590.           pts = newPTS;
  5591.         }
  5592.       }
  5593.  
  5594.       while (offset + 5 < len) {
  5595.         // The protection skip bit tells us if we have 2 bytes of CRC data at the end of the ADTS header
  5596.         headerLength = !!(data[offset + 1] & 0x01) ? 7 : 9;
  5597.         // retrieve frame size
  5598.         frameLength = (data[offset + 3] & 0x03) << 11 | data[offset + 4] << 3 | (data[offset + 5] & 0xE0) >>> 5;
  5599.         frameLength -= headerLength;
  5600.         //stamp = pes.pts;
  5601.  
  5602.         if (frameLength > 0 && offset + headerLength + frameLength <= len) {
  5603.           stamp = pts + frameIndex * frameDuration;
  5604.           //logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}/${(stamp/90).toFixed(0)}`);
  5605.           aacSample = { unit: data.subarray(offset + headerLength, offset + headerLength + frameLength), pts: stamp, dts: stamp };
  5606.           track.samples.push(aacSample);
  5607.           track.len += frameLength;
  5608.           offset += frameLength + headerLength;
  5609.           frameIndex++;
  5610.           // look for ADTS header (0xFFFx)
  5611.           for (; offset < len - 1; offset++) {
  5612.             if (data[offset] === 0xff && (data[offset + 1] & 0xf0) === 0xf0) {
  5613.               break;
  5614.             }
  5615.           }
  5616.         } else {
  5617.           break;
  5618.         }
  5619.       }
  5620.       if (offset < len) {
  5621.         aacOverFlow = data.subarray(offset, len);
  5622.         //logger.log(`AAC: overflow detected:${len-offset}`);
  5623.       } else {
  5624.           aacOverFlow = null;
  5625.         }
  5626.       this.aacOverFlow = aacOverFlow;
  5627.       this.lastAacPTS = stamp;
  5628.     }
  5629.   }, {
  5630.     key: '_parseID3PES',
  5631.     value: function _parseID3PES(pes) {
  5632.       this._id3Track.samples.push(pes);
  5633.     }
  5634.   }], [{
  5635.     key: 'probe',
  5636.     value: function probe(data) {
  5637.       // a TS fragment should contain at least 3 TS packets, a PAT, a PMT, and one PID, each starting with 0x47
  5638.       if (data.length >= 3 * 188 && data[0] === 0x47 && data[188] === 0x47 && data[2 * 188] === 0x47) {
  5639.         return true;
  5640.       } else {
  5641.         return false;
  5642.       }
  5643.     }
  5644.   }]);
  5645.  
  5646.   return TSDemuxer;
  5647. }();
  5648.  
  5649. exports.default = TSDemuxer;
  5650.  
  5651. },{"../errors":21,"../events":23,"../utils/logger":39,"./adts":14,"./exp-golomb":18}],21:[function(require,module,exports){
  5652. 'use strict';
  5653.  
  5654. Object.defineProperty(exports, "__esModule", {
  5655.   value: true
  5656. });
  5657. var ErrorTypes = exports.ErrorTypes = {
  5658.   // Identifier for a network error (loading error / timeout ...)
  5659.   NETWORK_ERROR: 'networkError',
  5660.   // Identifier for a media Error (video/parsing/mediasource error)
  5661.   MEDIA_ERROR: 'mediaError',
  5662.   // Identifier for all other errors
  5663.   OTHER_ERROR: 'otherError'
  5664. };
  5665.  
  5666. var ErrorDetails = exports.ErrorDetails = {
  5667.   // Identifier for a manifest load error - data: { url : faulty URL, response : XHR response}
  5668.   MANIFEST_LOAD_ERROR: 'manifestLoadError',
  5669.   // Identifier for a manifest load timeout - data: { url : faulty URL, response : XHR response}
  5670.   MANIFEST_LOAD_TIMEOUT: 'manifestLoadTimeOut',
  5671.   // Identifier for a manifest parsing error - data: { url : faulty URL, reason : error reason}
  5672.   MANIFEST_PARSING_ERROR: 'manifestParsingError',
  5673.   // Identifier for a manifest with only incompatible codecs error - data: { url : faulty URL, reason : error reason}
  5674.   MANIFEST_INCOMPATIBLE_CODECS_ERROR: 'manifestIncompatibleCodecsError',
  5675.   // Identifier for playlist load error - data: { url : faulty URL, response : XHR response}
  5676.   LEVEL_LOAD_ERROR: 'levelLoadError',
  5677.   // Identifier for playlist load timeout - data: { url : faulty URL, response : XHR response}
  5678.   LEVEL_LOAD_TIMEOUT: 'levelLoadTimeOut',
  5679.   // Identifier for a level switch error - data: { level : faulty level Id, event : error description}
  5680.   LEVEL_SWITCH_ERROR: 'levelSwitchError',
  5681.   // Identifier for fragment load error - data: { frag : fragment object, response : XHR response}
  5682.   FRAG_LOAD_ERROR: 'fragLoadError',
  5683.   // Identifier for fragment loop loading error - data: { frag : fragment object}
  5684.   FRAG_LOOP_LOADING_ERROR: 'fragLoopLoadingError',
  5685.   // Identifier for fragment load timeout error - data: { frag : fragment object}
  5686.   FRAG_LOAD_TIMEOUT: 'fragLoadTimeOut',
  5687.   // Identifier for a fragment decryption error event - data: parsing error description
  5688.   FRAG_DECRYPT_ERROR: 'fragDecryptError',
  5689.   // Identifier for a fragment parsing error event - data: parsing error description
  5690.   FRAG_PARSING_ERROR: 'fragParsingError',
  5691.   // Identifier for decrypt key load error - data: { frag : fragment object, response : XHR response}
  5692.   KEY_LOAD_ERROR: 'keyLoadError',
  5693.   // Identifier for decrypt key load timeout error - data: { frag : fragment object}
  5694.   KEY_LOAD_TIMEOUT: 'keyLoadTimeOut',
  5695.   // Triggered when an exception occurs while adding a sourceBuffer to MediaSource - data : {  err : exception , mimeType : mimeType }
  5696.   BUFFER_ADD_CODEC_ERROR: 'bufferAddCodecError',
  5697.   // Identifier for a buffer append error - data: append error description
  5698.   BUFFER_APPEND_ERROR: 'bufferAppendError',
  5699.   // Identifier for a buffer appending error event - data: appending error description
  5700.   BUFFER_APPENDING_ERROR: 'bufferAppendingError',
  5701.   // Identifier for a buffer stalled error event
  5702.   BUFFER_STALLED_ERROR: 'bufferStalledError',
  5703.   // Identifier for a buffer full event
  5704.   BUFFER_FULL_ERROR: 'bufferFullError',
  5705.   // Identifier for a buffer seek over hole event
  5706.   BUFFER_SEEK_OVER_HOLE: 'bufferSeekOverHole',
  5707.   // Identifier for an internal exception happening inside hls.js while handling an event
  5708.   INTERNAL_EXCEPTION: 'internalException'
  5709. };
  5710.  
  5711. },{}],22:[function(require,module,exports){
  5712. 'use strict';
  5713.  
  5714. Object.defineProperty(exports, "__esModule", {
  5715.   value: true
  5716. });
  5717.  
  5718. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };
  5719.  
  5720. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /*
  5721.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      *
  5722.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      * All objects in the event handling chain should inherit from this class
  5723.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      *
  5724.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      */
  5725.  
  5726. var _logger = require('./utils/logger');
  5727.  
  5728. var _errors = require('./errors');
  5729.  
  5730. var _events = require('./events');
  5731.  
  5732. var _events2 = _interopRequireDefault(_events);
  5733.  
  5734. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  5735.  
  5736. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  5737.  
  5738. var EventHandler = function () {
  5739.   function EventHandler(hls) {
  5740.     _classCallCheck(this, EventHandler);
  5741.  
  5742.     this.hls = hls;
  5743.     this.onEvent = this.onEvent.bind(this);
  5744.  
  5745.     for (var _len = arguments.length, events = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  5746.       events[_key - 1] = arguments[_key];
  5747.     }
  5748.  
  5749.     this.handledEvents = events;
  5750.     this.useGenericHandler = true;
  5751.  
  5752.     this.registerListeners();
  5753.   }
  5754.  
  5755.   _createClass(EventHandler, [{
  5756.     key: 'destroy',
  5757.     value: function destroy() {
  5758.       this.unregisterListeners();
  5759.     }
  5760.   }, {
  5761.     key: 'isEventHandler',
  5762.     value: function isEventHandler() {
  5763.       return _typeof(this.handledEvents) === 'object' && this.handledEvents.length && typeof this.onEvent === 'function';
  5764.     }
  5765.   }, {
  5766.     key: 'registerListeners',
  5767.     value: function registerListeners() {
  5768.       if (this.isEventHandler()) {
  5769.         this.handledEvents.forEach(function (event) {
  5770.           if (event === 'hlsEventGeneric') {
  5771.             throw new Error('Forbidden event name: ' + event);
  5772.           }
  5773.           this.hls.on(event, this.onEvent);
  5774.         }.bind(this));
  5775.       }
  5776.     }
  5777.   }, {
  5778.     key: 'unregisterListeners',
  5779.     value: function unregisterListeners() {
  5780.       if (this.isEventHandler()) {
  5781.         this.handledEvents.forEach(function (event) {
  5782.           this.hls.off(event, this.onEvent);
  5783.         }.bind(this));
  5784.       }
  5785.     }
  5786.  
  5787.     /**
  5788.      * arguments: event (string), data (any)
  5789.      */
  5790.  
  5791.   }, {
  5792.     key: 'onEvent',
  5793.     value: function onEvent(event, data) {
  5794.       this.onEventGeneric(event, data);
  5795.     }
  5796.   }, {
  5797.     key: 'onEventGeneric',
  5798.     value: function onEventGeneric(event, data) {
  5799.       var eventToFunction = function eventToFunction(event, data) {
  5800.         var funcName = 'on' + event.replace('hls', '');
  5801.         if (typeof this[funcName] !== 'function') {
  5802.           throw new Error('Event ' + event + ' has no generic handler in this ' + this.constructor.name + ' class (tried ' + funcName + ')');
  5803.         }
  5804.         return this[funcName].bind(this, data);
  5805.       };
  5806.       try {
  5807.         eventToFunction.call(this, event, data).call();
  5808.       } catch (err) {
  5809.         _logger.logger.error('internal error happened while processing ' + event + ':' + err.message);
  5810.         this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.OTHER_ERROR, details: _errors.ErrorDetails.INTERNAL_EXCEPTION, fatal: false, event: event, err: err });
  5811.       }
  5812.     }
  5813.   }]);
  5814.  
  5815.   return EventHandler;
  5816. }();
  5817.  
  5818. exports.default = EventHandler;
  5819.  
  5820. },{"./errors":21,"./events":23,"./utils/logger":39}],23:[function(require,module,exports){
  5821. 'use strict';
  5822.  
  5823. module.exports = {
  5824.   // fired before MediaSource is attaching to media element - data: { media }
  5825.   MEDIA_ATTACHING: 'hlsMediaAttaching',
  5826.   // fired when MediaSource has been succesfully attached to media element - data: { }
  5827.   MEDIA_ATTACHED: 'hlsMediaAttached',
  5828.   // fired before detaching MediaSource from media element - data: { }
  5829.   MEDIA_DETACHING: 'hlsMediaDetaching',
  5830.   // fired when MediaSource has been detached from media element - data: { }
  5831.   MEDIA_DETACHED: 'hlsMediaDetached',
  5832.   // fired when we buffer is going to be resetted
  5833.   BUFFER_RESET: 'hlsBufferReset',
  5834.   // fired when we know about the codecs that we need buffers for to push into - data: {tracks : { container, codec, levelCodec, initSegment, metadata }}
  5835.   BUFFER_CODECS: 'hlsBufferCodecs',
  5836.   // fired when we append a segment to the buffer - data: { segment: segment object }
  5837.   BUFFER_APPENDING: 'hlsBufferAppending',
  5838.   // fired when we are done with appending a media segment to the buffer
  5839.   BUFFER_APPENDED: 'hlsBufferAppended',
  5840.   // fired when the stream is finished and we want to notify the media buffer that there will be no more data
  5841.   BUFFER_EOS: 'hlsBufferEos',
  5842.   // fired when the media buffer should be flushed - data {startOffset, endOffset}
  5843.   BUFFER_FLUSHING: 'hlsBufferFlushing',
  5844.   // fired when the media has been flushed
  5845.   BUFFER_FLUSHED: 'hlsBufferFlushed',
  5846.   // fired to signal that a manifest loading starts - data: { url : manifestURL}
  5847.   MANIFEST_LOADING: 'hlsManifestLoading',
  5848.   // fired after manifest has been loaded - data: { levels : [available quality levels] , url : manifestURL, stats : { trequest, tfirst, tload, mtime}}
  5849.   MANIFEST_LOADED: 'hlsManifestLoaded',
  5850.   // fired after manifest has been parsed - data: { levels : [available quality levels] , firstLevel : index of first quality level appearing in Manifest}
  5851.   MANIFEST_PARSED: 'hlsManifestParsed',
  5852.   // fired when a level playlist loading starts - data: { url : level URL  level : id of level being loaded}
  5853.   LEVEL_LOADING: 'hlsLevelLoading',
  5854.   // fired when a level playlist loading finishes - data: { details : levelDetails object, level : id of loaded level, stats : { trequest, tfirst, tload, mtime} }
  5855.   LEVEL_LOADED: 'hlsLevelLoaded',
  5856.   // 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 }
  5857.   LEVEL_UPDATED: 'hlsLevelUpdated',
  5858.   // 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 }
  5859.   LEVEL_PTS_UPDATED: 'hlsLevelPtsUpdated',
  5860.   // fired when a level switch is requested - data: { level : id of new level }
  5861.   LEVEL_SWITCH: 'hlsLevelSwitch',
  5862.   // fired when a fragment loading starts - data: { frag : fragment object}
  5863.   FRAG_LOADING: 'hlsFragLoading',
  5864.   // fired when a fragment loading is progressing - data: { frag : fragment object, { trequest, tfirst, loaded}}
  5865.   FRAG_LOAD_PROGRESS: 'hlsFragLoadProgress',
  5866.   // Identifier for fragment load aborting for emergency switch down - data: {frag : fragment object}
  5867.   FRAG_LOAD_EMERGENCY_ABORTED: 'hlsFragLoadEmergencyAborted',
  5868.   // fired when a fragment loading is completed - data: { frag : fragment object, payload : fragment payload, stats : { trequest, tfirst, tload, length}}
  5869.   FRAG_LOADED: 'hlsFragLoaded',
  5870.   // fired when Init Segment has been extracted from fragment - data: { moov : moov MP4 box, codecs : codecs found while parsing fragment}
  5871.   FRAG_PARSING_INIT_SEGMENT: 'hlsFragParsingInitSegment',
  5872.   // fired when parsing sei text is completed - data: { samples : [ sei samples pes ] }
  5873.   FRAG_PARSING_USERDATA: 'hlsFragParsingUserdata',
  5874.   // fired when parsing id3 is completed - data: { samples : [ id3 samples pes ] }
  5875.   FRAG_PARSING_METADATA: 'hlsFragParsingMetadata',
  5876.   // fired when data have been extracted from fragment - data: { data1 : moof MP4 box or TS fragments, data2 : mdat MP4 box or null}
  5877.   FRAG_PARSING_DATA: 'hlsFragParsingData',
  5878.   // fired when fragment parsing is completed - data: undefined
  5879.   FRAG_PARSED: 'hlsFragParsed',
  5880.   // fired when fragment remuxed MP4 boxes have all been appended into SourceBuffer - data: { frag : fragment object, stats : { trequest, tfirst, tload, tparsed, tbuffered, length} }
  5881.   FRAG_BUFFERED: 'hlsFragBuffered',
  5882.   // fired when fragment matching with current media position is changing - data : { frag : fragment object }
  5883.   FRAG_CHANGED: 'hlsFragChanged',
  5884.   // Identifier for a FPS drop event - data: {curentDropped, currentDecoded, totalDroppedFrames}
  5885.   FPS_DROP: 'hlsFpsDrop',
  5886.   //triggered when FPS drop triggers auto level capping - data: {level, droppedlevel}
  5887.   FPS_DROP_LEVEL_CAPPING: 'hlsFpsDropLevelCapping',
  5888.   // 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}
  5889.   ERROR: 'hlsError',
  5890.   // 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
  5891.   DESTROYING: 'hlsDestroying',
  5892.   // fired when a decrypt key loading starts - data: { frag : fragment object}
  5893.   KEY_LOADING: 'hlsKeyLoading',
  5894.   // fired when a decrypt key loading is completed - data: { frag : fragment object, payload : key payload, stats : { trequest, tfirst, tload, length}}
  5895.   KEY_LOADED: 'hlsKeyLoaded',
  5896.   // fired upon stream controller state transitions - data: {previousState, nextState}
  5897.   STREAM_STATE_TRANSITION: 'hlsStreamStateTransition'
  5898. };
  5899.  
  5900. },{}],24:[function(require,module,exports){
  5901. "use strict";
  5902.  
  5903. Object.defineProperty(exports, "__esModule", {
  5904.   value: true
  5905. });
  5906.  
  5907. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  5908.  
  5909. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  5910.  
  5911. /**
  5912.  *  AAC helper
  5913.  */
  5914.  
  5915. var AAC = function () {
  5916.   function AAC() {
  5917.     _classCallCheck(this, AAC);
  5918.   }
  5919.  
  5920.   _createClass(AAC, null, [{
  5921.     key: "getSilentFrame",
  5922.     value: function getSilentFrame(channelCount) {
  5923.       if (channelCount === 1) {
  5924.         return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x23, 0x80]);
  5925.       } else if (channelCount === 2) {
  5926.         return new Uint8Array([0x21, 0x00, 0x49, 0x90, 0x02, 0x19, 0x00, 0x23, 0x80]);
  5927.       } else if (channelCount === 3) {
  5928.         return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x8e]);
  5929.       } else if (channelCount === 4) {
  5930.         return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x80, 0x2c, 0x80, 0x08, 0x02, 0x38]);
  5931.       } else if (channelCount === 5) {
  5932.         return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x38]);
  5933.       } else if (channelCount === 6) {
  5934.         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]);
  5935.       }
  5936.       return null;
  5937.     }
  5938.   }]);
  5939.  
  5940.   return AAC;
  5941. }();
  5942.  
  5943. exports.default = AAC;
  5944.  
  5945. },{}],25:[function(require,module,exports){
  5946. "use strict";
  5947.  
  5948. Object.defineProperty(exports, "__esModule", {
  5949.   value: true
  5950. });
  5951.  
  5952. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  5953.  
  5954. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  5955.  
  5956. /**
  5957.  * Buffer Helper class, providing methods dealing buffer length retrieval
  5958. */
  5959.  
  5960. var BufferHelper = function () {
  5961.   function BufferHelper() {
  5962.     _classCallCheck(this, BufferHelper);
  5963.   }
  5964.  
  5965.   _createClass(BufferHelper, null, [{
  5966.     key: "bufferInfo",
  5967.     value: function bufferInfo(media, pos, maxHoleDuration) {
  5968.       if (media) {
  5969.         var vbuffered = media.buffered,
  5970.             buffered = [],
  5971.             i;
  5972.         for (i = 0; i < vbuffered.length; i++) {
  5973.           buffered.push({ start: vbuffered.start(i), end: vbuffered.end(i) });
  5974.         }
  5975.         return this.bufferedInfo(buffered, pos, maxHoleDuration);
  5976.       } else {
  5977.         return { len: 0, start: 0, end: 0, nextStart: undefined };
  5978.       }
  5979.     }
  5980.   }, {
  5981.     key: "bufferedInfo",
  5982.     value: function bufferedInfo(buffered, pos, maxHoleDuration) {
  5983.       var buffered2 = [],
  5984.  
  5985.       // bufferStart and bufferEnd are buffer boundaries around current video position
  5986.       bufferLen,
  5987.           bufferStart,
  5988.           bufferEnd,
  5989.           bufferStartNext,
  5990.           i;
  5991.       // sort on buffer.start/smaller end (IE does not always return sorted buffered range)
  5992.       buffered.sort(function (a, b) {
  5993.         var diff = a.start - b.start;
  5994.         if (diff) {
  5995.           return diff;
  5996.         } else {
  5997.           return b.end - a.end;
  5998.         }
  5999.       });
  6000.       // there might be some small holes between buffer time range
  6001.       // consider that holes smaller than maxHoleDuration are irrelevant and build another
  6002.       // buffer time range representations that discards those holes
  6003.       for (i = 0; i < buffered.length; i++) {
  6004.         var buf2len = buffered2.length;
  6005.         if (buf2len) {
  6006.           var buf2end = buffered2[buf2len - 1].end;
  6007.           // if small hole (value between 0 or maxHoleDuration ) or overlapping (negative)
  6008.           if (buffered[i].start - buf2end < maxHoleDuration) {
  6009.             // merge overlapping time ranges
  6010.             // update lastRange.end only if smaller than item.end
  6011.             // e.g.  [ 1, 15] with  [ 2,8] => [ 1,15] (no need to modify lastRange.end)
  6012.             // whereas [ 1, 8] with  [ 2,15] => [ 1,15] ( lastRange should switch from [1,8] to [1,15])
  6013.             if (buffered[i].end > buf2end) {
  6014.               buffered2[buf2len - 1].end = buffered[i].end;
  6015.             }
  6016.           } else {
  6017.             // big hole
  6018.             buffered2.push(buffered[i]);
  6019.           }
  6020.         } else {
  6021.           // first value
  6022.           buffered2.push(buffered[i]);
  6023.         }
  6024.       }
  6025.       for (i = 0, bufferLen = 0, bufferStart = bufferEnd = pos; i < buffered2.length; i++) {
  6026.         var start = buffered2[i].start,
  6027.             end = buffered2[i].end;
  6028.         //logger.log('buf start/end:' + buffered.start(i) + '/' + buffered.end(i));
  6029.         if (pos + maxHoleDuration >= start && pos < end) {
  6030.           // play position is inside this buffer TimeRange, retrieve end of buffer position and buffer length
  6031.           bufferStart = start;
  6032.           bufferEnd = end;
  6033.           bufferLen = bufferEnd - pos;
  6034.         } else if (pos + maxHoleDuration < start) {
  6035.           bufferStartNext = start;
  6036.           break;
  6037.         }
  6038.       }
  6039.       return { len: bufferLen, start: bufferStart, end: bufferEnd, nextStart: bufferStartNext };
  6040.     }
  6041.   }]);
  6042.  
  6043.   return BufferHelper;
  6044. }();
  6045.  
  6046. exports.default = BufferHelper;
  6047.  
  6048. },{}],26:[function(require,module,exports){
  6049. 'use strict';
  6050.  
  6051. Object.defineProperty(exports, "__esModule", {
  6052.   value: true
  6053. });
  6054.  
  6055. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /**
  6056.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       * Level Helper class, providing methods dealing with playlist sliding and drift
  6057.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      */
  6058.  
  6059. var _logger = require('../utils/logger');
  6060.  
  6061. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  6062.  
  6063. var LevelHelper = function () {
  6064.   function LevelHelper() {
  6065.     _classCallCheck(this, LevelHelper);
  6066.   }
  6067.  
  6068.   _createClass(LevelHelper, null, [{
  6069.     key: 'mergeDetails',
  6070.     value: function mergeDetails(oldDetails, newDetails) {
  6071.       var start = Math.max(oldDetails.startSN, newDetails.startSN) - newDetails.startSN,
  6072.           end = Math.min(oldDetails.endSN, newDetails.endSN) - newDetails.startSN,
  6073.           delta = newDetails.startSN - oldDetails.startSN,
  6074.           oldfragments = oldDetails.fragments,
  6075.           newfragments = newDetails.fragments,
  6076.           ccOffset = 0,
  6077.           PTSFrag;
  6078.  
  6079.       // check if old/new playlists have fragments in common
  6080.       if (end < start) {
  6081.         newDetails.PTSKnown = false;
  6082.         return;
  6083.       }
  6084.       // loop through overlapping SN and update startPTS , cc, and duration if any found
  6085.       for (var i = start; i <= end; i++) {
  6086.         var oldFrag = oldfragments[delta + i],
  6087.             newFrag = newfragments[i];
  6088.         ccOffset = oldFrag.cc - newFrag.cc;
  6089.         if (!isNaN(oldFrag.startPTS)) {
  6090.           newFrag.start = newFrag.startPTS = oldFrag.startPTS;
  6091.           newFrag.endPTS = oldFrag.endPTS;
  6092.           newFrag.duration = oldFrag.duration;
  6093.           PTSFrag = newFrag;
  6094.         }
  6095.       }
  6096.  
  6097.       if (ccOffset) {
  6098.         _logger.logger.log('discontinuity sliding from playlist, take drift into account');
  6099.         for (i = 0; i < newfragments.length; i++) {
  6100.           newfragments[i].cc += ccOffset;
  6101.         }
  6102.       }
  6103.  
  6104.       // if at least one fragment contains PTS info, recompute PTS information for all fragments
  6105.       if (PTSFrag) {
  6106.         LevelHelper.updateFragPTS(newDetails, PTSFrag.sn, PTSFrag.startPTS, PTSFrag.endPTS);
  6107.       } else {
  6108.         // ensure that delta is within oldfragments range
  6109.         // also adjust sliding in case delta is 0 (we could have old=[50-60] and new=old=[50-61])
  6110.         // in that case we also need to adjust start offset of all fragments
  6111.         if (delta >= 0 && delta < oldfragments.length) {
  6112.           // adjust start by sliding offset
  6113.           var sliding = oldfragments[delta].start;
  6114.           for (i = 0; i < newfragments.length; i++) {
  6115.             newfragments[i].start += sliding;
  6116.           }
  6117.         }
  6118.       }
  6119.       // if we are here, it means we have fragments overlapping between
  6120.       // old and new level. reliable PTS info is thus relying on old level
  6121.       newDetails.PTSKnown = oldDetails.PTSKnown;
  6122.       return;
  6123.     }
  6124.   }, {
  6125.     key: 'updateFragPTS',
  6126.     value: function updateFragPTS(details, sn, startPTS, endPTS) {
  6127.       var fragIdx, fragments, frag, i;
  6128.       // exit if sn out of range
  6129.       if (sn < details.startSN || sn > details.endSN) {
  6130.         return 0;
  6131.       }
  6132.       fragIdx = sn - details.startSN;
  6133.       fragments = details.fragments;
  6134.       frag = fragments[fragIdx];
  6135.       if (!isNaN(frag.startPTS)) {
  6136.         startPTS = Math.min(startPTS, frag.startPTS);
  6137.         endPTS = Math.max(endPTS, frag.endPTS);
  6138.       }
  6139.  
  6140.       var drift = startPTS - frag.start;
  6141.  
  6142.       frag.start = frag.startPTS = startPTS;
  6143.       frag.endPTS = endPTS;
  6144.       frag.duration = endPTS - startPTS;
  6145.       // adjust fragment PTS/duration from seqnum-1 to frag 0
  6146.       for (i = fragIdx; i > 0; i--) {
  6147.         LevelHelper.updatePTS(fragments, i, i - 1);
  6148.       }
  6149.  
  6150.       // adjust fragment PTS/duration from seqnum to last frag
  6151.       for (i = fragIdx; i < fragments.length - 1; i++) {
  6152.         LevelHelper.updatePTS(fragments, i, i + 1);
  6153.       }
  6154.       details.PTSKnown = true;
  6155.       //logger.log(`                                            frag start/end:${startPTS.toFixed(3)}/${endPTS.toFixed(3)}`);
  6156.  
  6157.       return drift;
  6158.     }
  6159.   }, {
  6160.     key: 'updatePTS',
  6161.     value: function updatePTS(fragments, fromIdx, toIdx) {
  6162.       var fragFrom = fragments[fromIdx],
  6163.           fragTo = fragments[toIdx],
  6164.           fragToPTS = fragTo.startPTS;
  6165.       // if we know startPTS[toIdx]
  6166.       if (!isNaN(fragToPTS)) {
  6167.         // update fragment duration.
  6168.         // it helps to fix drifts between playlist reported duration and fragment real duration
  6169.         if (toIdx > fromIdx) {
  6170.           fragFrom.duration = fragToPTS - fragFrom.start;
  6171.           if (fragFrom.duration < 0) {
  6172.             _logger.logger.error('negative duration computed for frag ' + fragFrom.sn + ',level ' + fragFrom.level + ', there should be some duration drift between playlist and fragment!');
  6173.           }
  6174.         } else {
  6175.           fragTo.duration = fragFrom.start - fragToPTS;
  6176.           if (fragTo.duration < 0) {
  6177.             _logger.logger.error('negative duration computed for frag ' + fragTo.sn + ',level ' + fragTo.level + ', there should be some duration drift between playlist and fragment!');
  6178.           }
  6179.         }
  6180.       } else {
  6181.         // we dont know startPTS[toIdx]
  6182.         if (toIdx > fromIdx) {
  6183.           fragTo.start = fragFrom.start + fragFrom.duration;
  6184.         } else {
  6185.           fragTo.start = fragFrom.start - fragTo.duration;
  6186.         }
  6187.       }
  6188.     }
  6189.   }]);
  6190.  
  6191.   return LevelHelper;
  6192. }();
  6193.  
  6194. exports.default = LevelHelper;
  6195.  
  6196. },{"../utils/logger":39}],27:[function(require,module,exports){
  6197. /**
  6198.  * HLS interface
  6199.  */
  6200. 'use strict';
  6201.  
  6202. Object.defineProperty(exports, "__esModule", {
  6203.   value: true
  6204. });
  6205.  
  6206. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  6207.  
  6208. var _events = require('./events');
  6209.  
  6210. var _events2 = _interopRequireDefault(_events);
  6211.  
  6212. var _errors = require('./errors');
  6213.  
  6214. var _playlistLoader = require('./loader/playlist-loader');
  6215.  
  6216. var _playlistLoader2 = _interopRequireDefault(_playlistLoader);
  6217.  
  6218. var _fragmentLoader = require('./loader/fragment-loader');
  6219.  
  6220. var _fragmentLoader2 = _interopRequireDefault(_fragmentLoader);
  6221.  
  6222. var _abrController = require('./controller/abr-controller');
  6223.  
  6224. var _abrController2 = _interopRequireDefault(_abrController);
  6225.  
  6226. var _bufferController = require('./controller/buffer-controller');
  6227.  
  6228. var _bufferController2 = _interopRequireDefault(_bufferController);
  6229.  
  6230. var _capLevelController = require('./controller/cap-level-controller');
  6231.  
  6232. var _capLevelController2 = _interopRequireDefault(_capLevelController);
  6233.  
  6234. var _streamController = require('./controller/stream-controller');
  6235.  
  6236. var _streamController2 = _interopRequireDefault(_streamController);
  6237.  
  6238. var _levelController = require('./controller/level-controller');
  6239.  
  6240. var _levelController2 = _interopRequireDefault(_levelController);
  6241.  
  6242. var _timelineController = require('./controller/timeline-controller');
  6243.  
  6244. var _timelineController2 = _interopRequireDefault(_timelineController);
  6245.  
  6246. var _fpsController = require('./controller/fps-controller');
  6247.  
  6248. var _fpsController2 = _interopRequireDefault(_fpsController);
  6249.  
  6250. var _logger = require('./utils/logger');
  6251.  
  6252. var _xhrLoader = require('./utils/xhr-loader');
  6253.  
  6254. var _xhrLoader2 = _interopRequireDefault(_xhrLoader);
  6255.  
  6256. var _events3 = require('events');
  6257.  
  6258. var _events4 = _interopRequireDefault(_events3);
  6259.  
  6260. var _keyLoader = require('./loader/key-loader');
  6261.  
  6262. var _keyLoader2 = _interopRequireDefault(_keyLoader);
  6263.  
  6264. var _cues = require('./utils/cues');
  6265.  
  6266. var _cues2 = _interopRequireDefault(_cues);
  6267.  
  6268. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  6269.  
  6270. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  6271.  
  6272. var Hls = function () {
  6273.   _createClass(Hls, null, [{
  6274.     key: 'isSupported',
  6275.     value: function isSupported() {
  6276.       return window.MediaSource && window.MediaSource.isTypeSupported('video/mp4; codecs="avc1.42E01E,mp4a.40.2"');
  6277.     }
  6278.   }, {
  6279.     key: 'version',
  6280.     get: function get() {
  6281.       // replaced with browserify-versionify transform
  6282.       return '0.6.1';
  6283.     }
  6284.   }, {
  6285.     key: 'Events',
  6286.     get: function get() {
  6287.       return _events2.default;
  6288.     }
  6289.   }, {
  6290.     key: 'ErrorTypes',
  6291.     get: function get() {
  6292.       return _errors.ErrorTypes;
  6293.     }
  6294.   }, {
  6295.     key: 'ErrorDetails',
  6296.     get: function get() {
  6297.       return _errors.ErrorDetails;
  6298.     }
  6299.   }, {
  6300.     key: 'DefaultConfig',
  6301.     get: function get() {
  6302.       if (!Hls.defaultConfig) {
  6303.         Hls.defaultConfig = {
  6304.           autoStartLoad: true,
  6305.           debug: false,
  6306.           capLevelOnFPSDrop: false,
  6307.           capLevelToPlayerSize: false,
  6308.           maxBufferLength: 30,
  6309.           maxBufferSize: 60 * 1000 * 1000,
  6310.           maxBufferHole: 0.5,
  6311.           maxSeekHole: 2,
  6312.           seekHoleNudgeDuration: 0.01,
  6313.           stalledInBufferedNudgeThreshold: 10,
  6314.           maxFragLookUpTolerance: 0.2,
  6315.           liveSyncDurationCount: 3,
  6316.           liveMaxLatencyDurationCount: Infinity,
  6317.           liveSyncDuration: undefined,
  6318.           liveMaxLatencyDuration: undefined,
  6319.           maxMaxBufferLength: 600,
  6320.           enableWorker: true,
  6321.           enableSoftwareAES: true,
  6322.           manifestLoadingTimeOut: 10000,
  6323.           manifestLoadingMaxRetry: 1,
  6324.           manifestLoadingRetryDelay: 1000,
  6325.           levelLoadingTimeOut: 10000,
  6326.           levelLoadingMaxRetry: 4,
  6327.           levelLoadingRetryDelay: 1000,
  6328.           fragLoadingTimeOut: 20000,
  6329.           fragLoadingMaxRetry: 6,
  6330.           fragLoadingRetryDelay: 1000,
  6331.           fragLoadingLoopThreshold: 3,
  6332.           startFragPrefetch: false,
  6333.           fpsDroppedMonitoringPeriod: 5000,
  6334.           fpsDroppedMonitoringThreshold: 0.2,
  6335.           appendErrorMaxRetry: 3,
  6336.           loader: _xhrLoader2.default,
  6337.           fLoader: undefined,
  6338.           pLoader: undefined,
  6339.           abrController: _abrController2.default,
  6340.           bufferController: _bufferController2.default,
  6341.           capLevelController: _capLevelController2.default,
  6342.           fpsController: _fpsController2.default,
  6343.           streamController: _streamController2.default,
  6344.           timelineController: _timelineController2.default,
  6345.           cueHandler: _cues2.default,
  6346.           enableCEA708Captions: true,
  6347.           enableMP2TPassThrough: false,
  6348.           stretchShortVideoTrack: false
  6349.         };
  6350.       }
  6351.       return Hls.defaultConfig;
  6352.     },
  6353.     set: function set(defaultConfig) {
  6354.       Hls.defaultConfig = defaultConfig;
  6355.     }
  6356.   }]);
  6357.  
  6358.   function Hls() {
  6359.     var config = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
  6360.  
  6361.     _classCallCheck(this, Hls);
  6362.  
  6363.     var defaultConfig = Hls.DefaultConfig;
  6364.  
  6365.     if ((config.liveSyncDurationCount || config.liveMaxLatencyDurationCount) && (config.liveSyncDuration || config.liveMaxLatencyDuration)) {
  6366.       throw new Error('Illegal hls.js config: don\'t mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration');
  6367.     }
  6368.  
  6369.     for (var prop in defaultConfig) {
  6370.       if (prop in config) {
  6371.         continue;
  6372.       }
  6373.       config[prop] = defaultConfig[prop];
  6374.     }
  6375.  
  6376.     if (config.liveMaxLatencyDurationCount !== undefined && config.liveMaxLatencyDurationCount <= config.liveSyncDurationCount) {
  6377.       throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be gt "liveSyncDurationCount"');
  6378.     }
  6379.  
  6380.     if (config.liveMaxLatencyDuration !== undefined && (config.liveMaxLatencyDuration <= config.liveSyncDuration || config.liveSyncDuration === undefined)) {
  6381.       throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be gt "liveSyncDuration"');
  6382.     }
  6383.  
  6384.     (0, _logger.enableLogs)(config.debug);
  6385.     this.config = config;
  6386.     // observer setup
  6387.     var observer = this.observer = new _events4.default();
  6388.     observer.trigger = function trigger(event) {
  6389.       for (var _len = arguments.length, data = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  6390.         data[_key - 1] = arguments[_key];
  6391.       }
  6392.  
  6393.       observer.emit.apply(observer, [event, event].concat(data));
  6394.     };
  6395.  
  6396.     observer.off = function off(event) {
  6397.       for (var _len2 = arguments.length, data = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
  6398.         data[_key2 - 1] = arguments[_key2];
  6399.       }
  6400.  
  6401.       observer.removeListener.apply(observer, [event].concat(data));
  6402.     };
  6403.     this.on = observer.on.bind(observer);
  6404.     this.off = observer.off.bind(observer);
  6405.     this.trigger = observer.trigger.bind(observer);
  6406.     this.playlistLoader = new _playlistLoader2.default(this);
  6407.     this.fragmentLoader = new _fragmentLoader2.default(this);
  6408.     this.levelController = new _levelController2.default(this);
  6409.     this.abrController = new config.abrController(this);
  6410.     this.bufferController = new config.bufferController(this);
  6411.     this.capLevelController = new config.capLevelController(this);
  6412.     this.fpsController = new config.fpsController(this);
  6413.     this.streamController = new config.streamController(this);
  6414.     this.timelineController = new config.timelineController(this);
  6415.     this.keyLoader = new _keyLoader2.default(this);
  6416.   }
  6417.  
  6418.   _createClass(Hls, [{
  6419.     key: 'destroy',
  6420.     value: function destroy() {
  6421.       _logger.logger.log('destroy');
  6422.       this.trigger(_events2.default.DESTROYING);
  6423.       this.detachMedia();
  6424.       this.playlistLoader.destroy();
  6425.       this.fragmentLoader.destroy();
  6426.       this.levelController.destroy();
  6427.       this.abrController.destroy();
  6428.       this.bufferController.destroy();
  6429.       this.capLevelController.destroy();
  6430.       this.fpsController.destroy();
  6431.       this.streamController.destroy();
  6432.       this.timelineController.destroy();
  6433.       this.keyLoader.destroy();
  6434.       this.url = null;
  6435.       this.observer.removeAllListeners();
  6436.     }
  6437.   }, {
  6438.     key: 'attachMedia',
  6439.     value: function attachMedia(media) {
  6440.       _logger.logger.log('attachMedia');
  6441.       this.media = media;
  6442.       this.trigger(_events2.default.MEDIA_ATTACHING, { media: media });
  6443.     }
  6444.   }, {
  6445.     key: 'detachMedia',
  6446.     value: function detachMedia() {
  6447.       _logger.logger.log('detachMedia');
  6448.       this.trigger(_events2.default.MEDIA_DETACHING);
  6449.       this.media = null;
  6450.     }
  6451.   }, {
  6452.     key: 'loadSource',
  6453.     value: function loadSource(url) {
  6454.       _logger.logger.log('loadSource:' + url);
  6455.       this.url = url;
  6456.       // when attaching to a source URL, trigger a playlist load
  6457.       this.trigger(_events2.default.MANIFEST_LOADING, { url: url });
  6458.     }
  6459.   }, {
  6460.     key: 'startLoad',
  6461.     value: function startLoad() {
  6462.       var startPosition = arguments.length <= 0 || arguments[0] === undefined ? 0 : arguments[0];
  6463.  
  6464.       _logger.logger.log('startLoad');
  6465.       this.levelController.startLoad();
  6466.       this.streamController.startLoad(startPosition);
  6467.     }
  6468.   }, {
  6469.     key: 'stopLoad',
  6470.     value: function stopLoad() {
  6471.       _logger.logger.log('stopLoad');
  6472.       this.levelController.stopLoad();
  6473.       this.streamController.stopLoad();
  6474.     }
  6475.   }, {
  6476.     key: 'swapAudioCodec',
  6477.     value: function swapAudioCodec() {
  6478.       _logger.logger.log('swapAudioCodec');
  6479.       this.streamController.swapAudioCodec();
  6480.     }
  6481.   }, {
  6482.     key: 'recoverMediaError',
  6483.     value: function recoverMediaError() {
  6484.       _logger.logger.log('recoverMediaError');
  6485.       var media = this.media;
  6486.       this.detachMedia();
  6487.       this.attachMedia(media);
  6488.     }
  6489.  
  6490.     /** Return all quality levels **/
  6491.  
  6492.   }, {
  6493.     key: 'levels',
  6494.     get: function get() {
  6495.       return this.levelController.levels;
  6496.     }
  6497.  
  6498.     /** Return current playback quality level **/
  6499.  
  6500.   }, {
  6501.     key: 'currentLevel',
  6502.     get: function get() {
  6503.       return this.streamController.currentLevel;
  6504.     }
  6505.  
  6506.     /* set quality level immediately (-1 for automatic level selection) */
  6507.     ,
  6508.     set: function set(newLevel) {
  6509.       _logger.logger.log('set currentLevel:' + newLevel);
  6510.       this.loadLevel = newLevel;
  6511.       this.streamController.immediateLevelSwitch();
  6512.     }
  6513.  
  6514.     /** Return next playback quality level (quality level of next fragment) **/
  6515.  
  6516.   }, {
  6517.     key: 'nextLevel',
  6518.     get: function get() {
  6519.       return this.streamController.nextLevel;
  6520.     }
  6521.  
  6522.     /* set quality level for next fragment (-1 for automatic level selection) */
  6523.     ,
  6524.     set: function set(newLevel) {
  6525.       _logger.logger.log('set nextLevel:' + newLevel);
  6526.       this.levelController.manualLevel = newLevel;
  6527.       this.streamController.nextLevelSwitch();
  6528.     }
  6529.  
  6530.     /** Return the quality level of current/last loaded fragment **/
  6531.  
  6532.   }, {
  6533.     key: 'loadLevel',
  6534.     get: function get() {
  6535.       return this.levelController.level;
  6536.     }
  6537.  
  6538.     /* set quality level for current/next loaded fragment (-1 for automatic level selection) */
  6539.     ,
  6540.     set: function set(newLevel) {
  6541.       _logger.logger.log('set loadLevel:' + newLevel);
  6542.       this.levelController.manualLevel = newLevel;
  6543.     }
  6544.  
  6545.     /** Return the quality level of next loaded fragment **/
  6546.  
  6547.   }, {
  6548.     key: 'nextLoadLevel',
  6549.     get: function get() {
  6550.       return this.levelController.nextLoadLevel;
  6551.     }
  6552.  
  6553.     /** set quality level of next loaded fragment **/
  6554.     ,
  6555.     set: function set(level) {
  6556.       this.levelController.nextLoadLevel = level;
  6557.     }
  6558.  
  6559.     /** Return first level (index of first level referenced in manifest)
  6560.     **/
  6561.  
  6562.   }, {
  6563.     key: 'firstLevel',
  6564.     get: function get() {
  6565.       return this.levelController.firstLevel;
  6566.     }
  6567.  
  6568.     /** set first level (index of first level referenced in manifest)
  6569.     **/
  6570.     ,
  6571.     set: function set(newLevel) {
  6572.       _logger.logger.log('set firstLevel:' + newLevel);
  6573.       this.levelController.firstLevel = newLevel;
  6574.     }
  6575.  
  6576.     /** Return start level (level of first fragment that will be played back)
  6577.         if not overrided by user, first level appearing in manifest will be used as start level
  6578.         if -1 : automatic start level selection, playback will start from level matching download bandwidth (determined from download of first segment)
  6579.     **/
  6580.  
  6581.   }, {
  6582.     key: 'startLevel',
  6583.     get: function get() {
  6584.       return this.levelController.startLevel;
  6585.     }
  6586.  
  6587.     /** set  start level (level of first fragment that will be played back)
  6588.         if not overrided by user, first level appearing in manifest will be used as start level
  6589.         if -1 : automatic start level selection, playback will start from level matching download bandwidth (determined from download of first segment)
  6590.     **/
  6591.     ,
  6592.     set: function set(newLevel) {
  6593.       _logger.logger.log('set startLevel:' + newLevel);
  6594.       this.levelController.startLevel = newLevel;
  6595.     }
  6596.  
  6597.     /** Return the capping/max level value that could be used by automatic level selection algorithm **/
  6598.  
  6599.   }, {
  6600.     key: 'autoLevelCapping',
  6601.     get: function get() {
  6602.       return this.abrController.autoLevelCapping;
  6603.     }
  6604.  
  6605.     /** set the capping/max level value that could be used by automatic level selection algorithm **/
  6606.     ,
  6607.     set: function set(newLevel) {
  6608.       _logger.logger.log('set autoLevelCapping:' + newLevel);
  6609.       this.abrController.autoLevelCapping = newLevel;
  6610.     }
  6611.  
  6612.     /* check if we are in automatic level selection mode */
  6613.  
  6614.   }, {
  6615.     key: 'autoLevelEnabled',
  6616.     get: function get() {
  6617.       return this.levelController.manualLevel === -1;
  6618.     }
  6619.  
  6620.     /* return manual level */
  6621.  
  6622.   }, {
  6623.     key: 'manualLevel',
  6624.     get: function get() {
  6625.       return this.levelController.manualLevel;
  6626.     }
  6627.   }]);
  6628.  
  6629.   return Hls;
  6630. }();
  6631.  
  6632. exports.default = Hls;
  6633.  
  6634. },{"./controller/abr-controller":3,"./controller/buffer-controller":4,"./controller/cap-level-controller":5,"./controller/fps-controller":6,"./controller/level-controller":7,"./controller/stream-controller":8,"./controller/timeline-controller":9,"./errors":21,"./events":23,"./loader/fragment-loader":29,"./loader/key-loader":30,"./loader/playlist-loader":31,"./utils/cues":38,"./utils/logger":39,"./utils/xhr-loader":42,"events":1}],28:[function(require,module,exports){
  6635. 'use strict';
  6636.  
  6637. // This is mostly for support of the es6 module export
  6638. // syntax with the babel compiler, it looks like it doesnt support
  6639. // function exports like we are used to in node/commonjs
  6640. module.exports = require('./hls.js').default;
  6641.  
  6642. },{"./hls.js":27}],29:[function(require,module,exports){
  6643. 'use strict';
  6644.  
  6645. Object.defineProperty(exports, "__esModule", {
  6646.   value: true
  6647. });
  6648.  
  6649. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  6650.  
  6651. var _events = require('../events');
  6652.  
  6653. var _events2 = _interopRequireDefault(_events);
  6654.  
  6655. var _eventHandler = require('../event-handler');
  6656.  
  6657. var _eventHandler2 = _interopRequireDefault(_eventHandler);
  6658.  
  6659. var _errors = require('../errors');
  6660.  
  6661. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  6662.  
  6663. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  6664.  
  6665. function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
  6666.  
  6667. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /*
  6668.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 * Fragment Loader
  6669.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                */
  6670.  
  6671. var FragmentLoader = function (_EventHandler) {
  6672.   _inherits(FragmentLoader, _EventHandler);
  6673.  
  6674.   function FragmentLoader(hls) {
  6675.     _classCallCheck(this, FragmentLoader);
  6676.  
  6677.     return _possibleConstructorReturn(this, Object.getPrototypeOf(FragmentLoader).call(this, hls, _events2.default.FRAG_LOADING));
  6678.   }
  6679.  
  6680.   _createClass(FragmentLoader, [{
  6681.     key: 'destroy',
  6682.     value: function destroy() {
  6683.       if (this.loader) {
  6684.         this.loader.destroy();
  6685.         this.loader = null;
  6686.       }
  6687.       _eventHandler2.default.prototype.destroy.call(this);
  6688.     }
  6689.   }, {
  6690.     key: 'onFragLoading',
  6691.     value: function onFragLoading(data) {
  6692.       var frag = data.frag;
  6693.       this.frag = frag;
  6694.       this.frag.loaded = 0;
  6695.       var config = this.hls.config;
  6696.       frag.loader = this.loader = typeof config.fLoader !== 'undefined' ? new config.fLoader(config) : new config.loader(config);
  6697.       this.loader.load(frag.url, 'arraybuffer', this.loadsuccess.bind(this), this.loaderror.bind(this), this.loadtimeout.bind(this), config.fragLoadingTimeOut, 1, 0, this.loadprogress.bind(this), frag);
  6698.     }
  6699.   }, {
  6700.     key: 'loadsuccess',
  6701.     value: function loadsuccess(event, stats) {
  6702.       var payload = event.currentTarget.response;
  6703.       stats.length = payload.byteLength;
  6704.       // detach fragment loader on load success
  6705.       this.frag.loader = undefined;
  6706.       this.hls.trigger(_events2.default.FRAG_LOADED, { payload: payload, frag: this.frag, stats: stats });
  6707.     }
  6708.   }, {
  6709.     key: 'loaderror',
  6710.     value: function loaderror(event) {
  6711.       if (this.loader) {
  6712.         this.loader.abort();
  6713.       }
  6714.       this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.NETWORK_ERROR, details: _errors.ErrorDetails.FRAG_LOAD_ERROR, fatal: false, frag: this.frag, response: event });
  6715.     }
  6716.   }, {
  6717.     key: 'loadtimeout',
  6718.     value: function loadtimeout() {
  6719.       if (this.loader) {
  6720.         this.loader.abort();
  6721.       }
  6722.       this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.NETWORK_ERROR, details: _errors.ErrorDetails.FRAG_LOAD_TIMEOUT, fatal: false, frag: this.frag });
  6723.     }
  6724.   }, {
  6725.     key: 'loadprogress',
  6726.     value: function loadprogress(stats) {
  6727.       this.frag.loaded = stats.loaded;
  6728.       this.hls.trigger(_events2.default.FRAG_LOAD_PROGRESS, { frag: this.frag, stats: stats });
  6729.     }
  6730.   }]);
  6731.  
  6732.   return FragmentLoader;
  6733. }(_eventHandler2.default);
  6734.  
  6735. exports.default = FragmentLoader;
  6736.  
  6737. },{"../errors":21,"../event-handler":22,"../events":23}],30:[function(require,module,exports){
  6738. 'use strict';
  6739.  
  6740. Object.defineProperty(exports, "__esModule", {
  6741.   value: true
  6742. });
  6743.  
  6744. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  6745.  
  6746. var _events = require('../events');
  6747.  
  6748. var _events2 = _interopRequireDefault(_events);
  6749.  
  6750. var _eventHandler = require('../event-handler');
  6751.  
  6752. var _eventHandler2 = _interopRequireDefault(_eventHandler);
  6753.  
  6754. var _errors = require('../errors');
  6755.  
  6756. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  6757.  
  6758. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  6759.  
  6760. function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
  6761.  
  6762. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /*
  6763.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 * Decrypt key Loader
  6764.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                */
  6765.  
  6766. var KeyLoader = function (_EventHandler) {
  6767.   _inherits(KeyLoader, _EventHandler);
  6768.  
  6769.   function KeyLoader(hls) {
  6770.     _classCallCheck(this, KeyLoader);
  6771.  
  6772.     var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(KeyLoader).call(this, hls, _events2.default.KEY_LOADING));
  6773.  
  6774.     _this.decryptkey = null;
  6775.     _this.decrypturl = null;
  6776.     return _this;
  6777.   }
  6778.  
  6779.   _createClass(KeyLoader, [{
  6780.     key: 'destroy',
  6781.     value: function destroy() {
  6782.       if (this.loader) {
  6783.         this.loader.destroy();
  6784.         this.loader = null;
  6785.       }
  6786.       _eventHandler2.default.prototype.destroy.call(this);
  6787.     }
  6788.   }, {
  6789.     key: 'onKeyLoading',
  6790.     value: function onKeyLoading(data) {
  6791.       var frag = this.frag = data.frag,
  6792.           decryptdata = frag.decryptdata,
  6793.           uri = decryptdata.uri;
  6794.       // if uri is different from previous one or if decrypt key not retrieved yet
  6795.       if (uri !== this.decrypturl || this.decryptkey === null) {
  6796.         var config = this.hls.config;
  6797.         frag.loader = this.loader = new config.loader(config);
  6798.         this.decrypturl = uri;
  6799.         this.decryptkey = null;
  6800.         frag.loader.load(uri, 'arraybuffer', this.loadsuccess.bind(this), this.loaderror.bind(this), this.loadtimeout.bind(this), config.fragLoadingTimeOut, config.fragLoadingMaxRetry, config.fragLoadingRetryDelay, this.loadprogress.bind(this), frag);
  6801.       } else if (this.decryptkey) {
  6802.         // we already loaded this key, return it
  6803.         decryptdata.key = this.decryptkey;
  6804.         this.hls.trigger(_events2.default.KEY_LOADED, { frag: frag });
  6805.       }
  6806.     }
  6807.   }, {
  6808.     key: 'loadsuccess',
  6809.     value: function loadsuccess(event) {
  6810.       var frag = this.frag;
  6811.       this.decryptkey = frag.decryptdata.key = new Uint8Array(event.currentTarget.response);
  6812.       // detach fragment loader on load success
  6813.       frag.loader = undefined;
  6814.       this.hls.trigger(_events2.default.KEY_LOADED, { frag: frag });
  6815.     }
  6816.   }, {
  6817.     key: 'loaderror',
  6818.     value: function loaderror(event) {
  6819.       if (this.loader) {
  6820.         this.loader.abort();
  6821.       }
  6822.       this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.NETWORK_ERROR, details: _errors.ErrorDetails.KEY_LOAD_ERROR, fatal: false, frag: this.frag, response: event });
  6823.     }
  6824.   }, {
  6825.     key: 'loadtimeout',
  6826.     value: function loadtimeout() {
  6827.       if (this.loader) {
  6828.         this.loader.abort();
  6829.       }
  6830.       this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.NETWORK_ERROR, details: _errors.ErrorDetails.KEY_LOAD_TIMEOUT, fatal: false, frag: this.frag });
  6831.     }
  6832.   }, {
  6833.     key: 'loadprogress',
  6834.     value: function loadprogress() {}
  6835.   }]);
  6836.  
  6837.   return KeyLoader;
  6838. }(_eventHandler2.default);
  6839.  
  6840. exports.default = KeyLoader;
  6841.  
  6842. },{"../errors":21,"../event-handler":22,"../events":23}],31:[function(require,module,exports){
  6843. 'use strict';
  6844.  
  6845. Object.defineProperty(exports, "__esModule", {
  6846.   value: true
  6847. });
  6848.  
  6849. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  6850.  
  6851. var _events = require('../events');
  6852.  
  6853. var _events2 = _interopRequireDefault(_events);
  6854.  
  6855. var _eventHandler = require('../event-handler');
  6856.  
  6857. var _eventHandler2 = _interopRequireDefault(_eventHandler);
  6858.  
  6859. var _errors = require('../errors');
  6860.  
  6861. var _url = require('../utils/url');
  6862.  
  6863. var _url2 = _interopRequireDefault(_url);
  6864.  
  6865. var _attrList = require('../utils/attr-list');
  6866.  
  6867. var _attrList2 = _interopRequireDefault(_attrList);
  6868.  
  6869. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  6870.  
  6871. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  6872.  
  6873. function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
  6874.  
  6875. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /**
  6876.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 * Playlist Loader
  6877.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                */
  6878.  
  6879. //import {logger} from '../utils/logger';
  6880.  
  6881. var PlaylistLoader = function (_EventHandler) {
  6882.   _inherits(PlaylistLoader, _EventHandler);
  6883.  
  6884.   function PlaylistLoader(hls) {
  6885.     _classCallCheck(this, PlaylistLoader);
  6886.  
  6887.     return _possibleConstructorReturn(this, Object.getPrototypeOf(PlaylistLoader).call(this, hls, _events2.default.MANIFEST_LOADING, _events2.default.LEVEL_LOADING));
  6888.   }
  6889.  
  6890.   _createClass(PlaylistLoader, [{
  6891.     key: 'destroy',
  6892.     value: function destroy() {
  6893.       if (this.loader) {
  6894.         this.loader.destroy();
  6895.         this.loader = null;
  6896.       }
  6897.       this.url = this.id = null;
  6898.       _eventHandler2.default.prototype.destroy.call(this);
  6899.     }
  6900.   }, {
  6901.     key: 'onManifestLoading',
  6902.     value: function onManifestLoading(data) {
  6903.       this.load(data.url, null);
  6904.     }
  6905.   }, {
  6906.     key: 'onLevelLoading',
  6907.     value: function onLevelLoading(data) {
  6908.       this.load(data.url, data.level, data.id);
  6909.     }
  6910.   }, {
  6911.     key: 'load',
  6912.     value: function load(url, id1, id2) {
  6913.       var config = this.hls.config,
  6914.           retry,
  6915.           timeout,
  6916.           retryDelay;
  6917.  
  6918.       if (this.loading && this.loader) {
  6919.         if (this.url === url && this.id === id1 && this.id2 === id2) {
  6920.           // same request than last pending one, don't do anything
  6921.           return;
  6922.         } else {
  6923.           // one playlist load request is pending, but with different params, abort it before loading new playlist
  6924.           this.loader.abort();
  6925.         }
  6926.       }
  6927.  
  6928.       this.url = url;
  6929.       this.id = id1;
  6930.       this.id2 = id2;
  6931.       if (this.id === null) {
  6932.         retry = config.manifestLoadingMaxRetry;
  6933.         timeout = config.manifestLoadingTimeOut;
  6934.         retryDelay = config.manifestLoadingRetryDelay;
  6935.       } else {
  6936.         retry = config.levelLoadingMaxRetry;
  6937.         timeout = config.levelLoadingTimeOut;
  6938.         retryDelay = config.levelLoadingRetryDelay;
  6939.       }
  6940.       this.loader = typeof config.pLoader !== 'undefined' ? new config.pLoader(config) : new config.loader(config);
  6941.       this.loading = true;
  6942.       this.loader.load(url, '', this.loadsuccess.bind(this), this.loaderror.bind(this), this.loadtimeout.bind(this), timeout, retry, retryDelay);
  6943.     }
  6944.   }, {
  6945.     key: 'resolve',
  6946.     value: function resolve(url, baseUrl) {
  6947.       return _url2.default.buildAbsoluteURL(baseUrl, url);
  6948.     }
  6949.   }, {
  6950.     key: 'parseMasterPlaylist',
  6951.     value: function parseMasterPlaylist(string, baseurl) {
  6952.       var levels = [],
  6953.           result = void 0;
  6954.  
  6955.       // https://regex101.com is your friend
  6956.       var re = /#EXT-X-STREAM-INF:([^\n\r]*)[\r\n]+([^\r\n]+)/g;
  6957.       while ((result = re.exec(string)) != null) {
  6958.         var level = {};
  6959.  
  6960.         var attrs = level.attrs = new _attrList2.default(result[1]);
  6961.         level.url = this.resolve(result[2], baseurl);
  6962.  
  6963.         var resolution = attrs.decimalResolution('RESOLUTION');
  6964.         if (resolution) {
  6965.           level.width = resolution.width;
  6966.           level.height = resolution.height;
  6967.         }
  6968.         level.bitrate = attrs.decimalInteger('AVERAGE-BANDWIDTH') || attrs.decimalInteger('BANDWIDTH');
  6969.         level.name = attrs.NAME;
  6970.  
  6971.         var closedCaptions = attrs.enumeratedString('CLOSED-CAPTIONS');
  6972.  
  6973.         if (closedCaptions) {
  6974.           level.closedCaptions = closedCaptions;
  6975.         }
  6976.  
  6977.         var codecs = attrs.CODECS;
  6978.         if (codecs) {
  6979.           codecs = codecs.split(',');
  6980.           for (var i = 0; i < codecs.length; i++) {
  6981.             var codec = codecs[i];
  6982.             if (codec.indexOf('avc1') !== -1) {
  6983.               level.videoCodec = this.avc1toavcoti(codec);
  6984.             } else {
  6985.               level.audioCodec = codec;
  6986.             }
  6987.           }
  6988.         }
  6989.  
  6990.         levels.push(level);
  6991.       }
  6992.       return levels;
  6993.     }
  6994.  
  6995.     /**
  6996.      * Utility method for parseLevelPlaylist to create an initialization vector for a given segment
  6997.      * @returns {Uint8Array}
  6998.      */
  6999.  
  7000.   }, {
  7001.     key: 'createInitializationVector',
  7002.     value: function createInitializationVector(segmentNumber) {
  7003.       var uint8View = new Uint8Array(16);
  7004.  
  7005.       for (var i = 12; i < 16; i++) {
  7006.         uint8View[i] = segmentNumber >> 8 * (15 - i) & 0xff;
  7007.       }
  7008.  
  7009.       return uint8View;
  7010.     }
  7011.  
  7012.     /**
  7013.      * Utility method for parseLevelPlaylist to get a fragment's decryption data from the currently parsed encryption key data
  7014.      * @param levelkey - a playlist's encryption info
  7015.      * @param segmentNumber - the fragment's segment number
  7016.      * @returns {*} - an object to be applied as a fragment's decryptdata
  7017.      */
  7018.  
  7019.   }, {
  7020.     key: 'fragmentDecryptdataFromLevelkey',
  7021.     value: function fragmentDecryptdataFromLevelkey(levelkey, segmentNumber) {
  7022.       var decryptdata = levelkey;
  7023.  
  7024.       if (levelkey && levelkey.method && levelkey.uri && !levelkey.iv) {
  7025.         decryptdata = this.cloneObj(levelkey);
  7026.         decryptdata.iv = this.createInitializationVector(segmentNumber);
  7027.       }
  7028.  
  7029.       return decryptdata;
  7030.     }
  7031.   }, {
  7032.     key: 'avc1toavcoti',
  7033.     value: function avc1toavcoti(codec) {
  7034.       var result,
  7035.           avcdata = codec.split('.');
  7036.       if (avcdata.length > 2) {
  7037.         result = avcdata.shift() + '.';
  7038.         result += parseInt(avcdata.shift()).toString(16);
  7039.         result += ('000' + parseInt(avcdata.shift()).toString(16)).substr(-4);
  7040.       } else {
  7041.         result = codec;
  7042.       }
  7043.       return result;
  7044.     }
  7045.   }, {
  7046.     key: 'cloneObj',
  7047.     value: function cloneObj(obj) {
  7048.       return JSON.parse(JSON.stringify(obj));
  7049.     }
  7050.   }, {
  7051.     key: 'parseLevelPlaylist',
  7052.     value: function parseLevelPlaylist(string, baseurl, id) {
  7053.       var currentSN = 0,
  7054.           fragdecryptdata,
  7055.           totalduration = 0,
  7056.           level = { url: baseurl, fragments: [], live: true, startSN: 0 },
  7057.           levelkey = { method: null, key: null, iv: null, uri: null },
  7058.           cc = 0,
  7059.           programDateTime = null,
  7060.           frag = null,
  7061.           result,
  7062.           regexp,
  7063.           byteRangeEndOffset,
  7064.           byteRangeStartOffset;
  7065.  
  7066.       regexp = /(?:#EXT-X-(MEDIA-SEQUENCE):(\d+))|(?:#EXT-X-(TARGETDURATION):(\d+))|(?:#EXT-X-(KEY):(.*)[\r\n]+([^#|\r\n]+)?)|(?:#EXT(INF):([\d\.]+)[^\r\n]*([\r\n]+[^#|\r\n]+)?)|(?:#EXT-X-(BYTERANGE):([\d]+[@[\d]*)]*[\r\n]+([^#|\r\n]+)?|(?:#EXT-X-(ENDLIST))|(?:#EXT-X-(DIS)CONTINUITY))|(?:#EXT-X-(PROGRAM-DATE-TIME):(.*))/g;
  7067.       while ((result = regexp.exec(string)) !== null) {
  7068.         result.shift();
  7069.         result = result.filter(function (n) {
  7070.           return n !== undefined;
  7071.         });
  7072.         switch (result[0]) {
  7073.           case 'MEDIA-SEQUENCE':
  7074.             currentSN = level.startSN = parseInt(result[1]);
  7075.             break;
  7076.           case 'TARGETDURATION':
  7077.             level.targetduration = parseFloat(result[1]);
  7078.             break;
  7079.           case 'ENDLIST':
  7080.             level.live = false;
  7081.             break;
  7082.           case 'DIS':
  7083.             cc++;
  7084.             break;
  7085.           case 'BYTERANGE':
  7086.             var params = result[1].split('@');
  7087.             if (params.length === 1) {
  7088.               byteRangeStartOffset = byteRangeEndOffset;
  7089.             } else {
  7090.               byteRangeStartOffset = parseInt(params[1]);
  7091.             }
  7092.             byteRangeEndOffset = parseInt(params[0]) + byteRangeStartOffset;
  7093.             if (frag && !frag.url) {
  7094.               frag.byteRangeStartOffset = byteRangeStartOffset;
  7095.               frag.byteRangeEndOffset = byteRangeEndOffset;
  7096.               frag.url = this.resolve(result[2], baseurl);
  7097.             }
  7098.             break;
  7099.           case 'INF':
  7100.             var duration = parseFloat(result[1]);
  7101.             if (!isNaN(duration)) {
  7102.               var sn = currentSN++;
  7103.               fragdecryptdata = this.fragmentDecryptdataFromLevelkey(levelkey, sn);
  7104.               var url = result[2] ? this.resolve(result[2], baseurl) : null;
  7105.               frag = { url: url, duration: duration, start: totalduration, sn: sn, level: id, cc: cc, byteRangeStartOffset: byteRangeStartOffset, byteRangeEndOffset: byteRangeEndOffset, decryptdata: fragdecryptdata, programDateTime: programDateTime };
  7106.               level.fragments.push(frag);
  7107.               totalduration += duration;
  7108.               byteRangeStartOffset = null;
  7109.               programDateTime = null;
  7110.             }
  7111.             break;
  7112.           case 'KEY':
  7113.             // https://tools.ietf.org/html/draft-pantos-http-live-streaming-08#section-3.4.4
  7114.             var decryptparams = result[1];
  7115.             var keyAttrs = new _attrList2.default(decryptparams);
  7116.             var decryptmethod = keyAttrs.enumeratedString('METHOD'),
  7117.                 decrypturi = keyAttrs.URI,
  7118.                 decryptiv = keyAttrs.hexadecimalInteger('IV');
  7119.             if (decryptmethod) {
  7120.               levelkey = { method: null, key: null, iv: null, uri: null };
  7121.               if (decrypturi && decryptmethod === 'AES-128') {
  7122.                 levelkey.method = decryptmethod;
  7123.                 // URI to get the key
  7124.                 levelkey.uri = this.resolve(decrypturi, baseurl);
  7125.                 levelkey.key = null;
  7126.                 // Initialization Vector (IV)
  7127.                 levelkey.iv = decryptiv;
  7128.               }
  7129.             }
  7130.  
  7131.             //issue #425, applying url and decrypt data in instances where EXT-KEY immediately follow EXT-INF
  7132.             if (frag && !frag.url && result.length >= 3) {
  7133.               frag.url = this.resolve(result[2], baseurl);
  7134.  
  7135.               //we have not moved onto another segment, we are still parsing one
  7136.               fragdecryptdata = this.fragmentDecryptdataFromLevelkey(levelkey, currentSN - 1);
  7137.               frag.decryptdata = fragdecryptdata;
  7138.             }
  7139.             break;
  7140.           case 'PROGRAM-DATE-TIME':
  7141.             programDateTime = new Date(Date.parse(result[1]));
  7142.             break;
  7143.           default:
  7144.             break;
  7145.         }
  7146.       }
  7147.       //logger.log('found ' + level.fragments.length + ' fragments');
  7148.       if (frag && !frag.url) {
  7149.         level.fragments.pop();
  7150.         totalduration -= frag.duration;
  7151.       }
  7152.       level.totalduration = totalduration;
  7153.       level.averagetargetduration = totalduration / level.fragments.length;
  7154.       level.endSN = currentSN - 1;
  7155.       return level;
  7156.     }
  7157.   }, {
  7158.     key: 'loadsuccess',
  7159.     value: function loadsuccess(event, stats) {
  7160.       var target = event.currentTarget,
  7161.           string = target.responseText,
  7162.           url = target.responseURL,
  7163.           id = this.id,
  7164.           id2 = this.id2,
  7165.           hls = this.hls,
  7166.           levels;
  7167.  
  7168.       this.loading = false;
  7169.       // responseURL not supported on some browsers (it is used to detect URL redirection)
  7170.       // data-uri mode also not supported (but no need to detect redirection)
  7171.       if (url === undefined || url.indexOf('data:') === 0) {
  7172.         // fallback to initial URL
  7173.         url = this.url;
  7174.       }
  7175.       stats.tload = performance.now();
  7176.       stats.mtime = new Date(target.getResponseHeader('Last-Modified'));
  7177.       if (string.indexOf('#EXTM3U') === 0) {
  7178.         if (string.indexOf('#EXTINF:') > 0) {
  7179.           // 1 level playlist
  7180.           // if first request, fire manifest loaded event, level will be reloaded afterwards
  7181.           // (this is to have a uniform logic for 1 level/multilevel playlists)
  7182.           if (this.id === null) {
  7183.             hls.trigger(_events2.default.MANIFEST_LOADED, { levels: [{ url: url }], url: url, stats: stats });
  7184.           } else {
  7185.             var levelDetails = this.parseLevelPlaylist(string, url, id);
  7186.             stats.tparsed = performance.now();
  7187.             hls.trigger(_events2.default.LEVEL_LOADED, { details: levelDetails, level: id, id: id2, stats: stats });
  7188.           }
  7189.         } else {
  7190.           levels = this.parseMasterPlaylist(string, url);
  7191.           // multi level playlist, parse level info
  7192.           if (levels.length) {
  7193.             hls.trigger(_events2.default.MANIFEST_LOADED, { levels: levels, url: url, stats: stats });
  7194.           } else {
  7195.             hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.NETWORK_ERROR, details: _errors.ErrorDetails.MANIFEST_PARSING_ERROR, fatal: true, url: url, reason: 'no level found in manifest' });
  7196.           }
  7197.         }
  7198.       } else {
  7199.         hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.NETWORK_ERROR, details: _errors.ErrorDetails.MANIFEST_PARSING_ERROR, fatal: true, url: url, reason: 'no EXTM3U delimiter' });
  7200.       }
  7201.     }
  7202.   }, {
  7203.     key: 'loaderror',
  7204.     value: function loaderror(event) {
  7205.       var details, fatal;
  7206.       if (this.id === null) {
  7207.         details = _errors.ErrorDetails.MANIFEST_LOAD_ERROR;
  7208.         fatal = true;
  7209.       } else {
  7210.         details = _errors.ErrorDetails.LEVEL_LOAD_ERROR;
  7211.         fatal = false;
  7212.       }
  7213.       if (this.loader) {
  7214.         this.loader.abort();
  7215.       }
  7216.       this.loading = false;
  7217.       this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.NETWORK_ERROR, details: details, fatal: fatal, url: this.url, loader: this.loader, response: event.currentTarget, level: this.id, id: this.id2 });
  7218.     }
  7219.   }, {
  7220.     key: 'loadtimeout',
  7221.     value: function loadtimeout() {
  7222.       var details, fatal;
  7223.       if (this.id === null) {
  7224.         details = _errors.ErrorDetails.MANIFEST_LOAD_TIMEOUT;
  7225.         fatal = true;
  7226.       } else {
  7227.         details = _errors.ErrorDetails.LEVEL_LOAD_TIMEOUT;
  7228.         fatal = false;
  7229.       }
  7230.       if (this.loader) {
  7231.         this.loader.abort();
  7232.       }
  7233.       this.loading = false;
  7234.       this.hls.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.NETWORK_ERROR, details: details, fatal: fatal, url: this.url, loader: this.loader, level: this.id, id: this.id2 });
  7235.     }
  7236.   }]);
  7237.  
  7238.   return PlaylistLoader;
  7239. }(_eventHandler2.default);
  7240.  
  7241. exports.default = PlaylistLoader;
  7242.  
  7243. },{"../errors":21,"../event-handler":22,"../events":23,"../utils/attr-list":35,"../utils/url":41}],32:[function(require,module,exports){
  7244. 'use strict';
  7245.  
  7246. Object.defineProperty(exports, "__esModule", {
  7247.   value: true
  7248. });
  7249.  
  7250. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  7251.  
  7252. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  7253.  
  7254. /**
  7255.  * Generate MP4 Box
  7256. */
  7257.  
  7258. //import Hex from '../utils/hex';
  7259.  
  7260. var MP4 = function () {
  7261.   function MP4() {
  7262.     _classCallCheck(this, MP4);
  7263.   }
  7264.  
  7265.   _createClass(MP4, null, [{
  7266.     key: 'init',
  7267.     value: function init() {
  7268.       MP4.types = {
  7269.         avc1: [], // codingname
  7270.         avcC: [],
  7271.         btrt: [],
  7272.         dinf: [],
  7273.         dref: [],
  7274.         esds: [],
  7275.         ftyp: [],
  7276.         hdlr: [],
  7277.         mdat: [],
  7278.         mdhd: [],
  7279.         mdia: [],
  7280.         mfhd: [],
  7281.         minf: [],
  7282.         moof: [],
  7283.         moov: [],
  7284.         mp4a: [],
  7285.         mvex: [],
  7286.         mvhd: [],
  7287.         sdtp: [],
  7288.         stbl: [],
  7289.         stco: [],
  7290.         stsc: [],
  7291.         stsd: [],
  7292.         stsz: [],
  7293.         stts: [],
  7294.         tfdt: [],
  7295.         tfhd: [],
  7296.         traf: [],
  7297.         trak: [],
  7298.         trun: [],
  7299.         trex: [],
  7300.         tkhd: [],
  7301.         vmhd: [],
  7302.         smhd: []
  7303.       };
  7304.  
  7305.       var i;
  7306.       for (i in MP4.types) {
  7307.         if (MP4.types.hasOwnProperty(i)) {
  7308.           MP4.types[i] = [i.charCodeAt(0), i.charCodeAt(1), i.charCodeAt(2), i.charCodeAt(3)];
  7309.         }
  7310.       }
  7311.  
  7312.       var videoHdlr = new Uint8Array([0x00, // version 0
  7313.       0x00, 0x00, 0x00, // flags
  7314.       0x00, 0x00, 0x00, 0x00, // pre_defined
  7315.       0x76, 0x69, 0x64, 0x65, // handler_type: 'vide'
  7316.       0x00, 0x00, 0x00, 0x00, // reserved
  7317.       0x00, 0x00, 0x00, 0x00, // reserved
  7318.       0x00, 0x00, 0x00, 0x00, // reserved
  7319.       0x56, 0x69, 0x64, 0x65, 0x6f, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'VideoHandler'
  7320.       ]);
  7321.  
  7322.       var audioHdlr = new Uint8Array([0x00, // version 0
  7323.       0x00, 0x00, 0x00, // flags
  7324.       0x00, 0x00, 0x00, 0x00, // pre_defined
  7325.       0x73, 0x6f, 0x75, 0x6e, // handler_type: 'soun'
  7326.       0x00, 0x00, 0x00, 0x00, // reserved
  7327.       0x00, 0x00, 0x00, 0x00, // reserved
  7328.       0x00, 0x00, 0x00, 0x00, // reserved
  7329.       0x53, 0x6f, 0x75, 0x6e, 0x64, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'SoundHandler'
  7330.       ]);
  7331.  
  7332.       MP4.HDLR_TYPES = {
  7333.         'video': videoHdlr,
  7334.         'audio': audioHdlr
  7335.       };
  7336.  
  7337.       var dref = new Uint8Array([0x00, // version 0
  7338.       0x00, 0x00, 0x00, // flags
  7339.       0x00, 0x00, 0x00, 0x01, // entry_count
  7340.       0x00, 0x00, 0x00, 0x0c, // entry_size
  7341.       0x75, 0x72, 0x6c, 0x20, // 'url' type
  7342.       0x00, // version 0
  7343.       0x00, 0x00, 0x01 // entry_flags
  7344.       ]);
  7345.  
  7346.       var stco = new Uint8Array([0x00, // version
  7347.       0x00, 0x00, 0x00, // flags
  7348.       0x00, 0x00, 0x00, 0x00 // entry_count
  7349.       ]);
  7350.  
  7351.       MP4.STTS = MP4.STSC = MP4.STCO = stco;
  7352.  
  7353.       MP4.STSZ = new Uint8Array([0x00, // version
  7354.       0x00, 0x00, 0x00, // flags
  7355.       0x00, 0x00, 0x00, 0x00, // sample_size
  7356.       0x00, 0x00, 0x00, 0x00]);
  7357.       // sample_count
  7358.       MP4.VMHD = new Uint8Array([0x00, // version
  7359.       0x00, 0x00, 0x01, // flags
  7360.       0x00, 0x00, // graphicsmode
  7361.       0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // opcolor
  7362.       ]);
  7363.       MP4.SMHD = new Uint8Array([0x00, // version
  7364.       0x00, 0x00, 0x00, // flags
  7365.       0x00, 0x00, // balance
  7366.       0x00, 0x00 // reserved
  7367.       ]);
  7368.  
  7369.       MP4.STSD = new Uint8Array([0x00, // version 0
  7370.       0x00, 0x00, 0x00, // flags
  7371.       0x00, 0x00, 0x00, 0x01]); // entry_count
  7372.  
  7373.       var majorBrand = new Uint8Array([105, 115, 111, 109]); // isom
  7374.       var avc1Brand = new Uint8Array([97, 118, 99, 49]); // avc1
  7375.       var minorVersion = new Uint8Array([0, 0, 0, 1]);
  7376.  
  7377.       MP4.FTYP = MP4.box(MP4.types.ftyp, majorBrand, minorVersion, majorBrand, avc1Brand);
  7378.       MP4.DINF = MP4.box(MP4.types.dinf, MP4.box(MP4.types.dref, dref));
  7379.     }
  7380.   }, {
  7381.     key: 'box',
  7382.     value: function box(type) {
  7383.       var payload = Array.prototype.slice.call(arguments, 1),
  7384.           size = 8,
  7385.           i = payload.length,
  7386.           len = i,
  7387.           result;
  7388.       // calculate the total size we need to allocate
  7389.       while (i--) {
  7390.         size += payload[i].byteLength;
  7391.       }
  7392.       result = new Uint8Array(size);
  7393.       result[0] = size >> 24 & 0xff;
  7394.       result[1] = size >> 16 & 0xff;
  7395.       result[2] = size >> 8 & 0xff;
  7396.       result[3] = size & 0xff;
  7397.       result.set(type, 4);
  7398.       // copy the payload into the result
  7399.       for (i = 0, size = 8; i < len; i++) {
  7400.         // copy payload[i] array @ offset size
  7401.         result.set(payload[i], size);
  7402.         size += payload[i].byteLength;
  7403.       }
  7404.       return result;
  7405.     }
  7406.   }, {
  7407.     key: 'hdlr',
  7408.     value: function hdlr(type) {
  7409.       return MP4.box(MP4.types.hdlr, MP4.HDLR_TYPES[type]);
  7410.     }
  7411.   }, {
  7412.     key: 'mdat',
  7413.     value: function mdat(data) {
  7414.       return MP4.box(MP4.types.mdat, data);
  7415.     }
  7416.   }, {
  7417.     key: 'mdhd',
  7418.     value: function mdhd(timescale, duration) {
  7419.       duration *= timescale;
  7420.       return MP4.box(MP4.types.mdhd, new Uint8Array([0x00, // version 0
  7421.       0x00, 0x00, 0x00, // flags
  7422.       0x00, 0x00, 0x00, 0x02, // creation_time
  7423.       0x00, 0x00, 0x00, 0x03, // modification_time
  7424.       timescale >> 24 & 0xFF, timescale >> 16 & 0xFF, timescale >> 8 & 0xFF, timescale & 0xFF, // timescale
  7425.       duration >> 24, duration >> 16 & 0xFF, duration >> 8 & 0xFF, duration & 0xFF, // duration
  7426.       0x55, 0xc4, // 'und' language (undetermined)
  7427.       0x00, 0x00]));
  7428.     }
  7429.   }, {
  7430.     key: 'mdia',
  7431.     value: function mdia(track) {
  7432.       return MP4.box(MP4.types.mdia, MP4.mdhd(track.timescale, track.duration), MP4.hdlr(track.type), MP4.minf(track));
  7433.     }
  7434.   }, {
  7435.     key: 'mfhd',
  7436.     value: function mfhd(sequenceNumber) {
  7437.       return MP4.box(MP4.types.mfhd, new Uint8Array([0x00, 0x00, 0x00, 0x00, // flags
  7438.       sequenceNumber >> 24, sequenceNumber >> 16 & 0xFF, sequenceNumber >> 8 & 0xFF, sequenceNumber & 0xFF]));
  7439.     }
  7440.   }, {
  7441.     key: 'minf',
  7442.     // sequence_number
  7443.     value: function minf(track) {
  7444.       if (track.type === 'audio') {
  7445.         return MP4.box(MP4.types.minf, MP4.box(MP4.types.smhd, MP4.SMHD), MP4.DINF, MP4.stbl(track));
  7446.       } else {
  7447.         return MP4.box(MP4.types.minf, MP4.box(MP4.types.vmhd, MP4.VMHD), MP4.DINF, MP4.stbl(track));
  7448.       }
  7449.     }
  7450.   }, {
  7451.     key: 'moof',
  7452.     value: function moof(sn, baseMediaDecodeTime, track) {
  7453.       return MP4.box(MP4.types.moof, MP4.mfhd(sn), MP4.traf(track, baseMediaDecodeTime));
  7454.     }
  7455.     /**
  7456.      * @param tracks... (optional) {array} the tracks associated with this movie
  7457.      */
  7458.  
  7459.   }, {
  7460.     key: 'moov',
  7461.     value: function moov(tracks) {
  7462.       var i = tracks.length,
  7463.           boxes = [];
  7464.  
  7465.       while (i--) {
  7466.         boxes[i] = MP4.trak(tracks[i]);
  7467.       }
  7468.  
  7469.       return MP4.box.apply(null, [MP4.types.moov, MP4.mvhd(tracks[0].timescale, tracks[0].duration)].concat(boxes).concat(MP4.mvex(tracks)));
  7470.     }
  7471.   }, {
  7472.     key: 'mvex',
  7473.     value: function mvex(tracks) {
  7474.       var i = tracks.length,
  7475.           boxes = [];
  7476.  
  7477.       while (i--) {
  7478.         boxes[i] = MP4.trex(tracks[i]);
  7479.       }
  7480.       return MP4.box.apply(null, [MP4.types.mvex].concat(boxes));
  7481.     }
  7482.   }, {
  7483.     key: 'mvhd',
  7484.     value: function mvhd(timescale, duration) {
  7485.       duration *= timescale;
  7486.       var bytes = new Uint8Array([0x00, // version 0
  7487.       0x00, 0x00, 0x00, // flags
  7488.       0x00, 0x00, 0x00, 0x01, // creation_time
  7489.       0x00, 0x00, 0x00, 0x02, // modification_time
  7490.       timescale >> 24 & 0xFF, timescale >> 16 & 0xFF, timescale >> 8 & 0xFF, timescale & 0xFF, // timescale
  7491.       duration >> 24 & 0xFF, duration >> 16 & 0xFF, duration >> 8 & 0xFF, duration & 0xFF, // duration
  7492.       0x00, 0x01, 0x00, 0x00, // 1.0 rate
  7493.       0x01, 0x00, // 1.0 volume
  7494.       0x00, 0x00, // reserved
  7495.       0x00, 0x00, 0x00, 0x00, // reserved
  7496.       0x00, 0x00, 0x00, 0x00, // reserved
  7497.       0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, // transformation: unity matrix
  7498.       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // pre_defined
  7499.       0xff, 0xff, 0xff, 0xff // next_track_ID
  7500.       ]);
  7501.       return MP4.box(MP4.types.mvhd, bytes);
  7502.     }
  7503.   }, {
  7504.     key: 'sdtp',
  7505.     value: function sdtp(track) {
  7506.       var samples = track.samples || [],
  7507.           bytes = new Uint8Array(4 + samples.length),
  7508.           flags,
  7509.           i;
  7510.       // leave the full box header (4 bytes) all zero
  7511.       // write the sample table
  7512.       for (i = 0; i < samples.length; i++) {
  7513.         flags = samples[i].flags;
  7514.         bytes[i + 4] = flags.dependsOn << 4 | flags.isDependedOn << 2 | flags.hasRedundancy;
  7515.       }
  7516.  
  7517.       return MP4.box(MP4.types.sdtp, bytes);
  7518.     }
  7519.   }, {
  7520.     key: 'stbl',
  7521.     value: function stbl(track) {
  7522.       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));
  7523.     }
  7524.   }, {
  7525.     key: 'avc1',
  7526.     value: function avc1(track) {
  7527.       var sps = [],
  7528.           pps = [],
  7529.           i,
  7530.           data,
  7531.           len;
  7532.       // assemble the SPSs
  7533.  
  7534.       for (i = 0; i < track.sps.length; i++) {
  7535.         data = track.sps[i];
  7536.         len = data.byteLength;
  7537.         sps.push(len >>> 8 & 0xFF);
  7538.         sps.push(len & 0xFF);
  7539.         sps = sps.concat(Array.prototype.slice.call(data)); // SPS
  7540.       }
  7541.  
  7542.       // assemble the PPSs
  7543.       for (i = 0; i < track.pps.length; i++) {
  7544.         data = track.pps[i];
  7545.         len = data.byteLength;
  7546.         pps.push(len >>> 8 & 0xFF);
  7547.         pps.push(len & 0xFF);
  7548.         pps = pps.concat(Array.prototype.slice.call(data));
  7549.       }
  7550.  
  7551.       var avcc = MP4.box(MP4.types.avcC, new Uint8Array([0x01, // version
  7552.       sps[3], // profile
  7553.       sps[4], // profile compat
  7554.       sps[5], // level
  7555.       0xfc | 3, // lengthSizeMinusOne, hard-coded to 4 bytes
  7556.       0xE0 | track.sps.length // 3bit reserved (111) + numOfSequenceParameterSets
  7557.       ].concat(sps).concat([track.pps.length // numOfPictureParameterSets
  7558.       ]).concat(pps))),
  7559.           // "PPS"
  7560.       width = track.width,
  7561.           height = track.height;
  7562.       //console.log('avcc:' + Hex.hexDump(avcc));
  7563.       return MP4.box(MP4.types.avc1, new Uint8Array([0x00, 0x00, 0x00, // reserved
  7564.       0x00, 0x00, 0x00, // reserved
  7565.       0x00, 0x01, // data_reference_index
  7566.       0x00, 0x00, // pre_defined
  7567.       0x00, 0x00, // reserved
  7568.       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // pre_defined
  7569.       width >> 8 & 0xFF, width & 0xff, // width
  7570.       height >> 8 & 0xFF, height & 0xff, // height
  7571.       0x00, 0x48, 0x00, 0x00, // horizresolution
  7572.       0x00, 0x48, 0x00, 0x00, // vertresolution
  7573.       0x00, 0x00, 0x00, 0x00, // reserved
  7574.       0x00, 0x01, // frame_count
  7575.       0x12, 0x64, 0x61, 0x69, 0x6C, //dailymotion/hls.js
  7576.       0x79, 0x6D, 0x6F, 0x74, 0x69, 0x6F, 0x6E, 0x2F, 0x68, 0x6C, 0x73, 0x2E, 0x6A, 0x73, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // compressorname
  7577.       0x00, 0x18, // depth = 24
  7578.       0x11, 0x11]), // pre_defined = -1
  7579.       avcc, MP4.box(MP4.types.btrt, new Uint8Array([0x00, 0x1c, 0x9c, 0x80, // bufferSizeDB
  7580.       0x00, 0x2d, 0xc6, 0xc0, // maxBitrate
  7581.       0x00, 0x2d, 0xc6, 0xc0])) // avgBitrate
  7582.       );
  7583.     }
  7584.   }, {
  7585.     key: 'esds',
  7586.     value: function esds(track) {
  7587.       var configlen = track.config.length;
  7588.       return new Uint8Array([0x00, // version 0
  7589.       0x00, 0x00, 0x00, // flags
  7590.  
  7591.       0x03, // descriptor_type
  7592.       0x17 + configlen, // length
  7593.       0x00, 0x01, //es_id
  7594.       0x00, // stream_priority
  7595.  
  7596.       0x04, // descriptor_type
  7597.       0x0f + configlen, // length
  7598.       0x40, //codec : mpeg4_audio
  7599.       0x15, // stream_type
  7600.       0x00, 0x00, 0x00, // buffer_size
  7601.       0x00, 0x00, 0x00, 0x00, // maxBitrate
  7602.       0x00, 0x00, 0x00, 0x00, // avgBitrate
  7603.  
  7604.       0x05 // descriptor_type
  7605.       ].concat([configlen]).concat(track.config).concat([0x06, 0x01, 0x02])); // GASpecificConfig)); // length + audio config descriptor
  7606.     }
  7607.   }, {
  7608.     key: 'mp4a',
  7609.     value: function mp4a(track) {
  7610.       var audiosamplerate = track.audiosamplerate;
  7611.       return MP4.box(MP4.types.mp4a, new Uint8Array([0x00, 0x00, 0x00, // reserved
  7612.       0x00, 0x00, 0x00, // reserved
  7613.       0x00, 0x01, // data_reference_index
  7614.       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
  7615.       0x00, track.channelCount, // channelcount
  7616.       0x00, 0x10, // sampleSize:16bits
  7617.       0x00, 0x00, 0x00, 0x00, // reserved2
  7618.       audiosamplerate >> 8 & 0xFF, audiosamplerate & 0xff, //
  7619.       0x00, 0x00]), MP4.box(MP4.types.esds, MP4.esds(track)));
  7620.     }
  7621.   }, {
  7622.     key: 'stsd',
  7623.     value: function stsd(track) {
  7624.       if (track.type === 'audio') {
  7625.         return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp4a(track));
  7626.       } else {
  7627.         return MP4.box(MP4.types.stsd, MP4.STSD, MP4.avc1(track));
  7628.       }
  7629.     }
  7630.   }, {
  7631.     key: 'tkhd',
  7632.     value: function tkhd(track) {
  7633.       var id = track.id,
  7634.           duration = track.duration * track.timescale,
  7635.           width = track.width,
  7636.           height = track.height;
  7637.       return MP4.box(MP4.types.tkhd, new Uint8Array([0x00, // version 0
  7638.       0x00, 0x00, 0x07, // flags
  7639.       0x00, 0x00, 0x00, 0x00, // creation_time
  7640.       0x00, 0x00, 0x00, 0x00, // modification_time
  7641.       id >> 24 & 0xFF, id >> 16 & 0xFF, id >> 8 & 0xFF, id & 0xFF, // track_ID
  7642.       0x00, 0x00, 0x00, 0x00, // reserved
  7643.       duration >> 24, duration >> 16 & 0xFF, duration >> 8 & 0xFF, duration & 0xFF, // duration
  7644.       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
  7645.       0x00, 0x00, // layer
  7646.       0x00, 0x00, // alternate_group
  7647.       0x00, 0x00, // non-audio track volume
  7648.       0x00, 0x00, // reserved
  7649.       0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, // transformation: unity matrix
  7650.       width >> 8 & 0xFF, width & 0xFF, 0x00, 0x00, // width
  7651.       height >> 8 & 0xFF, height & 0xFF, 0x00, 0x00 // height
  7652.       ]));
  7653.     }
  7654.   }, {
  7655.     key: 'traf',
  7656.     value: function traf(track, baseMediaDecodeTime) {
  7657.       var sampleDependencyTable = MP4.sdtp(track),
  7658.           id = track.id;
  7659.       return MP4.box(MP4.types.traf, MP4.box(MP4.types.tfhd, new Uint8Array([0x00, // version 0
  7660.       0x00, 0x00, 0x00, // flags
  7661.       id >> 24, id >> 16 & 0XFF, id >> 8 & 0XFF, id & 0xFF])), // track_ID
  7662.       MP4.box(MP4.types.tfdt, new Uint8Array([0x00, // version 0
  7663.       0x00, 0x00, 0x00, // flags
  7664.       baseMediaDecodeTime >> 24, baseMediaDecodeTime >> 16 & 0XFF, baseMediaDecodeTime >> 8 & 0XFF, baseMediaDecodeTime & 0xFF])), // baseMediaDecodeTime
  7665.       MP4.trun(track, sampleDependencyTable.length + 16 + // tfhd
  7666.       16 + // tfdt
  7667.       8 + // traf header
  7668.       16 + // mfhd
  7669.       8 + // moof header
  7670.       8), // mdat header
  7671.       sampleDependencyTable);
  7672.     }
  7673.  
  7674.     /**
  7675.      * Generate a track box.
  7676.      * @param track {object} a track definition
  7677.      * @return {Uint8Array} the track box
  7678.      */
  7679.  
  7680.   }, {
  7681.     key: 'trak',
  7682.     value: function trak(track) {
  7683.       track.duration = track.duration || 0xffffffff;
  7684.       return MP4.box(MP4.types.trak, MP4.tkhd(track), MP4.mdia(track));
  7685.     }
  7686.   }, {
  7687.     key: 'trex',
  7688.     value: function trex(track) {
  7689.       var id = track.id;
  7690.       return MP4.box(MP4.types.trex, new Uint8Array([0x00, // version 0
  7691.       0x00, 0x00, 0x00, // flags
  7692.       id >> 24, id >> 16 & 0XFF, id >> 8 & 0XFF, id & 0xFF, // track_ID
  7693.       0x00, 0x00, 0x00, 0x01, // default_sample_description_index
  7694.       0x00, 0x00, 0x00, 0x00, // default_sample_duration
  7695.       0x00, 0x00, 0x00, 0x00, // default_sample_size
  7696.       0x00, 0x01, 0x00, 0x01 // default_sample_flags
  7697.       ]));
  7698.     }
  7699.   }, {
  7700.     key: 'trun',
  7701.     value: function trun(track, offset) {
  7702.       var samples = track.samples || [],
  7703.           len = samples.length,
  7704.           arraylen = 12 + 16 * len,
  7705.           array = new Uint8Array(arraylen),
  7706.           i,
  7707.           sample,
  7708.           duration,
  7709.           size,
  7710.           flags,
  7711.           cts;
  7712.       offset += 8 + arraylen;
  7713.       array.set([0x00, // version 0
  7714.       0x00, 0x0f, 0x01, // flags
  7715.       len >>> 24 & 0xFF, len >>> 16 & 0xFF, len >>> 8 & 0xFF, len & 0xFF, // sample_count
  7716.       offset >>> 24 & 0xFF, offset >>> 16 & 0xFF, offset >>> 8 & 0xFF, offset & 0xFF // data_offset
  7717.       ], 0);
  7718.       for (i = 0; i < len; i++) {
  7719.         sample = samples[i];
  7720.         duration = sample.duration;
  7721.         size = sample.size;
  7722.         flags = sample.flags;
  7723.         cts = sample.cts;
  7724.         array.set([duration >>> 24 & 0xFF, duration >>> 16 & 0xFF, duration >>> 8 & 0xFF, duration & 0xFF, // sample_duration
  7725.         size >>> 24 & 0xFF, size >>> 16 & 0xFF, size >>> 8 & 0xFF, size & 0xFF, // sample_size
  7726.         flags.isLeading << 2 | flags.dependsOn, flags.isDependedOn << 6 | flags.hasRedundancy << 4 | flags.paddingValue << 1 | flags.isNonSync, flags.degradPrio & 0xF0 << 8, flags.degradPrio & 0x0F, // sample_flags
  7727.         cts >>> 24 & 0xFF, cts >>> 16 & 0xFF, cts >>> 8 & 0xFF, cts & 0xFF // sample_composition_time_offset
  7728.         ], 12 + 16 * i);
  7729.       }
  7730.       return MP4.box(MP4.types.trun, array);
  7731.     }
  7732.   }, {
  7733.     key: 'initSegment',
  7734.     value: function initSegment(tracks) {
  7735.       if (!MP4.types) {
  7736.         MP4.init();
  7737.       }
  7738.       var movie = MP4.moov(tracks),
  7739.           result;
  7740.       result = new Uint8Array(MP4.FTYP.byteLength + movie.byteLength);
  7741.       result.set(MP4.FTYP);
  7742.       result.set(movie, MP4.FTYP.byteLength);
  7743.       return result;
  7744.     }
  7745.   }]);
  7746.  
  7747.   return MP4;
  7748. }();
  7749.  
  7750. exports.default = MP4;
  7751.  
  7752. },{}],33:[function(require,module,exports){
  7753. 'use strict';
  7754.  
  7755. Object.defineProperty(exports, "__esModule", {
  7756.   value: true
  7757. });
  7758.  
  7759. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /**
  7760.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       * fMP4 remuxer
  7761.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      */
  7762.  
  7763. var _aac = require('../helper/aac');
  7764.  
  7765. var _aac2 = _interopRequireDefault(_aac);
  7766.  
  7767. var _events = require('../events');
  7768.  
  7769. var _events2 = _interopRequireDefault(_events);
  7770.  
  7771. var _logger = require('../utils/logger');
  7772.  
  7773. var _mp4Generator = require('../remux/mp4-generator');
  7774.  
  7775. var _mp4Generator2 = _interopRequireDefault(_mp4Generator);
  7776.  
  7777. var _errors = require('../errors');
  7778.  
  7779. require('../utils/polyfill');
  7780.  
  7781. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  7782.  
  7783. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  7784.  
  7785. var MP4Remuxer = function () {
  7786.   function MP4Remuxer(observer, config) {
  7787.     _classCallCheck(this, MP4Remuxer);
  7788.  
  7789.     this.observer = observer;
  7790.     this.config = config;
  7791.     this.ISGenerated = false;
  7792.     this.PES2MP4SCALEFACTOR = 4;
  7793.     this.PES_TIMESCALE = 90000;
  7794.     this.MP4_TIMESCALE = this.PES_TIMESCALE / this.PES2MP4SCALEFACTOR;
  7795.   }
  7796.  
  7797.   _createClass(MP4Remuxer, [{
  7798.     key: 'destroy',
  7799.     value: function destroy() {}
  7800.   }, {
  7801.     key: 'insertDiscontinuity',
  7802.     value: function insertDiscontinuity() {
  7803.       this._initPTS = this._initDTS = this.nextAacPts = this.nextAvcDts = undefined;
  7804.     }
  7805.   }, {
  7806.     key: 'switchLevel',
  7807.     value: function switchLevel() {
  7808.       this.ISGenerated = false;
  7809.     }
  7810.   }, {
  7811.     key: 'remux',
  7812.     value: function remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous) {
  7813.       // generate Init Segment if needed
  7814.       if (!this.ISGenerated) {
  7815.         this.generateIS(audioTrack, videoTrack, timeOffset);
  7816.       }
  7817.  
  7818.       if (this.ISGenerated) {
  7819.         // Purposefully remuxing audio before video, so that remuxVideo can use nextAacPts, which is
  7820.         // calculated in remuxAudio.
  7821.         //logger.log('nb AAC samples:' + audioTrack.samples.length);
  7822.         if (audioTrack.samples.length) {
  7823.           var audioData = this.remuxAudio(audioTrack, timeOffset, contiguous);
  7824.           //logger.log('nb AVC samples:' + videoTrack.samples.length);
  7825.           if (videoTrack.samples.length) {
  7826.             var audioTrackLength = void 0;
  7827.             if (audioData) {
  7828.               audioTrackLength = audioData.endPTS - audioData.startPTS;
  7829.             }
  7830.             this.remuxVideo(videoTrack, timeOffset, contiguous, audioTrackLength);
  7831.           }
  7832.         } else {
  7833.           var videoData = void 0;
  7834.           //logger.log('nb AVC samples:' + videoTrack.samples.length);
  7835.           if (videoTrack.samples.length) {
  7836.             videoData = this.remuxVideo(videoTrack, timeOffset, contiguous);
  7837.           }
  7838.           if (videoData && audioTrack.codec) {
  7839.             this.remuxEmptyAudio(audioTrack, timeOffset, contiguous, videoData);
  7840.           }
  7841.         }
  7842.       }
  7843.       //logger.log('nb ID3 samples:' + audioTrack.samples.length);
  7844.       if (id3Track.samples.length) {
  7845.         this.remuxID3(id3Track, timeOffset);
  7846.       }
  7847.       //logger.log('nb ID3 samples:' + audioTrack.samples.length);
  7848.       if (textTrack.samples.length) {
  7849.         this.remuxText(textTrack, timeOffset);
  7850.       }
  7851.       //notify end of parsing
  7852.       this.observer.trigger(_events2.default.FRAG_PARSED);
  7853.     }
  7854.   }, {
  7855.     key: 'generateIS',
  7856.     value: function generateIS(audioTrack, videoTrack, timeOffset) {
  7857.       var observer = this.observer,
  7858.           audioSamples = audioTrack.samples,
  7859.           videoSamples = videoTrack.samples,
  7860.           pesTimeScale = this.PES_TIMESCALE,
  7861.           tracks = {},
  7862.           data = { tracks: tracks, unique: false },
  7863.           computePTSDTS = this._initPTS === undefined,
  7864.           initPTS,
  7865.           initDTS;
  7866.  
  7867.       if (computePTSDTS) {
  7868.         initPTS = initDTS = Infinity;
  7869.       }
  7870.       if (audioTrack.config && audioSamples.length) {
  7871.         audioTrack.timescale = audioTrack.audiosamplerate;
  7872.         // MP4 duration (track duration in seconds multiplied by timescale) is coded on 32 bits
  7873.         // we know that each AAC sample contains 1024 frames....
  7874.         // in order to avoid overflowing the 32 bit counter for large duration, we use smaller timescale (timescale/gcd)
  7875.         // we just need to ensure that AAC sample duration will still be an integer (will be 1024/gcd)
  7876.         if (audioTrack.timescale * audioTrack.duration > Math.pow(2, 32)) {
  7877.           (function () {
  7878.             var greatestCommonDivisor = function greatestCommonDivisor(a, b) {
  7879.               if (!b) {
  7880.                 return a;
  7881.               }
  7882.               return greatestCommonDivisor(b, a % b);
  7883.             };
  7884.             audioTrack.timescale = audioTrack.audiosamplerate / greatestCommonDivisor(audioTrack.audiosamplerate, 1024);
  7885.           })();
  7886.         }
  7887.         _logger.logger.log('audio mp4 timescale :' + audioTrack.timescale);
  7888.         tracks.audio = {
  7889.           container: 'audio/mp4',
  7890.           codec: audioTrack.codec,
  7891.           initSegment: _mp4Generator2.default.initSegment([audioTrack]),
  7892.           metadata: {
  7893.             channelCount: audioTrack.channelCount
  7894.           }
  7895.         };
  7896.         if (computePTSDTS) {
  7897.           // remember first PTS of this demuxing context. for audio, PTS + DTS ...
  7898.           initPTS = initDTS = audioSamples[0].pts - pesTimeScale * timeOffset;
  7899.         }
  7900.       }
  7901.  
  7902.       if (videoTrack.sps && videoTrack.pps && videoSamples.length) {
  7903.         videoTrack.timescale = this.MP4_TIMESCALE;
  7904.         tracks.video = {
  7905.           container: 'video/mp4',
  7906.           codec: videoTrack.codec,
  7907.           initSegment: _mp4Generator2.default.initSegment([videoTrack]),
  7908.           metadata: {
  7909.             width: videoTrack.width,
  7910.             height: videoTrack.height
  7911.           }
  7912.         };
  7913.         if (computePTSDTS) {
  7914.           initPTS = Math.min(initPTS, videoSamples[0].pts - pesTimeScale * timeOffset);
  7915.           initDTS = Math.min(initDTS, videoSamples[0].dts - pesTimeScale * timeOffset);
  7916.         }
  7917.       }
  7918.  
  7919.       if (Object.keys(tracks).length) {
  7920.         observer.trigger(_events2.default.FRAG_PARSING_INIT_SEGMENT, data);
  7921.         this.ISGenerated = true;
  7922.         if (computePTSDTS) {
  7923.           this._initPTS = initPTS;
  7924.           this._initDTS = initDTS;
  7925.         }
  7926.       } else {
  7927.         observer.trigger(_events2.default.ERROR, { type: _errors.ErrorTypes.MEDIA_ERROR, details: _errors.ErrorDetails.FRAG_PARSING_ERROR, fatal: false, reason: 'no audio/video samples found' });
  7928.       }
  7929.     }
  7930.   }, {
  7931.     key: 'remuxVideo',
  7932.     value: function remuxVideo(track, timeOffset, contiguous, audioTrackLength) {
  7933.       var offset = 8,
  7934.           pesTimeScale = this.PES_TIMESCALE,
  7935.           pes2mp4ScaleFactor = this.PES2MP4SCALEFACTOR,
  7936.           mp4SampleDuration,
  7937.           mdat,
  7938.           moof,
  7939.           firstPTS,
  7940.           firstDTS,
  7941.           nextDTS,
  7942.           lastPTS,
  7943.           lastDTS,
  7944.           inputSamples = track.samples,
  7945.           outputSamples = [];
  7946.  
  7947.       // PTS is coded on 33bits, and can loop from -2^32 to 2^32
  7948.       // PTSNormalize will make PTS/DTS value monotonic, we use last known DTS value as reference value
  7949.       var nextAvcDts = void 0;
  7950.       if (contiguous) {
  7951.         // if parsed fragment is contiguous with last one, let's use last DTS value as reference
  7952.         nextAvcDts = this.nextAvcDts;
  7953.       } else {
  7954.         // if not contiguous, let's use target timeOffset
  7955.         nextAvcDts = timeOffset * pesTimeScale;
  7956.       }
  7957.  
  7958.       // compute first DTS and last DTS, normalize them against reference value
  7959.       var sample = inputSamples[0];
  7960.       firstDTS = Math.max(this._PTSNormalize(sample.dts, nextAvcDts) - this._initDTS, 0);
  7961.       firstPTS = Math.max(this._PTSNormalize(sample.pts, nextAvcDts) - this._initDTS, 0);
  7962.  
  7963.       // check timestamp continuity accross consecutive fragments (this is to remove inter-fragment gap/hole)
  7964.       var delta = Math.round((firstDTS - nextAvcDts) / 90);
  7965.       // if fragment are contiguous, detect hole/overlapping between fragments
  7966.       if (contiguous) {
  7967.         if (delta) {
  7968.           if (delta > 1) {
  7969.             _logger.logger.log('AVC:' + delta + ' ms hole between fragments detected,filling it');
  7970.           } else if (delta < -1) {
  7971.             _logger.logger.log('AVC:' + -delta + ' ms overlapping between fragments detected');
  7972.           }
  7973.           // remove hole/gap : set DTS to next expected DTS
  7974.           firstDTS = nextAvcDts;
  7975.           inputSamples[0].dts = firstDTS + this._initDTS;
  7976.           // offset PTS as well, ensure that PTS is smaller or equal than new DTS
  7977.           firstPTS = Math.max(firstPTS - delta, nextAvcDts);
  7978.           inputSamples[0].pts = firstPTS + this._initDTS;
  7979.           _logger.logger.log('Video/PTS/DTS adjusted: ' + firstPTS + '/' + firstDTS + ',delta:' + delta);
  7980.         }
  7981.       }
  7982.       nextDTS = firstDTS;
  7983.  
  7984.       // compute lastPTS/lastDTS
  7985.       sample = inputSamples[inputSamples.length - 1];
  7986.       lastDTS = Math.max(this._PTSNormalize(sample.dts, nextAvcDts) - this._initDTS, 0);
  7987.       lastPTS = Math.max(this._PTSNormalize(sample.pts, nextAvcDts) - this._initDTS, 0);
  7988.       lastPTS = Math.max(lastPTS, lastDTS);
  7989.  
  7990.       var vendor = navigator.vendor,
  7991.           userAgent = navigator.userAgent,
  7992.           isSafari = vendor && vendor.indexOf('Apple') > -1 && userAgent && !userAgent.match('CriOS');
  7993.  
  7994.       // on Safari let's signal the same sample duration for all samples
  7995.       // sample duration (as expected by trun MP4 boxes), should be the delta between sample DTS
  7996.       // set this constant duration as being the avg delta between consecutive DTS.
  7997.       if (isSafari) {
  7998.         mp4SampleDuration = Math.round((lastDTS - firstDTS) / (pes2mp4ScaleFactor * (inputSamples.length - 1)));
  7999.       }
  8000.  
  8001.       // normalize all PTS/DTS now ...
  8002.       for (var i = 0; i < inputSamples.length; i++) {
  8003.         var _sample = inputSamples[i];
  8004.         if (isSafari) {
  8005.           // sample DTS is computed using a constant decoding offset (mp4SampleDuration) between samples
  8006.           _sample.dts = firstDTS + i * pes2mp4ScaleFactor * mp4SampleDuration;
  8007.         } else {
  8008.           // ensure sample monotonic DTS
  8009.           _sample.dts = Math.max(this._PTSNormalize(_sample.dts, nextAvcDts) - this._initDTS, firstDTS);
  8010.           // ensure dts is a multiple of scale factor to avoid rounding issues
  8011.           _sample.dts = Math.round(_sample.dts / pes2mp4ScaleFactor) * pes2mp4ScaleFactor;
  8012.         }
  8013.         // we normalize PTS against nextAvcDts, we also substract initDTS (some streams don't start @ PTS O)
  8014.         // and we ensure that computed value is greater or equal than sample DTS
  8015.         _sample.pts = Math.max(this._PTSNormalize(_sample.pts, nextAvcDts) - this._initDTS, _sample.dts);
  8016.         // ensure pts is a multiple of scale factor to avoid rounding issues
  8017.         _sample.pts = Math.round(_sample.pts / pes2mp4ScaleFactor) * pes2mp4ScaleFactor;
  8018.       }
  8019.  
  8020.       /* concatenate the video data and construct the mdat in place
  8021.         (need 8 more bytes to fill length and mpdat type) */
  8022.       mdat = new Uint8Array(track.len + 4 * track.nbNalu + 8);
  8023.       var view = new DataView(mdat.buffer);
  8024.       view.setUint32(0, mdat.byteLength);
  8025.       mdat.set(_mp4Generator2.default.types.mdat, 4);
  8026.  
  8027.       for (var _i = 0; _i < inputSamples.length; _i++) {
  8028.         var avcSample = inputSamples[_i],
  8029.             mp4SampleLength = 0,
  8030.             compositionTimeOffset = void 0;
  8031.         // convert NALU bitstream to MP4 format (prepend NALU with size field)
  8032.         while (avcSample.units.units.length) {
  8033.           var unit = avcSample.units.units.shift();
  8034.           view.setUint32(offset, unit.data.byteLength);
  8035.           offset += 4;
  8036.           mdat.set(unit.data, offset);
  8037.           offset += unit.data.byteLength;
  8038.           mp4SampleLength += 4 + unit.data.byteLength;
  8039.         }
  8040.  
  8041.         if (!isSafari) {
  8042.           // expected sample duration is the Decoding Timestamp diff of consecutive samples
  8043.           if (_i < inputSamples.length - 1) {
  8044.             mp4SampleDuration = inputSamples[_i + 1].dts - avcSample.dts;
  8045.           } else {
  8046.             var config = this.config,
  8047.                 lastFrameDuration = avcSample.dts - inputSamples[_i > 0 ? _i - 1 : _i].dts;
  8048.             if (config.stretchShortVideoTrack) {
  8049.               // In some cases, a segment's audio track duration may exceed the video track duration.
  8050.               // Since we've already remuxed audio, and we know how long the audio track is, we look to
  8051.               // see if the delta to the next segment is longer than the minimum of maxBufferHole and
  8052.               // maxSeekHole. If so, playback would potentially get stuck, so we artificially inflate
  8053.               // the duration of the last frame to minimize any potential gap between segments.
  8054.               var maxBufferHole = config.maxBufferHole,
  8055.                   maxSeekHole = config.maxSeekHole,
  8056.                   gapTolerance = Math.floor(Math.min(maxBufferHole, maxSeekHole) * pesTimeScale),
  8057.                   deltaToFrameEnd = (audioTrackLength ? firstPTS + audioTrackLength * pesTimeScale : this.nextAacPts) - avcSample.pts;
  8058.               if (deltaToFrameEnd > gapTolerance) {
  8059.                 // We subtract lastFrameDuration from deltaToFrameEnd to try to prevent any video
  8060.                 // frame overlap. maxBufferHole/maxSeekHole should be >> lastFrameDuration anyway.
  8061.                 mp4SampleDuration = deltaToFrameEnd - lastFrameDuration;
  8062.                 if (mp4SampleDuration < 0) {
  8063.                   mp4SampleDuration = lastFrameDuration;
  8064.                 }
  8065.                 _logger.logger.log('It is approximately ' + deltaToFrameEnd / 90 + ' ms to the next segment; using duration ' + mp4SampleDuration / 90 + ' ms for the last video frame.');
  8066.               } else {
  8067.                 mp4SampleDuration = lastFrameDuration;
  8068.               }
  8069.             } else {
  8070.               mp4SampleDuration = lastFrameDuration;
  8071.             }
  8072.           }
  8073.           mp4SampleDuration /= pes2mp4ScaleFactor;
  8074.           compositionTimeOffset = Math.round((avcSample.pts - avcSample.dts) / pes2mp4ScaleFactor);
  8075.         } else {
  8076.           compositionTimeOffset = Math.max(0, mp4SampleDuration * Math.round((avcSample.pts - avcSample.dts) / (pes2mp4ScaleFactor * mp4SampleDuration)));
  8077.         }
  8078.  
  8079.         //console.log('PTS/DTS/initDTS/normPTS/normDTS/relative PTS : ${avcSample.pts}/${avcSample.dts}/${this._initDTS}/${ptsnorm}/${dtsnorm}/${(avcSample.pts/4294967296).toFixed(3)}');
  8080.         outputSamples.push({
  8081.           size: mp4SampleLength,
  8082.           // constant duration
  8083.           duration: mp4SampleDuration,
  8084.           cts: compositionTimeOffset,
  8085.           flags: {
  8086.             isLeading: 0,
  8087.             isDependedOn: 0,
  8088.             hasRedundancy: 0,
  8089.             degradPrio: 0,
  8090.             dependsOn: avcSample.key ? 2 : 1,
  8091.             isNonSync: avcSample.key ? 0 : 1
  8092.           }
  8093.         });
  8094.       }
  8095.       // next AVC sample DTS should be equal to last sample DTS + last sample duration (in PES timescale)
  8096.       this.nextAvcDts = lastDTS + mp4SampleDuration * pes2mp4ScaleFactor;
  8097.       track.len = 0;
  8098.       track.nbNalu = 0;
  8099.       if (outputSamples.length && navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {
  8100.         var flags = outputSamples[0].flags;
  8101.         // chrome workaround, mark first sample as being a Random Access Point to avoid sourcebuffer append issue
  8102.         // https://code.google.com/p/chromium/issues/detail?id=229412
  8103.         flags.dependsOn = 2;
  8104.         flags.isNonSync = 0;
  8105.       }
  8106.       track.samples = outputSamples;
  8107.       moof = _mp4Generator2.default.moof(track.sequenceNumber++, firstDTS / pes2mp4ScaleFactor, track);
  8108.       track.samples = [];
  8109.       var data = {
  8110.         data1: moof,
  8111.         data2: mdat,
  8112.         startPTS: firstPTS / pesTimeScale,
  8113.         endPTS: (lastPTS + pes2mp4ScaleFactor * mp4SampleDuration) / pesTimeScale,
  8114.         startDTS: firstDTS / pesTimeScale,
  8115.         endDTS: this.nextAvcDts / pesTimeScale,
  8116.         type: 'video',
  8117.         nb: outputSamples.length
  8118.       };
  8119.       this.observer.trigger(_events2.default.FRAG_PARSING_DATA, data);
  8120.       return data;
  8121.     }
  8122.   }, {
  8123.     key: 'remuxAudio',
  8124.     value: function remuxAudio(track, timeOffset, contiguous) {
  8125.       var pesTimeScale = this.PES_TIMESCALE,
  8126.           mp4timeScale = track.timescale,
  8127.           pes2mp4ScaleFactor = pesTimeScale / mp4timeScale,
  8128.           expectedSampleDuration = track.timescale * 1024 / track.audiosamplerate;
  8129.       var view,
  8130.           offset = 8,
  8131.           aacSample,
  8132.           mp4Sample,
  8133.           unit,
  8134.           mdat,
  8135.           moof,
  8136.           firstPTS,
  8137.           firstDTS,
  8138.           lastDTS,
  8139.           pts,
  8140.           dts,
  8141.           ptsnorm,
  8142.           dtsnorm,
  8143.           samples = [],
  8144.           samples0 = [];
  8145.  
  8146.       track.samples.sort(function (a, b) {
  8147.         return a.pts - b.pts;
  8148.       });
  8149.       samples0 = track.samples;
  8150.  
  8151.       var nextAacPts = contiguous ? this.nextAacPts : timeOffset * pesTimeScale;
  8152.  
  8153.       // If the audio track is missing samples, the frames seem to get "left-shifted" within the
  8154.       // resulting mp4 segment, causing sync issues and leaving gaps at the end of the audio segment.
  8155.       // In an effort to prevent this from happening, we inject frames here where there are gaps.
  8156.       // When possible, we inject a silent frame; when that's not possible, we duplicate the last
  8157.       // frame.
  8158.       var firstPtsNorm = this._PTSNormalize(samples0[0].pts - this._initPTS, nextAacPts),
  8159.           pesFrameDuration = expectedSampleDuration * pes2mp4ScaleFactor;
  8160.       var nextPtsNorm = firstPtsNorm + pesFrameDuration;
  8161.       for (var i = 1; i < samples0.length;) {
  8162.         // First, let's see how far off this frame is from where we expect it to be
  8163.         var sample = samples0[i],
  8164.             ptsNorm = this._PTSNormalize(sample.pts - this._initPTS, nextAacPts),
  8165.             delta = ptsNorm - nextPtsNorm;
  8166.  
  8167.         // If we're overlapping by more than half a duration, drop this sample
  8168.         if (delta < -0.5 * pesFrameDuration) {
  8169.           _logger.logger.log('Dropping frame due to ' + Math.abs(delta / 90) + ' ms overlap.');
  8170.           samples0.splice(i, 1);
  8171.           track.len -= sample.unit.length;
  8172.           // Don't touch nextPtsNorm or i
  8173.         }
  8174.         // Otherwise, if we're more than half a frame away from where we should be, insert missing frames
  8175.         else if (delta > 0.5 * pesFrameDuration) {
  8176.             var missing = Math.round(delta / pesFrameDuration);
  8177.             _logger.logger.log('Injecting ' + missing + ' frame' + (missing > 1 ? 's' : '') + ' of missing audio due to ' + Math.round(delta / 90) + ' ms gap.');
  8178.             for (var j = 0; j < missing; j++) {
  8179.               var newStamp = samples0[i - 1].pts + pesFrameDuration,
  8180.                   fillFrame = _aac2.default.getSilentFrame(track.channelCount);
  8181.               if (!fillFrame) {
  8182.                 _logger.logger.log('Unable to get silent frame for given audio codec; duplicating last frame instead.');
  8183.                 fillFrame = sample.unit.slice(0);
  8184.               }
  8185.               samples0.splice(i, 0, { unit: fillFrame, pts: newStamp, dts: newStamp });
  8186.               track.len += fillFrame.length;
  8187.               i += 1;
  8188.             }
  8189.  
  8190.             // Adjust sample to next expected pts
  8191.             nextPtsNorm += (missing + 1) * pesFrameDuration;
  8192.             sample.pts = samples0[i - 1].pts + pesFrameDuration;
  8193.             i += 1;
  8194.           }
  8195.           // Otherwise, we're within half a frame duration, so just adjust pts
  8196.           else {
  8197.               if (Math.abs(delta) > 0.1 * pesFrameDuration) {
  8198.                 _logger.logger.log('Invalid frame delta ' + (ptsNorm - nextPtsNorm + pesFrameDuration) + ' at PTS ' + Math.round(ptsNorm / 90) + ' (should be ' + pesFrameDuration + ').');
  8199.               }
  8200.               nextPtsNorm += pesFrameDuration;
  8201.               sample.pts = samples0[i - 1].pts + pesFrameDuration;
  8202.               i += 1;
  8203.             }
  8204.       }
  8205.  
  8206.       while (samples0.length) {
  8207.         aacSample = samples0.shift();
  8208.         unit = aacSample.unit;
  8209.         pts = aacSample.pts - this._initDTS;
  8210.         dts = aacSample.dts - this._initDTS;
  8211.         //logger.log(`Audio/PTS:${Math.round(pts/90)}`);
  8212.         // if not first sample
  8213.         if (lastDTS !== undefined) {
  8214.           ptsnorm = this._PTSNormalize(pts, lastDTS);
  8215.           dtsnorm = this._PTSNormalize(dts, lastDTS);
  8216.           mp4Sample.duration = (dtsnorm - lastDTS) / pes2mp4ScaleFactor;
  8217.         } else {
  8218.           ptsnorm = this._PTSNormalize(pts, nextAacPts);
  8219.           dtsnorm = this._PTSNormalize(dts, nextAacPts);
  8220.           var _delta = Math.round(1000 * (ptsnorm - nextAacPts) / pesTimeScale);
  8221.           // if fragment are contiguous, detect hole/overlapping between fragments
  8222.           if (contiguous) {
  8223.             // log delta
  8224.             if (_delta) {
  8225.               if (_delta > 0) {
  8226.                 _logger.logger.log(_delta + ' ms hole between AAC samples detected,filling it');
  8227.                 // if we have frame overlap, overlapping for more than half a frame duraion
  8228.               } else if (_delta < -12) {
  8229.                   // drop overlapping audio frames... browser will deal with it
  8230.                   _logger.logger.log(-_delta + ' ms overlapping between AAC samples detected, drop frame');
  8231.                   track.len -= unit.byteLength;
  8232.                   continue;
  8233.                 }
  8234.               // set PTS/DTS to expected PTS/DTS
  8235.               ptsnorm = dtsnorm = nextAacPts;
  8236.             }
  8237.           }
  8238.           // remember first PTS of our aacSamples, ensure value is positive
  8239.           firstPTS = Math.max(0, ptsnorm);
  8240.           firstDTS = Math.max(0, dtsnorm);
  8241.           if (track.len > 0) {
  8242.             /* concatenate the audio data and construct the mdat in place
  8243.               (need 8 more bytes to fill length and mdat type) */
  8244.             mdat = new Uint8Array(track.len + 8);
  8245.             view = new DataView(mdat.buffer);
  8246.             view.setUint32(0, mdat.byteLength);
  8247.             mdat.set(_mp4Generator2.default.types.mdat, 4);
  8248.           } else {
  8249.             // no audio samples
  8250.             return;
  8251.           }
  8252.         }
  8253.         mdat.set(unit, offset);
  8254.         offset += unit.byteLength;
  8255.         //console.log('PTS/DTS/initDTS/normPTS/normDTS/relative PTS : ${aacSample.pts}/${aacSample.dts}/${this._initDTS}/${ptsnorm}/${dtsnorm}/${(aacSample.pts/4294967296).toFixed(3)}');
  8256.         mp4Sample = {
  8257.           size: unit.byteLength,
  8258.           cts: 0,
  8259.           duration: 0,
  8260.           flags: {
  8261.             isLeading: 0,
  8262.             isDependedOn: 0,
  8263.             hasRedundancy: 0,
  8264.             degradPrio: 0,
  8265.             dependsOn: 1
  8266.           }
  8267.         };
  8268.         samples.push(mp4Sample);
  8269.         lastDTS = dtsnorm;
  8270.       }
  8271.       var lastSampleDuration = 0;
  8272.       var nbSamples = samples.length;
  8273.       //set last sample duration as being identical to previous sample
  8274.       if (nbSamples >= 2) {
  8275.         lastSampleDuration = samples[nbSamples - 2].duration;
  8276.         mp4Sample.duration = lastSampleDuration;
  8277.       }
  8278.       if (nbSamples) {
  8279.         // next aac sample PTS should be equal to last sample PTS + duration
  8280.         this.nextAacPts = ptsnorm + pes2mp4ScaleFactor * lastSampleDuration;
  8281.         //logger.log('Audio/PTS/PTSend:' + aacSample.pts.toFixed(0) + '/' + this.nextAacDts.toFixed(0));
  8282.         track.len = 0;
  8283.         track.samples = samples;
  8284.         moof = _mp4Generator2.default.moof(track.sequenceNumber++, firstDTS / pes2mp4ScaleFactor, track);
  8285.         track.samples = [];
  8286.         var audioData = {
  8287.           data1: moof,
  8288.           data2: mdat,
  8289.           startPTS: firstPTS / pesTimeScale,
  8290.           endPTS: this.nextAacPts / pesTimeScale,
  8291.           startDTS: firstDTS / pesTimeScale,
  8292.           endDTS: (dtsnorm + pes2mp4ScaleFactor * lastSampleDuration) / pesTimeScale,
  8293.           type: 'audio',
  8294.           nb: nbSamples
  8295.         };
  8296.         this.observer.trigger(_events2.default.FRAG_PARSING_DATA, audioData);
  8297.         return audioData;
  8298.       }
  8299.       return null;
  8300.     }
  8301.   }, {
  8302.     key: 'remuxEmptyAudio',
  8303.     value: function remuxEmptyAudio(track, timeOffset, contiguous, videoData) {
  8304.       var pesTimeScale = this.PES_TIMESCALE,
  8305.           mp4timeScale = track.timescale ? track.timescale : track.audiosamplerate,
  8306.           pes2mp4ScaleFactor = pesTimeScale / mp4timeScale,
  8307.  
  8308.  
  8309.       // sync with video's timestamp
  8310.       startDTS = videoData.startDTS * pesTimeScale,
  8311.           endDTS = videoData.endDTS * pesTimeScale,
  8312.  
  8313.  
  8314.       // one sample's duration value
  8315.       sampleDuration = 1024,
  8316.           frameDuration = pes2mp4ScaleFactor * sampleDuration,
  8317.  
  8318.  
  8319.       // samples count of this segment's duration
  8320.       nbSamples = Math.ceil((endDTS - startDTS) / frameDuration),
  8321.  
  8322.  
  8323.       // silent frame
  8324.       silentFrame = _aac2.default.getSilentFrame(track.channelCount);
  8325.  
  8326.       // Can't remux if we can't generate a silent frame...
  8327.       if (!silentFrame) {
  8328.         _logger.logger.trace('Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec!');
  8329.         return;
  8330.       }
  8331.  
  8332.       var samples = [];
  8333.       for (var i = 0; i < nbSamples; i++) {
  8334.         var stamp = startDTS + i * frameDuration;
  8335.         samples.push({ unit: silentFrame.slice(0), pts: stamp, dts: stamp });
  8336.         track.len += silentFrame.length;
  8337.       }
  8338.       track.samples = samples;
  8339.  
  8340.       this.remuxAudio(track, timeOffset, contiguous);
  8341.     }
  8342.   }, {
  8343.     key: 'remuxID3',
  8344.     value: function remuxID3(track, timeOffset) {
  8345.       var length = track.samples.length,
  8346.           sample;
  8347.       // consume samples
  8348.       if (length) {
  8349.         for (var index = 0; index < length; index++) {
  8350.           sample = track.samples[index];
  8351.           // setting id3 pts, dts to relative time
  8352.           // using this._initPTS and this._initDTS to calculate relative time
  8353.           sample.pts = (sample.pts - this._initPTS) / this.PES_TIMESCALE;
  8354.           sample.dts = (sample.dts - this._initDTS) / this.PES_TIMESCALE;
  8355.         }
  8356.         this.observer.trigger(_events2.default.FRAG_PARSING_METADATA, {
  8357.           samples: track.samples
  8358.         });
  8359.       }
  8360.  
  8361.       track.samples = [];
  8362.       timeOffset = timeOffset;
  8363.     }
  8364.   }, {
  8365.     key: 'remuxText',
  8366.     value: function remuxText(track, timeOffset) {
  8367.       track.samples.sort(function (a, b) {
  8368.         return a.pts - b.pts;
  8369.       });
  8370.  
  8371.       var length = track.samples.length,
  8372.           sample;
  8373.       // consume samples
  8374.       if (length) {
  8375.         for (var index = 0; index < length; index++) {
  8376.           sample = track.samples[index];
  8377.           // setting text pts, dts to relative time
  8378.           // using this._initPTS and this._initDTS to calculate relative time
  8379.           sample.pts = (sample.pts - this._initPTS) / this.PES_TIMESCALE;
  8380.         }
  8381.         this.observer.trigger(_events2.default.FRAG_PARSING_USERDATA, {
  8382.           samples: track.samples
  8383.         });
  8384.       }
  8385.  
  8386.       track.samples = [];
  8387.       timeOffset = timeOffset;
  8388.     }
  8389.   }, {
  8390.     key: '_PTSNormalize',
  8391.     value: function _PTSNormalize(value, reference) {
  8392.       var offset;
  8393.       if (reference === undefined) {
  8394.         return value;
  8395.       }
  8396.       if (reference < value) {
  8397.         // - 2^33
  8398.         offset = -8589934592;
  8399.       } else {
  8400.         // + 2^33
  8401.         offset = 8589934592;
  8402.       }
  8403.       /* PTS is 33bit (from 0 to 2^33 -1)
  8404.         if diff between value and reference is bigger than half of the amplitude (2^32) then it means that
  8405.         PTS looping occured. fill the gap */
  8406.       while (Math.abs(value - reference) > 4294967296) {
  8407.         value += offset;
  8408.       }
  8409.       return value;
  8410.     }
  8411.   }, {
  8412.     key: 'passthrough',
  8413.     get: function get() {
  8414.       return false;
  8415.     }
  8416.   }]);
  8417.  
  8418.   return MP4Remuxer;
  8419. }();
  8420.  
  8421. exports.default = MP4Remuxer;
  8422.  
  8423. },{"../errors":21,"../events":23,"../helper/aac":24,"../remux/mp4-generator":32,"../utils/logger":39,"../utils/polyfill":40}],34:[function(require,module,exports){
  8424. 'use strict';
  8425.  
  8426. Object.defineProperty(exports, "__esModule", {
  8427.   value: true
  8428. });
  8429.  
  8430. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /**
  8431.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       * passthrough remuxer
  8432.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      */
  8433.  
  8434.  
  8435. var _events = require('../events');
  8436.  
  8437. var _events2 = _interopRequireDefault(_events);
  8438.  
  8439. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  8440.  
  8441. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  8442.  
  8443. var PassThroughRemuxer = function () {
  8444.   function PassThroughRemuxer(observer) {
  8445.     _classCallCheck(this, PassThroughRemuxer);
  8446.  
  8447.     this.observer = observer;
  8448.     this.ISGenerated = false;
  8449.   }
  8450.  
  8451.   _createClass(PassThroughRemuxer, [{
  8452.     key: 'destroy',
  8453.     value: function destroy() {}
  8454.   }, {
  8455.     key: 'insertDiscontinuity',
  8456.     value: function insertDiscontinuity() {}
  8457.   }, {
  8458.     key: 'switchLevel',
  8459.     value: function switchLevel() {
  8460.       this.ISGenerated = false;
  8461.     }
  8462.   }, {
  8463.     key: 'remux',
  8464.     value: function remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, rawData) {
  8465.       var observer = this.observer;
  8466.       // generate Init Segment if needed
  8467.       if (!this.ISGenerated) {
  8468.         var tracks = {},
  8469.             data = { tracks: tracks, unique: true },
  8470.             track = videoTrack,
  8471.             codec = track.codec;
  8472.  
  8473.         if (codec) {
  8474.           data.tracks.video = {
  8475.             container: track.container,
  8476.             codec: codec,
  8477.             metadata: {
  8478.               width: track.width,
  8479.               height: track.height
  8480.             }
  8481.           };
  8482.         }
  8483.  
  8484.         track = audioTrack;
  8485.         codec = track.codec;
  8486.         if (codec) {
  8487.           data.tracks.audio = {
  8488.             container: track.container,
  8489.             codec: codec,
  8490.             metadata: {
  8491.               channelCount: track.channelCount
  8492.             }
  8493.           };
  8494.         }
  8495.         this.ISGenerated = true;
  8496.         observer.trigger(_events2.default.FRAG_PARSING_INIT_SEGMENT, data);
  8497.       }
  8498.       observer.trigger(_events2.default.FRAG_PARSING_DATA, {
  8499.         data1: rawData,
  8500.         startPTS: timeOffset,
  8501.         startDTS: timeOffset,
  8502.         type: 'audiovideo',
  8503.         nb: 1
  8504.       });
  8505.     }
  8506.   }, {
  8507.     key: 'passthrough',
  8508.     get: function get() {
  8509.       return true;
  8510.     }
  8511.   }]);
  8512.  
  8513.   return PassThroughRemuxer;
  8514. }();
  8515.  
  8516. exports.default = PassThroughRemuxer;
  8517.  
  8518. },{"../events":23}],35:[function(require,module,exports){
  8519. 'use strict';
  8520.  
  8521. Object.defineProperty(exports, "__esModule", {
  8522.   value: true
  8523. });
  8524.  
  8525. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  8526.  
  8527. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  8528.  
  8529. // adapted from https://github.com/kanongil/node-m3u8parse/blob/master/attrlist.js
  8530.  
  8531. var AttrList = function () {
  8532.   function AttrList(attrs) {
  8533.     _classCallCheck(this, AttrList);
  8534.  
  8535.     if (typeof attrs === 'string') {
  8536.       attrs = AttrList.parseAttrList(attrs);
  8537.     }
  8538.     for (var attr in attrs) {
  8539.       if (attrs.hasOwnProperty(attr)) {
  8540.         this[attr] = attrs[attr];
  8541.       }
  8542.     }
  8543.   }
  8544.  
  8545.   _createClass(AttrList, [{
  8546.     key: 'decimalInteger',
  8547.     value: function decimalInteger(attrName) {
  8548.       var intValue = parseInt(this[attrName], 10);
  8549.       if (intValue > Number.MAX_SAFE_INTEGER) {
  8550.         return Infinity;
  8551.       }
  8552.       return intValue;
  8553.     }
  8554.   }, {
  8555.     key: 'hexadecimalInteger',
  8556.     value: function hexadecimalInteger(attrName) {
  8557.       if (this[attrName]) {
  8558.         var stringValue = (this[attrName] || '0x').slice(2);
  8559.         stringValue = (stringValue.length & 1 ? '0' : '') + stringValue;
  8560.  
  8561.         var value = new Uint8Array(stringValue.length / 2);
  8562.         for (var i = 0; i < stringValue.length / 2; i++) {
  8563.           value[i] = parseInt(stringValue.slice(i * 2, i * 2 + 2), 16);
  8564.         }
  8565.         return value;
  8566.       } else {
  8567.         return null;
  8568.       }
  8569.     }
  8570.   }, {
  8571.     key: 'hexadecimalIntegerAsNumber',
  8572.     value: function hexadecimalIntegerAsNumber(attrName) {
  8573.       var intValue = parseInt(this[attrName], 16);
  8574.       if (intValue > Number.MAX_SAFE_INTEGER) {
  8575.         return Infinity;
  8576.       }
  8577.       return intValue;
  8578.     }
  8579.   }, {
  8580.     key: 'decimalFloatingPoint',
  8581.     value: function decimalFloatingPoint(attrName) {
  8582.       return parseFloat(this[attrName]);
  8583.     }
  8584.   }, {
  8585.     key: 'enumeratedString',
  8586.     value: function enumeratedString(attrName) {
  8587.       return this[attrName];
  8588.     }
  8589.   }, {
  8590.     key: 'decimalResolution',
  8591.     value: function decimalResolution(attrName) {
  8592.       var res = /^(\d+)x(\d+)$/.exec(this[attrName]);
  8593.       if (res === null) {
  8594.         return undefined;
  8595.       }
  8596.       return {
  8597.         width: parseInt(res[1], 10),
  8598.         height: parseInt(res[2], 10)
  8599.       };
  8600.     }
  8601.   }], [{
  8602.     key: 'parseAttrList',
  8603.     value: function parseAttrList(input) {
  8604.       var re = /\s*(.+?)\s*=((?:\".*?\")|.*?)(?:,|$)/g;
  8605.       var match,
  8606.           attrs = {};
  8607.       while ((match = re.exec(input)) !== null) {
  8608.         var value = match[2],
  8609.             quote = '"';
  8610.  
  8611.         if (value.indexOf(quote) === 0 && value.lastIndexOf(quote) === value.length - 1) {
  8612.           value = value.slice(1, -1);
  8613.         }
  8614.         attrs[match[1]] = value;
  8615.       }
  8616.       return attrs;
  8617.     }
  8618.   }]);
  8619.  
  8620.   return AttrList;
  8621. }();
  8622.  
  8623. exports.default = AttrList;
  8624.  
  8625. },{}],36:[function(require,module,exports){
  8626. "use strict";
  8627.  
  8628. var BinarySearch = {
  8629.     /**
  8630.      * Searches for an item in an array which matches a certain condition.
  8631.      * This requires the condition to only match one item in the array,
  8632.      * and for the array to be ordered.
  8633.      *
  8634.      * @param {Array} list The array to search.
  8635.      * @param {Function} comparisonFunction
  8636.      *      Called and provided a candidate item as the first argument.
  8637.      *      Should return:
  8638.      *          > -1 if the item should be located at a lower index than the provided item.
  8639.      *          > 1 if the item should be located at a higher index than the provided item.
  8640.      *          > 0 if the item is the item you're looking for.
  8641.      *
  8642.      * @return {*} The object if it is found or null otherwise.
  8643.      */
  8644.     search: function search(list, comparisonFunction) {
  8645.         var minIndex = 0;
  8646.         var maxIndex = list.length - 1;
  8647.         var currentIndex = null;
  8648.         var currentElement = null;
  8649.  
  8650.         while (minIndex <= maxIndex) {
  8651.             currentIndex = (minIndex + maxIndex) / 2 | 0;
  8652.             currentElement = list[currentIndex];
  8653.  
  8654.             var comparisonResult = comparisonFunction(currentElement);
  8655.             if (comparisonResult > 0) {
  8656.                 minIndex = currentIndex + 1;
  8657.             } else if (comparisonResult < 0) {
  8658.                 maxIndex = currentIndex - 1;
  8659.             } else {
  8660.                 return currentElement;
  8661.             }
  8662.         }
  8663.  
  8664.         return null;
  8665.     }
  8666. };
  8667.  
  8668. module.exports = BinarySearch;
  8669.  
  8670. },{}],37:[function(require,module,exports){
  8671. 'use strict';
  8672.  
  8673. Object.defineProperty(exports, "__esModule", {
  8674.     value: true
  8675. });
  8676.  
  8677. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  8678.  
  8679. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  8680.  
  8681. /**
  8682.  *
  8683.  * This code was ported from the dash.js project at:
  8684.  *   https://github.com/Dash-Industry-Forum/dash.js/blob/development/externals/cea608-parser.js
  8685.  *   https://github.com/Dash-Industry-Forum/dash.js/commit/8269b26a761e0853bb21d78780ed945144ecdd4d#diff-71bc295a2d6b6b7093a1d3290d53a4b2
  8686.  *
  8687.  * The original copyright appears below:
  8688.  *
  8689.  * The copyright in this software is being made available under the BSD License,
  8690.  * included below. This software may be subject to other third party and contributor
  8691.  * rights, including patent rights, and no such rights are granted under this license.
  8692.  *
  8693.  * Copyright (c) 2015-2016, DASH Industry Forum.
  8694.  * All rights reserved.
  8695.  *
  8696.  * Redistribution and use in source and binary forms, with or without modification,
  8697.  * are permitted provided that the following conditions are met:
  8698.  *  1. Redistributions of source code must retain the above copyright notice, this
  8699.  *  list of conditions and the following disclaimer.
  8700.  *  * Redistributions in binary form must reproduce the above copyright notice,
  8701.  *  this list of conditions and the following disclaimer in the documentation and/or
  8702.  *  other materials provided with the distribution.
  8703.  *  2. Neither the name of Dash Industry Forum nor the names of its
  8704.  *  contributors may be used to endorse or promote products derived from this software
  8705.  *  without specific prior written permission.
  8706.  *
  8707.  *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY
  8708.  *  EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  8709.  *  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
  8710.  *  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
  8711.  *  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  8712.  *  NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  8713.  *  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  8714.  *  WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  8715.  *  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  8716.  *  POSSIBILITY OF SUCH DAMAGE.
  8717.  */
  8718. /**
  8719.  *  Exceptions from regular ASCII. CodePoints are mapped to UTF-16 codes
  8720.  */
  8721.  
  8722. var specialCea608CharsCodes = {
  8723.     0x2a: 0xe1, // lowercase a, acute accent
  8724.     0x5c: 0xe9, // lowercase e, acute accent
  8725.     0x5e: 0xed, // lowercase i, acute accent
  8726.     0x5f: 0xf3, // lowercase o, acute accent
  8727.     0x60: 0xfa, // lowercase u, acute accent
  8728.     0x7b: 0xe7, // lowercase c with cedilla
  8729.     0x7c: 0xf7, // division symbol
  8730.     0x7d: 0xd1, // uppercase N tilde
  8731.     0x7e: 0xf1, // lowercase n tilde
  8732.     0x7f: 0x2588, // Full block
  8733.     // THIS BLOCK INCLUDES THE 16 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS
  8734.     // THAT COME FROM HI BYTE=0x11 AND LOW BETWEEN 0x30 AND 0x3F
  8735.     // THIS MEANS THAT \x50 MUST BE ADDED TO THE VALUES
  8736.     0x80: 0xae, // Registered symbol (R)
  8737.     0x81: 0xb0, // degree sign
  8738.     0x82: 0xbd, // 1/2 symbol
  8739.     0x83: 0xbf, // Inverted (open) question mark
  8740.     0x84: 0x2122, // Trademark symbol (TM)
  8741.     0x85: 0xa2, // Cents symbol
  8742.     0x86: 0xa3, // Pounds sterling
  8743.     0x87: 0x266a, // Music 8'th note
  8744.     0x88: 0xe0, // lowercase a, grave accent
  8745.     0x89: 0x20, // transparent space (regular)
  8746.     0x8a: 0xe8, // lowercase e, grave accent
  8747.     0x8b: 0xe2, // lowercase a, circumflex accent
  8748.     0x8c: 0xea, // lowercase e, circumflex accent
  8749.     0x8d: 0xee, // lowercase i, circumflex accent
  8750.     0x8e: 0xf4, // lowercase o, circumflex accent
  8751.     0x8f: 0xfb, // lowercase u, circumflex accent
  8752.     // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS
  8753.     // THAT COME FROM HI BYTE=0x12 AND LOW BETWEEN 0x20 AND 0x3F
  8754.     0x90: 0xc1, // capital letter A with acute
  8755.     0x91: 0xc9, // capital letter E with acute
  8756.     0x92: 0xd3, // capital letter O with acute
  8757.     0x93: 0xda, // capital letter U with acute
  8758.     0x94: 0xdc, // capital letter U with diaresis
  8759.     0x95: 0xfc, // lowercase letter U with diaeresis
  8760.     0x96: 0x2018, // opening single quote
  8761.     0x97: 0xa1, // inverted exclamation mark
  8762.     0x98: 0x2a, // asterisk
  8763.     0x99: 0x2019, // closing single quote
  8764.     0x9a: 0x2501, // box drawings heavy horizontal
  8765.     0x9b: 0xa9, // copyright sign
  8766.     0x9c: 0x2120, // Service mark
  8767.     0x9d: 0x2022, // (round) bullet
  8768.     0x9e: 0x201c, // Left double quotation mark
  8769.     0x9f: 0x201d, // Right double quotation mark
  8770.     0xa0: 0xc0, // uppercase A, grave accent
  8771.     0xa1: 0xc2, // uppercase A, circumflex
  8772.     0xa2: 0xc7, // uppercase C with cedilla
  8773.     0xa3: 0xc8, // uppercase E, grave accent
  8774.     0xa4: 0xca, // uppercase E, circumflex
  8775.     0xa5: 0xcb, // capital letter E with diaresis
  8776.     0xa6: 0xeb, // lowercase letter e with diaresis
  8777.     0xa7: 0xce, // uppercase I, circumflex
  8778.     0xa8: 0xcf, // uppercase I, with diaresis
  8779.     0xa9: 0xef, // lowercase i, with diaresis
  8780.     0xaa: 0xd4, // uppercase O, circumflex
  8781.     0xab: 0xd9, // uppercase U, grave accent
  8782.     0xac: 0xf9, // lowercase u, grave accent
  8783.     0xad: 0xdb, // uppercase U, circumflex
  8784.     0xae: 0xab, // left-pointing double angle quotation mark
  8785.     0xaf: 0xbb, // right-pointing double angle quotation mark
  8786.     // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS
  8787.     // THAT COME FROM HI BYTE=0x13 AND LOW BETWEEN 0x20 AND 0x3F
  8788.     0xb0: 0xc3, // Uppercase A, tilde
  8789.     0xb1: 0xe3, // Lowercase a, tilde
  8790.     0xb2: 0xcd, // Uppercase I, acute accent
  8791.     0xb3: 0xcc, // Uppercase I, grave accent
  8792.     0xb4: 0xec, // Lowercase i, grave accent
  8793.     0xb5: 0xd2, // Uppercase O, grave accent
  8794.     0xb6: 0xf2, // Lowercase o, grave accent
  8795.     0xb7: 0xd5, // Uppercase O, tilde
  8796.     0xb8: 0xf5, // Lowercase o, tilde
  8797.     0xb9: 0x7b, // Open curly brace
  8798.     0xba: 0x7d, // Closing curly brace
  8799.     0xbb: 0x5c, // Backslash
  8800.     0xbc: 0x5e, // Caret
  8801.     0xbd: 0x5f, // Underscore
  8802.     0xbe: 0x7c, // Pipe (vertical line)
  8803.     0xbf: 0x223c, // Tilde operator
  8804.     0xc0: 0xc4, // Uppercase A, umlaut
  8805.     0xc1: 0xe4, // Lowercase A, umlaut
  8806.     0xc2: 0xd6, // Uppercase O, umlaut
  8807.     0xc3: 0xf6, // Lowercase o, umlaut
  8808.     0xc4: 0xdf, // Esszett (sharp S)
  8809.     0xc5: 0xa5, // Yen symbol
  8810.     0xc6: 0xa4, // Generic currency sign
  8811.     0xc7: 0x2503, // Box drawings heavy vertical
  8812.     0xc8: 0xc5, // Uppercase A, ring
  8813.     0xc9: 0xe5, // Lowercase A, ring
  8814.     0xca: 0xd8, // Uppercase O, stroke
  8815.     0xcb: 0xf8, // Lowercase o, strok
  8816.     0xcc: 0x250f, // Box drawings heavy down and right
  8817.     0xcd: 0x2513, // Box drawings heavy down and left
  8818.     0xce: 0x2517, // Box drawings heavy up and right
  8819.     0xcf: 0x251b // Box drawings heavy up and left
  8820. };
  8821.  
  8822. /**
  8823.  * Utils
  8824.  */
  8825. var getCharForByte = function getCharForByte(byte) {
  8826.     var charCode = byte;
  8827.     if (specialCea608CharsCodes.hasOwnProperty(byte)) {
  8828.         charCode = specialCea608CharsCodes[byte];
  8829.     }
  8830.     return String.fromCharCode(charCode);
  8831. };
  8832.  
  8833. var NR_ROWS = 15,
  8834.     NR_COLS = 32;
  8835. // Tables to look up row from PAC data
  8836. var rowsLowCh1 = { 0x11: 1, 0x12: 3, 0x15: 5, 0x16: 7, 0x17: 9, 0x10: 11, 0x13: 12, 0x14: 14 };
  8837. var rowsHighCh1 = { 0x11: 2, 0x12: 4, 0x15: 6, 0x16: 8, 0x17: 10, 0x13: 13, 0x14: 15 };
  8838. var rowsLowCh2 = { 0x19: 1, 0x1A: 3, 0x1D: 5, 0x1E: 7, 0x1F: 9, 0x18: 11, 0x1B: 12, 0x1C: 14 };
  8839. var rowsHighCh2 = { 0x19: 2, 0x1A: 4, 0x1D: 6, 0x1E: 8, 0x1F: 10, 0x1B: 13, 0x1C: 15 };
  8840.  
  8841. var backgroundColors = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta', 'black', 'transparent'];
  8842.  
  8843. /**
  8844.  * Simple logger class to be able to write with time-stamps and filter on level.
  8845.  */
  8846. var logger = {
  8847.     verboseFilter: { 'DATA': 3, 'DEBUG': 3, 'INFO': 2, 'WARNING': 2, 'TEXT': 1, 'ERROR': 0 },
  8848.     time: null,
  8849.     verboseLevel: 0, // Only write errors
  8850.     setTime: function setTime(newTime) {
  8851.         this.time = newTime;
  8852.     },
  8853.     log: function log(severity, msg) {
  8854.         var minLevel = this.verboseFilter[severity];
  8855.         if (this.verboseLevel >= minLevel) {
  8856.             console.log(this.time + ' [' + severity + '] ' + msg);
  8857.         }
  8858.     }
  8859. };
  8860.  
  8861. var numArrayToHexArray = function numArrayToHexArray(numArray) {
  8862.     var hexArray = [];
  8863.     for (var j = 0; j < numArray.length; j++) {
  8864.         hexArray.push(numArray[j].toString(16));
  8865.     }
  8866.     return hexArray;
  8867. };
  8868.  
  8869. var PenState = function () {
  8870.     function PenState(foreground, underline, italics, background, flash) {
  8871.         _classCallCheck(this, PenState);
  8872.  
  8873.         this.foreground = foreground || 'white';
  8874.         this.underline = underline || false;
  8875.         this.italics = italics || false;
  8876.         this.background = background || 'black';
  8877.         this.flash = flash || false;
  8878.     }
  8879.  
  8880.     _createClass(PenState, [{
  8881.         key: 'reset',
  8882.         value: function reset() {
  8883.             this.foreground = 'white';
  8884.             this.underline = false;
  8885.             this.italics = false;
  8886.             this.background = 'black';
  8887.             this.flash = false;
  8888.         }
  8889.     }, {
  8890.         key: 'setStyles',
  8891.         value: function setStyles(styles) {
  8892.             var attribs = ['foreground', 'underline', 'italics', 'background', 'flash'];
  8893.             for (var i = 0; i < attribs.length; i++) {
  8894.                 var style = attribs[i];
  8895.                 if (styles.hasOwnProperty(style)) {
  8896.                     this[style] = styles[style];
  8897.                 }
  8898.             }
  8899.         }
  8900.     }, {
  8901.         key: 'isDefault',
  8902.         value: function isDefault() {
  8903.             return this.foreground === 'white' && !this.underline && !this.italics && this.background === 'black' && !this.flash;
  8904.         }
  8905.     }, {
  8906.         key: 'equals',
  8907.         value: function equals(other) {
  8908.             return this.foreground === other.foreground && this.underline === other.underline && this.italics === other.italics && this.background === other.background && this.flash === other.flash;
  8909.         }
  8910.     }, {
  8911.         key: 'copy',
  8912.         value: function copy(newPenState) {
  8913.             this.foreground = newPenState.foreground;
  8914.             this.underline = newPenState.underline;
  8915.             this.italics = newPenState.italics;
  8916.             this.background = newPenState.background;
  8917.             this.flash = newPenState.flash;
  8918.         }
  8919.     }, {
  8920.         key: 'toString',
  8921.         value: function toString() {
  8922.             return 'color=' + this.foreground + ', underline=' + this.underline + ', italics=' + this.italics + ', background=' + this.background + ', flash=' + this.flash;
  8923.         }
  8924.     }]);
  8925.  
  8926.     return PenState;
  8927. }();
  8928.  
  8929. /**
  8930.  * Unicode character with styling and background.
  8931.  * @constructor
  8932.  */
  8933.  
  8934.  
  8935. var StyledUnicodeChar = function () {
  8936.     function StyledUnicodeChar(uchar, foreground, underline, italics, background, flash) {
  8937.         _classCallCheck(this, StyledUnicodeChar);
  8938.  
  8939.         this.uchar = uchar || ' '; // unicode character
  8940.         this.penState = new PenState(foreground, underline, italics, background, flash);
  8941.     }
  8942.  
  8943.     _createClass(StyledUnicodeChar, [{
  8944.         key: 'reset',
  8945.         value: function reset() {
  8946.             this.uchar = ' ';
  8947.             this.penState.reset();
  8948.         }
  8949.     }, {
  8950.         key: 'setChar',
  8951.         value: function setChar(uchar, newPenState) {
  8952.             this.uchar = uchar;
  8953.             this.penState.copy(newPenState);
  8954.         }
  8955.     }, {
  8956.         key: 'setPenState',
  8957.         value: function setPenState(newPenState) {
  8958.             this.penState.copy(newPenState);
  8959.         }
  8960.     }, {
  8961.         key: 'equals',
  8962.         value: function equals(other) {
  8963.             return this.uchar === other.uchar && this.penState.equals(other.penState);
  8964.         }
  8965.     }, {
  8966.         key: 'copy',
  8967.         value: function copy(newChar) {
  8968.             this.uchar = newChar.uchar;
  8969.             this.penState.copy(newChar.penState);
  8970.         }
  8971.     }, {
  8972.         key: 'isEmpty',
  8973.         value: function isEmpty() {
  8974.             return this.uchar === ' ' && this.penState.isDefault();
  8975.         }
  8976.     }]);
  8977.  
  8978.     return StyledUnicodeChar;
  8979. }();
  8980.  
  8981. /**
  8982.  * CEA-608 row consisting of NR_COLS instances of StyledUnicodeChar.
  8983.  * @constructor
  8984.  */
  8985.  
  8986.  
  8987. var Row = function () {
  8988.     function Row() {
  8989.         _classCallCheck(this, Row);
  8990.  
  8991.         this.chars = [];
  8992.         for (var i = 0; i < NR_COLS; i++) {
  8993.             this.chars.push(new StyledUnicodeChar());
  8994.         }
  8995.         this.pos = 0;
  8996.         this.currPenState = new PenState();
  8997.     }
  8998.  
  8999.     _createClass(Row, [{
  9000.         key: 'equals',
  9001.         value: function equals(other) {
  9002.             var equal = true;
  9003.             for (var i = 0; i < NR_COLS; i++) {
  9004.                 if (!this.chars[i].equals(other.chars[i])) {
  9005.                     equal = false;
  9006.                     break;
  9007.                 }
  9008.             }
  9009.             return equal;
  9010.         }
  9011.     }, {
  9012.         key: 'copy',
  9013.         value: function copy(other) {
  9014.             for (var i = 0; i < NR_COLS; i++) {
  9015.                 this.chars[i].copy(other.chars[i]);
  9016.             }
  9017.         }
  9018.     }, {
  9019.         key: 'isEmpty',
  9020.         value: function isEmpty() {
  9021.             var empty = true;
  9022.             for (var i = 0; i < NR_COLS; i++) {
  9023.                 if (!this.chars[i].isEmpty()) {
  9024.                     empty = false;
  9025.                     break;
  9026.                 }
  9027.             }
  9028.             return empty;
  9029.         }
  9030.  
  9031.         /**
  9032.          *  Set the cursor to a valid column.
  9033.          */
  9034.  
  9035.     }, {
  9036.         key: 'setCursor',
  9037.         value: function setCursor(absPos) {
  9038.             if (this.pos !== absPos) {
  9039.                 this.pos = absPos;
  9040.             }
  9041.             if (this.pos < 0) {
  9042.                 logger.log('ERROR', 'Negative cursor position ' + this.pos);
  9043.                 this.pos = 0;
  9044.             } else if (this.pos > NR_COLS) {
  9045.                 logger.log('ERROR', 'Too large cursor position ' + this.pos);
  9046.                 this.pos = NR_COLS;
  9047.             }
  9048.         }
  9049.  
  9050.         /**
  9051.          * Move the cursor relative to current position.
  9052.          */
  9053.  
  9054.     }, {
  9055.         key: 'moveCursor',
  9056.         value: function moveCursor(relPos) {
  9057.             var newPos = this.pos + relPos;
  9058.             if (relPos > 1) {
  9059.                 for (var i = this.pos + 1; i < newPos + 1; i++) {
  9060.                     this.chars[i].setPenState(this.currPenState);
  9061.                 }
  9062.             }
  9063.             this.setCursor(newPos);
  9064.         }
  9065.  
  9066.         /**
  9067.          * Backspace, move one step back and clear character.
  9068.          */
  9069.  
  9070.     }, {
  9071.         key: 'backSpace',
  9072.         value: function backSpace() {
  9073.             this.moveCursor(-1);
  9074.             this.chars[this.pos].setChar(' ', this.currPenState);
  9075.         }
  9076.     }, {
  9077.         key: 'insertChar',
  9078.         value: function insertChar(byte) {
  9079.             if (byte >= 0x90) {
  9080.                 //Extended char
  9081.                 this.backSpace();
  9082.             }
  9083.             var char = getCharForByte(byte);
  9084.             if (this.pos >= NR_COLS) {
  9085.                 logger.log('ERROR', 'Cannot insert ' + byte.toString(16) + ' (' + char + ') at position ' + this.pos + '. Skipping it!');
  9086.                 return;
  9087.             }
  9088.             this.chars[this.pos].setChar(char, this.currPenState);
  9089.             this.moveCursor(1);
  9090.         }
  9091.     }, {
  9092.         key: 'clearFromPos',
  9093.         value: function clearFromPos(startPos) {
  9094.             var i;
  9095.             for (i = startPos; i < NR_COLS; i++) {
  9096.                 this.chars[i].reset();
  9097.             }
  9098.         }
  9099.     }, {
  9100.         key: 'clear',
  9101.         value: function clear() {
  9102.             this.clearFromPos(0);
  9103.             this.pos = 0;
  9104.             this.currPenState.reset();
  9105.         }
  9106.     }, {
  9107.         key: 'clearToEndOfRow',
  9108.         value: function clearToEndOfRow() {
  9109.             this.clearFromPos(this.pos);
  9110.         }
  9111.     }, {
  9112.         key: 'getTextString',
  9113.         value: function getTextString() {
  9114.             var chars = [];
  9115.             var empty = true;
  9116.             for (var i = 0; i < NR_COLS; i++) {
  9117.                 var char = this.chars[i].uchar;
  9118.                 if (char !== ' ') {
  9119.                     empty = false;
  9120.                 }
  9121.                 chars.push(char);
  9122.             }
  9123.             if (empty) {
  9124.                 return '';
  9125.             } else {
  9126.                 return chars.join('');
  9127.             }
  9128.         }
  9129.     }, {
  9130.         key: 'setPenStyles',
  9131.         value: function setPenStyles(styles) {
  9132.             this.currPenState.setStyles(styles);
  9133.             var currChar = this.chars[this.pos];
  9134.             currChar.setPenState(this.currPenState);
  9135.         }
  9136.     }]);
  9137.  
  9138.     return Row;
  9139. }();
  9140.  
  9141. /**
  9142.  * Keep a CEA-608 screen of 32x15 styled characters
  9143.  * @constructor
  9144. */
  9145.  
  9146.  
  9147. var CaptionScreen = function () {
  9148.     function CaptionScreen() {
  9149.         _classCallCheck(this, CaptionScreen);
  9150.  
  9151.         this.rows = [];
  9152.         for (var i = 0; i < NR_ROWS; i++) {
  9153.             this.rows.push(new Row()); // Note that we use zero-based numbering (0-14)
  9154.         }
  9155.         this.currRow = NR_ROWS - 1;
  9156.         this.nrRollUpRows = null;
  9157.         this.reset();
  9158.     }
  9159.  
  9160.     _createClass(CaptionScreen, [{
  9161.         key: 'reset',
  9162.         value: function reset() {
  9163.             for (var i = 0; i < NR_ROWS; i++) {
  9164.                 this.rows[i].clear();
  9165.             }
  9166.             this.currRow = NR_ROWS - 1;
  9167.         }
  9168.     }, {
  9169.         key: 'equals',
  9170.         value: function equals(other) {
  9171.             var equal = true;
  9172.             for (var i = 0; i < NR_ROWS; i++) {
  9173.                 if (!this.rows[i].equals(other.rows[i])) {
  9174.                     equal = false;
  9175.                     break;
  9176.                 }
  9177.             }
  9178.             return equal;
  9179.         }
  9180.     }, {
  9181.         key: 'copy',
  9182.         value: function copy(other) {
  9183.             for (var i = 0; i < NR_ROWS; i++) {
  9184.                 this.rows[i].copy(other.rows[i]);
  9185.             }
  9186.         }
  9187.     }, {
  9188.         key: 'isEmpty',
  9189.         value: function isEmpty() {
  9190.             var empty = true;
  9191.             for (var i = 0; i < NR_ROWS; i++) {
  9192.                 if (!this.rows[i].isEmpty()) {
  9193.                     empty = false;
  9194.                     break;
  9195.                 }
  9196.             }
  9197.             return empty;
  9198.         }
  9199.     }, {
  9200.         key: 'backSpace',
  9201.         value: function backSpace() {
  9202.             var row = this.rows[this.currRow];
  9203.             row.backSpace();
  9204.         }
  9205.     }, {
  9206.         key: 'clearToEndOfRow',
  9207.         value: function clearToEndOfRow() {
  9208.             var row = this.rows[this.currRow];
  9209.             row.clearToEndOfRow();
  9210.         }
  9211.  
  9212.         /**
  9213.          * Insert a character (without styling) in the current row.
  9214.          */
  9215.  
  9216.     }, {
  9217.         key: 'insertChar',
  9218.         value: function insertChar(char) {
  9219.             var row = this.rows[this.currRow];
  9220.             row.insertChar(char);
  9221.         }
  9222.     }, {
  9223.         key: 'setPen',
  9224.         value: function setPen(styles) {
  9225.             var row = this.rows[this.currRow];
  9226.             row.setPenStyles(styles);
  9227.         }
  9228.     }, {
  9229.         key: 'moveCursor',
  9230.         value: function moveCursor(relPos) {
  9231.             var row = this.rows[this.currRow];
  9232.             row.moveCursor(relPos);
  9233.         }
  9234.     }, {
  9235.         key: 'setCursor',
  9236.         value: function setCursor(absPos) {
  9237.             logger.log('INFO', 'setCursor: ' + absPos);
  9238.             var row = this.rows[this.currRow];
  9239.             row.setCursor(absPos);
  9240.         }
  9241.     }, {
  9242.         key: 'setPAC',
  9243.         value: function setPAC(pacData) {
  9244.             logger.log('INFO', 'pacData = ' + JSON.stringify(pacData));
  9245.             var newRow = pacData.row - 1;
  9246.             if (this.nrRollUpRows && newRow < this.nrRollUpRows - 1) {
  9247.                 newRow = this.nrRollUpRows - 1;
  9248.             }
  9249.             this.currRow = newRow;
  9250.             var row = this.rows[this.currRow];
  9251.             if (pacData.indent !== null) {
  9252.                 var indent = pacData.indent;
  9253.                 var prevPos = Math.max(indent - 1, 0);
  9254.                 row.setCursor(pacData.indent);
  9255.                 pacData.color = row.chars[prevPos].penState.foreground;
  9256.             }
  9257.             var styles = { foreground: pacData.color, underline: pacData.underline, italics: pacData.italics, background: 'black', flash: false };
  9258.             this.setPen(styles);
  9259.         }
  9260.  
  9261.         /**
  9262.          * Set background/extra foreground, but first do back_space, and then insert space (backwards compatibility).
  9263.          */
  9264.  
  9265.     }, {
  9266.         key: 'setBkgData',
  9267.         value: function setBkgData(bkgData) {
  9268.  
  9269.             logger.log('INFO', 'bkgData = ' + JSON.stringify(bkgData));
  9270.             this.backSpace();
  9271.             this.setPen(bkgData);
  9272.             this.insertChar(0x20); //Space
  9273.         }
  9274.     }, {
  9275.         key: 'setRollUpRows',
  9276.         value: function setRollUpRows(nrRows) {
  9277.             this.nrRollUpRows = nrRows;
  9278.         }
  9279.     }, {
  9280.         key: 'rollUp',
  9281.         value: function rollUp() {
  9282.             if (this.nrRollUpRows === null) {
  9283.                 logger.log('DEBUG', 'roll_up but nrRollUpRows not set yet');
  9284.                 return; //Not properly setup
  9285.             }
  9286.             logger.log('TEXT', this.getDisplayText());
  9287.             var topRowIndex = this.currRow + 1 - this.nrRollUpRows;
  9288.             var topRow = this.rows.splice(topRowIndex, 1)[0];
  9289.             topRow.clear();
  9290.             this.rows.splice(this.currRow, 0, topRow);
  9291.             logger.log('INFO', 'Rolling up');
  9292.             //logger.log('TEXT', this.get_display_text())
  9293.         }
  9294.  
  9295.         /**
  9296.          * Get all non-empty rows with as unicode text.
  9297.          */
  9298.  
  9299.     }, {
  9300.         key: 'getDisplayText',
  9301.         value: function getDisplayText(asOneRow) {
  9302.             asOneRow = asOneRow || false;
  9303.             var displayText = [];
  9304.             var text = '';
  9305.             var rowNr = -1;
  9306.             for (var i = 0; i < NR_ROWS; i++) {
  9307.                 var rowText = this.rows[i].getTextString();
  9308.                 if (rowText) {
  9309.                     rowNr = i + 1;
  9310.                     if (asOneRow) {
  9311.                         displayText.push('Row ' + rowNr + ': \'' + rowText + '\'');
  9312.                     } else {
  9313.                         displayText.push(rowText.trim());
  9314.                     }
  9315.                 }
  9316.             }
  9317.             if (displayText.length > 0) {
  9318.                 if (asOneRow) {
  9319.                     text = '[' + displayText.join(' | ') + ']';
  9320.                 } else {
  9321.                     text = displayText.join('\n');
  9322.                 }
  9323.             }
  9324.             return text;
  9325.         }
  9326.     }, {
  9327.         key: 'getTextAndFormat',
  9328.         value: function getTextAndFormat() {
  9329.             return this.rows;
  9330.         }
  9331.     }]);
  9332.  
  9333.     return CaptionScreen;
  9334. }();
  9335.  
  9336. //var modes = ['MODE_ROLL-UP', 'MODE_POP-ON', 'MODE_PAINT-ON', 'MODE_TEXT'];
  9337.  
  9338. var Cea608Channel = function () {
  9339.     function Cea608Channel(channelNumber, outputFilter) {
  9340.         _classCallCheck(this, Cea608Channel);
  9341.  
  9342.         this.chNr = channelNumber;
  9343.         this.outputFilter = outputFilter;
  9344.         this.mode = null;
  9345.         this.verbose = 0;
  9346.         this.displayedMemory = new CaptionScreen();
  9347.         this.nonDisplayedMemory = new CaptionScreen();
  9348.         this.lastOutputScreen = new CaptionScreen();
  9349.         this.currRollUpRow = this.displayedMemory.rows[NR_ROWS - 1];
  9350.         this.writeScreen = this.displayedMemory;
  9351.         this.mode = null;
  9352.         this.cueStartTime = null; // Keeps track of where a cue started.
  9353.     }
  9354.  
  9355.     _createClass(Cea608Channel, [{
  9356.         key: 'reset',
  9357.         value: function reset() {
  9358.             this.mode = null;
  9359.             this.displayedMemory.reset();
  9360.             this.nonDisplayedMemory.reset();
  9361.             this.lastOutputScreen.reset();
  9362.             this.currRollUpRow = this.displayedMemory.rows[NR_ROWS - 1];
  9363.             this.writeScreen = this.displayedMemory;
  9364.             this.mode = null;
  9365.             this.cueStartTime = null;
  9366.             this.lastCueEndTime = null;
  9367.         }
  9368.     }, {
  9369.         key: 'getHandler',
  9370.         value: function getHandler() {
  9371.             return this.outputFilter;
  9372.         }
  9373.     }, {
  9374.         key: 'setHandler',
  9375.         value: function setHandler(newHandler) {
  9376.             this.outputFilter = newHandler;
  9377.         }
  9378.     }, {
  9379.         key: 'setPAC',
  9380.         value: function setPAC(pacData) {
  9381.             this.writeScreen.setPAC(pacData);
  9382.         }
  9383.     }, {
  9384.         key: 'setBkgData',
  9385.         value: function setBkgData(bkgData) {
  9386.             this.writeScreen.setBkgData(bkgData);
  9387.         }
  9388.     }, {
  9389.         key: 'setMode',
  9390.         value: function setMode(newMode) {
  9391.             if (newMode === this.mode) {
  9392.                 return;
  9393.             }
  9394.             this.mode = newMode;
  9395.             logger.log('INFO', 'MODE=' + newMode);
  9396.             if (this.mode === 'MODE_POP-ON') {
  9397.                 this.writeScreen = this.nonDisplayedMemory;
  9398.             } else {
  9399.                 this.writeScreen = this.displayedMemory;
  9400.                 this.writeScreen.reset();
  9401.             }
  9402.             if (this.mode !== 'MODE_ROLL-UP') {
  9403.                 this.displayedMemory.nrRollUpRows = null;
  9404.                 this.nonDisplayedMemory.nrRollUpRows = null;
  9405.             }
  9406.             this.mode = newMode;
  9407.         }
  9408.     }, {
  9409.         key: 'insertChars',
  9410.         value: function insertChars(chars) {
  9411.             for (var i = 0; i < chars.length; i++) {
  9412.                 this.writeScreen.insertChar(chars[i]);
  9413.             }
  9414.             var screen = this.writeScreen === this.displayedMemory ? 'DISP' : 'NON_DISP';
  9415.             logger.log('INFO', screen + ': ' + this.writeScreen.getDisplayText(true));
  9416.             if (this.mode === 'MODE_PAINT-ON' || this.mode === 'MODE_ROLL-UP') {
  9417.                 logger.log('TEXT', 'DISPLAYED: ' + this.displayedMemory.getDisplayText(true));
  9418.                 this.outputDataUpdate();
  9419.             }
  9420.         }
  9421.     }, {
  9422.         key: 'ccRCL',
  9423.         value: function ccRCL() {
  9424.             // Resume Caption Loading (switch mode to Pop On)
  9425.             logger.log('INFO', 'RCL - Resume Caption Loading');
  9426.             this.setMode('MODE_POP-ON');
  9427.         }
  9428.     }, {
  9429.         key: 'ccBS',
  9430.         value: function ccBS() {
  9431.             // BackSpace
  9432.             logger.log('INFO', 'BS - BackSpace');
  9433.             if (this.mode === 'MODE_TEXT') {
  9434.                 return;
  9435.             }
  9436.             this.writeScreen.backSpace();
  9437.             if (this.writeScreen === this.displayedMemory) {
  9438.                 this.outputDataUpdate();
  9439.             }
  9440.         }
  9441.     }, {
  9442.         key: 'ccAOF',
  9443.         value: function ccAOF() {
  9444.             // Reserved (formerly Alarm Off)
  9445.             return;
  9446.         }
  9447.     }, {
  9448.         key: 'ccAON',
  9449.         value: function ccAON() {
  9450.             // Reserved (formerly Alarm On)
  9451.             return;
  9452.         }
  9453.     }, {
  9454.         key: 'ccDER',
  9455.         value: function ccDER() {
  9456.             // Delete to End of Row
  9457.             logger.log('INFO', 'DER- Delete to End of Row');
  9458.             this.writeScreen.clearToEndOfRow();
  9459.             this.outputDataUpdate();
  9460.         }
  9461.     }, {
  9462.         key: 'ccRU',
  9463.         value: function ccRU(nrRows) {
  9464.             //Roll-Up Captions-2,3,or 4 Rows
  9465.             logger.log('INFO', 'RU(' + nrRows + ') - Roll Up');
  9466.             this.writeScreen = this.displayedMemory;
  9467.             this.setMode('MODE_ROLL-UP');
  9468.             this.writeScreen.setRollUpRows(nrRows);
  9469.         }
  9470.     }, {
  9471.         key: 'ccFON',
  9472.         value: function ccFON() {
  9473.             //Flash On
  9474.             logger.log('INFO', 'FON - Flash On');
  9475.             this.writeScreen.setPen({ flash: true });
  9476.         }
  9477.     }, {
  9478.         key: 'ccRDC',
  9479.         value: function ccRDC() {
  9480.             // Resume Direct Captioning (switch mode to PaintOn)
  9481.             logger.log('INFO', 'RDC - Resume Direct Captioning');
  9482.             this.setMode('MODE_PAINT-ON');
  9483.         }
  9484.     }, {
  9485.         key: 'ccTR',
  9486.         value: function ccTR() {
  9487.             // Text Restart in text mode (not supported, however)
  9488.             logger.log('INFO', 'TR');
  9489.             this.setMode('MODE_TEXT');
  9490.         }
  9491.     }, {
  9492.         key: 'ccRTD',
  9493.         value: function ccRTD() {
  9494.             // Resume Text Display in Text mode (not supported, however)
  9495.             logger.log('INFO', 'RTD');
  9496.             this.setMode('MODE_TEXT');
  9497.         }
  9498.     }, {
  9499.         key: 'ccEDM',
  9500.         value: function ccEDM() {
  9501.             // Erase Displayed Memory
  9502.             logger.log('INFO', 'EDM - Erase Displayed Memory');
  9503.             this.displayedMemory.reset();
  9504.             this.outputDataUpdate();
  9505.         }
  9506.     }, {
  9507.         key: 'ccCR',
  9508.         value: function ccCR() {
  9509.             // Carriage Return
  9510.             logger.log('CR - Carriage Return');
  9511.             this.writeScreen.rollUp();
  9512.             this.outputDataUpdate();
  9513.         }
  9514.     }, {
  9515.         key: 'ccENM',
  9516.         value: function ccENM() {
  9517.             //Erase Non-Displayed Memory
  9518.             logger.log('INFO', 'ENM - Erase Non-displayed Memory');
  9519.             this.nonDisplayedMemory.reset();
  9520.         }
  9521.     }, {
  9522.         key: 'ccEOC',
  9523.         value: function ccEOC() {
  9524.             //End of Caption (Flip Memories)
  9525.             logger.log('INFO', 'EOC - End Of Caption');
  9526.             if (this.mode === 'MODE_POP-ON') {
  9527.                 var tmp = this.displayedMemory;
  9528.                 this.displayedMemory = this.nonDisplayedMemory;
  9529.                 this.nonDisplayedMemory = tmp;
  9530.                 this.writeScreen = this.nonDisplayedMemory;
  9531.                 logger.log('TEXT', 'DISP: ' + this.displayedMemory.getDisplayText());
  9532.             }
  9533.             this.outputDataUpdate();
  9534.         }
  9535.     }, {
  9536.         key: 'ccTO',
  9537.         value: function ccTO(nrCols) {
  9538.             // Tab Offset 1,2, or 3 columns
  9539.             logger.log('INFO', 'TO(' + nrCols + ') - Tab Offset');
  9540.             this.writeScreen.moveCursor(nrCols);
  9541.         }
  9542.     }, {
  9543.         key: 'ccMIDROW',
  9544.         value: function ccMIDROW(secondByte) {
  9545.             // Parse MIDROW command
  9546.             var styles = { flash: false };
  9547.             styles.underline = secondByte % 2 === 1;
  9548.             styles.italics = secondByte >= 0x2e;
  9549.             if (!styles.italics) {
  9550.                 var colorIndex = Math.floor(secondByte / 2) - 0x10;
  9551.                 var colors = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta'];
  9552.                 styles.foreground = colors[colorIndex];
  9553.             } else {
  9554.                 styles.foreground = 'white';
  9555.             }
  9556.             logger.log('INFO', 'MIDROW: ' + JSON.stringify(styles));
  9557.             this.writeScreen.setPen(styles);
  9558.         }
  9559.     }, {
  9560.         key: 'outputDataUpdate',
  9561.         value: function outputDataUpdate() {
  9562.             var t = logger.time;
  9563.             if (t === null) {
  9564.                 return;
  9565.             }
  9566.             if (this.outputFilter) {
  9567.                 if (this.outputFilter.updateData) {
  9568.                     this.outputFilter.updateData(t, this.displayedMemory);
  9569.                 }
  9570.                 if (this.cueStartTime === null && !this.displayedMemory.isEmpty()) {
  9571.                     // Start of a new cue
  9572.                     this.cueStartTime = t;
  9573.                 } else {
  9574.                     if (!this.displayedMemory.equals(this.lastOutputScreen)) {
  9575.                         if (this.outputFilter.newCue) {
  9576.                             this.outputFilter.newCue(this.cueStartTime, t, this.lastOutputScreen);
  9577.                         }
  9578.                         this.cueStartTime = this.displayedMemory.isEmpty() ? null : t;
  9579.                     }
  9580.                 }
  9581.                 this.lastOutputScreen.copy(this.displayedMemory);
  9582.             }
  9583.         }
  9584.     }, {
  9585.         key: 'cueSplitAtTime',
  9586.         value: function cueSplitAtTime(t) {
  9587.             if (this.outputFilter) {
  9588.                 if (!this.displayedMemory.isEmpty()) {
  9589.                     if (this.outputFilter.newCue) {
  9590.                         this.outputFilter.newCue(this.cueStartTime, t, this.displayedMemory);
  9591.                     }
  9592.                     this.cueStartTime = t;
  9593.                 }
  9594.             }
  9595.         }
  9596.     }]);
  9597.  
  9598.     return Cea608Channel;
  9599. }();
  9600.  
  9601. var Cea608Parser = function () {
  9602.     function Cea608Parser(field, out1, out2) {
  9603.         _classCallCheck(this, Cea608Parser);
  9604.  
  9605.         this.field = field || 1;
  9606.         this.outputs = [out1, out2];
  9607.         this.channels = [new Cea608Channel(1, out1), new Cea608Channel(2, out2)];
  9608.         this.currChNr = -1; // Will be 1 or 2
  9609.         this.lastCmdA = null; // First byte of last command
  9610.         this.lastCmdB = null; // Second byte of last command
  9611.         this.bufferedData = [];
  9612.         this.startTime = null;
  9613.         this.lastTime = null;
  9614.         this.dataCounters = { 'padding': 0, 'char': 0, 'cmd': 0, 'other': 0 };
  9615.     }
  9616.  
  9617.     _createClass(Cea608Parser, [{
  9618.         key: 'getHandler',
  9619.         value: function getHandler(index) {
  9620.             return this.channels[index].getHandler();
  9621.         }
  9622.     }, {
  9623.         key: 'setHandler',
  9624.         value: function setHandler(index, newHandler) {
  9625.             this.channels[index].setHandler(newHandler);
  9626.         }
  9627.  
  9628.         /**
  9629.          * Add data for time t in forms of list of bytes (unsigned ints). The bytes are treated as pairs.
  9630.          */
  9631.  
  9632.     }, {
  9633.         key: 'addData',
  9634.         value: function addData(t, byteList) {
  9635.             var cmdFound,
  9636.                 a,
  9637.                 b,
  9638.                 charsFound = false;
  9639.  
  9640.             this.lastTime = t;
  9641.             logger.setTime(t);
  9642.  
  9643.             for (var i = 0; i < byteList.length; i += 2) {
  9644.                 a = byteList[i] & 0x7f;
  9645.                 b = byteList[i + 1] & 0x7f;
  9646.                 if (a === 0 && b === 0) {
  9647.                     this.dataCounters.padding += 2;
  9648.                     continue;
  9649.                 } else {
  9650.                     logger.log('DATA', '[' + numArrayToHexArray([byteList[i], byteList[i + 1]]) + '] -> (' + numArrayToHexArray([a, b]) + ')');
  9651.                 }
  9652.                 cmdFound = this.parseCmd(a, b);
  9653.                 if (!cmdFound) {
  9654.                     cmdFound = this.parseMidrow(a, b);
  9655.                 }
  9656.                 if (!cmdFound) {
  9657.                     cmdFound = this.parsePAC(a, b);
  9658.                 }
  9659.                 if (!cmdFound) {
  9660.                     cmdFound = this.parseBackgroundAttributes(a, b);
  9661.                 }
  9662.                 if (!cmdFound) {
  9663.                     charsFound = this.parseChars(a, b);
  9664.                     if (charsFound) {
  9665.                         if (this.currChNr && this.currChNr >= 0) {
  9666.                             var channel = this.channels[this.currChNr - 1];
  9667.                             channel.insertChars(charsFound);
  9668.                         } else {
  9669.                             logger.log('WARNING', 'No channel found yet. TEXT-MODE?');
  9670.                         }
  9671.                     }
  9672.                 }
  9673.                 if (cmdFound) {
  9674.                     this.dataCounters.cmd += 2;
  9675.                 } else if (charsFound) {
  9676.                     this.dataCounters.char += 2;
  9677.                 } else {
  9678.                     this.dataCounters.other += 2;
  9679.                     logger.log('WARNING', 'Couldn\'t parse cleaned data ' + numArrayToHexArray([a, b]) + ' orig: ' + numArrayToHexArray([byteList[i], byteList[i + 1]]));
  9680.                 }
  9681.             }
  9682.         }
  9683.  
  9684.         /**
  9685.          * Parse Command.
  9686.          * @returns {Boolean} Tells if a command was found
  9687.          */
  9688.  
  9689.     }, {
  9690.         key: 'parseCmd',
  9691.         value: function parseCmd(a, b) {
  9692.             var chNr = null;
  9693.  
  9694.             var cond1 = (a === 0x14 || a === 0x1C) && 0x20 <= b && b <= 0x2F;
  9695.             var cond2 = (a === 0x17 || a === 0x1F) && 0x21 <= b && b <= 0x23;
  9696.             if (!(cond1 || cond2)) {
  9697.                 return false;
  9698.             }
  9699.  
  9700.             if (a === this.lastCmdA && b === this.lastCmdB) {
  9701.                 this.lastCmdA = null;
  9702.                 this.lastCmdB = null; // Repeated commands are dropped (once)
  9703.                 logger.log('DEBUG', 'Repeated command (' + numArrayToHexArray([a, b]) + ') is dropped');
  9704.                 return true;
  9705.             }
  9706.  
  9707.             if (a === 0x14 || a === 0x17) {
  9708.                 chNr = 1;
  9709.             } else {
  9710.                 chNr = 2; // (a === 0x1C || a=== 0x1f)
  9711.             }
  9712.  
  9713.             var channel = this.channels[chNr - 1];
  9714.  
  9715.             if (a === 0x14 || a === 0x1C) {
  9716.                 if (b === 0x20) {
  9717.                     channel.ccRCL();
  9718.                 } else if (b === 0x21) {
  9719.                     channel.ccBS();
  9720.                 } else if (b === 0x22) {
  9721.                     channel.ccAOF();
  9722.                 } else if (b === 0x23) {
  9723.                     channel.ccAON();
  9724.                 } else if (b === 0x24) {
  9725.                     channel.ccDER();
  9726.                 } else if (b === 0x25) {
  9727.                     channel.ccRU(2);
  9728.                 } else if (b === 0x26) {
  9729.                     channel.ccRU(3);
  9730.                 } else if (b === 0x27) {
  9731.                     channel.ccRU(4);
  9732.                 } else if (b === 0x28) {
  9733.                     channel.ccFON();
  9734.                 } else if (b === 0x29) {
  9735.                     channel.ccRDC();
  9736.                 } else if (b === 0x2A) {
  9737.                     channel.ccTR();
  9738.                 } else if (b === 0x2B) {
  9739.                     channel.ccRTD();
  9740.                 } else if (b === 0x2C) {
  9741.                     channel.ccEDM();
  9742.                 } else if (b === 0x2D) {
  9743.                     channel.ccCR();
  9744.                 } else if (b === 0x2E) {
  9745.                     channel.ccENM();
  9746.                 } else if (b === 0x2F) {
  9747.                     channel.ccEOC();
  9748.                 }
  9749.             } else {
  9750.                 //a == 0x17 || a == 0x1F
  9751.                 channel.ccTO(b - 0x20);
  9752.             }
  9753.             this.lastCmdA = a;
  9754.             this.lastCmdB = b;
  9755.             this.currChNr = chNr;
  9756.             return true;
  9757.         }
  9758.  
  9759.         /**
  9760.          * Parse midrow styling command
  9761.          * @returns {Boolean}
  9762.          */
  9763.  
  9764.     }, {
  9765.         key: 'parseMidrow',
  9766.         value: function parseMidrow(a, b) {
  9767.             var chNr = null;
  9768.  
  9769.             if ((a === 0x11 || a === 0x19) && 0x20 <= b && b <= 0x2f) {
  9770.                 if (a === 0x11) {
  9771.                     chNr = 1;
  9772.                 } else {
  9773.                     chNr = 2;
  9774.                 }
  9775.                 if (chNr !== this.currChNr) {
  9776.                     logger.log('ERROR', 'Mismatch channel in midrow parsing');
  9777.                     return false;
  9778.                 }
  9779.                 var channel = this.channels[chNr - 1];
  9780.                 channel.ccMIDROW(b);
  9781.                 logger.log('DEBUG', 'MIDROW (' + numArrayToHexArray([a, b]) + ')');
  9782.                 return true;
  9783.             }
  9784.             return false;
  9785.         }
  9786.         /**
  9787.          * Parse Preable Access Codes (Table 53).
  9788.          * @returns {Boolean} Tells if PAC found
  9789.          */
  9790.  
  9791.     }, {
  9792.         key: 'parsePAC',
  9793.         value: function parsePAC(a, b) {
  9794.  
  9795.             var chNr = null;
  9796.             var row = null;
  9797.  
  9798.             var case1 = (0x11 <= a && a <= 0x17 || 0x19 <= a && a <= 0x1F) && 0x40 <= b && b <= 0x7F;
  9799.             var case2 = (a === 0x10 || a === 0x18) && 0x40 <= b && b <= 0x5F;
  9800.             if (!(case1 || case2)) {
  9801.                 return false;
  9802.             }
  9803.  
  9804.             if (a === this.lastCmdA && b === this.lastCmdB) {
  9805.                 this.lastCmdA = null;
  9806.                 this.lastCmdB = null;
  9807.                 return true; // Repeated commands are dropped (once)
  9808.             }
  9809.  
  9810.             chNr = a <= 0x17 ? 1 : 2;
  9811.  
  9812.             if (0x40 <= b && b <= 0x5F) {
  9813.                 row = chNr === 1 ? rowsLowCh1[a] : rowsLowCh2[a];
  9814.             } else {
  9815.                 // 0x60 <= b <= 0x7F
  9816.                 row = chNr === 1 ? rowsHighCh1[a] : rowsHighCh2[a];
  9817.             }
  9818.             var pacData = this.interpretPAC(row, b);
  9819.             var channel = this.channels[chNr - 1];
  9820.             channel.setPAC(pacData);
  9821.             this.lastCmdA = a;
  9822.             this.lastCmdB = b;
  9823.             this.currChNr = chNr;
  9824.             return true;
  9825.         }
  9826.  
  9827.         /**
  9828.          * Interpret the second byte of the pac, and return the information.
  9829.          * @returns {Object} pacData with style parameters.
  9830.          */
  9831.  
  9832.     }, {
  9833.         key: 'interpretPAC',
  9834.         value: function interpretPAC(row, byte) {
  9835.             var pacIndex = byte;
  9836.             var pacData = { color: null, italics: false, indent: null, underline: false, row: row };
  9837.  
  9838.             if (byte > 0x5F) {
  9839.                 pacIndex = byte - 0x60;
  9840.             } else {
  9841.                 pacIndex = byte - 0x40;
  9842.             }
  9843.             pacData.underline = (pacIndex & 1) === 1;
  9844.             if (pacIndex <= 0xd) {
  9845.                 pacData.color = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta', 'white'][Math.floor(pacIndex / 2)];
  9846.             } else if (pacIndex <= 0xf) {
  9847.                 pacData.italics = true;
  9848.                 pacData.color = 'white';
  9849.             } else {
  9850.                 pacData.indent = Math.floor((pacIndex - 0x10) / 2) * 4;
  9851.             }
  9852.             return pacData; // Note that row has zero offset. The spec uses 1.
  9853.         }
  9854.  
  9855.         /**
  9856.          * Parse characters.
  9857.          * @returns An array with 1 to 2 codes corresponding to chars, if found. null otherwise.
  9858.          */
  9859.  
  9860.     }, {
  9861.         key: 'parseChars',
  9862.         value: function parseChars(a, b) {
  9863.  
  9864.             var channelNr = null,
  9865.                 charCodes = null,
  9866.                 charCode1 = null;
  9867.  
  9868.             if (a >= 0x19) {
  9869.                 channelNr = 2;
  9870.                 charCode1 = a - 8;
  9871.             } else {
  9872.                 channelNr = 1;
  9873.                 charCode1 = a;
  9874.             }
  9875.             if (0x11 <= charCode1 && charCode1 <= 0x13) {
  9876.                 // Special character
  9877.                 var oneCode = b;
  9878.                 if (charCode1 === 0x11) {
  9879.                     oneCode = b + 0x50;
  9880.                 } else if (charCode1 === 0x12) {
  9881.                     oneCode = b + 0x70;
  9882.                 } else {
  9883.                     oneCode = b + 0x90;
  9884.                 }
  9885.                 logger.log('INFO', 'Special char \'' + getCharForByte(oneCode) + '\' in channel ' + channelNr);
  9886.                 charCodes = [oneCode];
  9887.             } else if (0x20 <= a && a <= 0x7f) {
  9888.                 charCodes = b === 0 ? [a] : [a, b];
  9889.             }
  9890.             if (charCodes) {
  9891.                 var hexCodes = numArrayToHexArray(charCodes);
  9892.                 logger.log('DEBUG', 'Char codes =  ' + hexCodes.join(','));
  9893.                 this.lastCmdA = null;
  9894.                 this.lastCmdB = null;
  9895.             }
  9896.             return charCodes;
  9897.         }
  9898.  
  9899.         /**
  9900.         * Parse extended background attributes as well as new foreground color black.
  9901.         * @returns{Boolean} Tells if background attributes are found
  9902.         */
  9903.  
  9904.     }, {
  9905.         key: 'parseBackgroundAttributes',
  9906.         value: function parseBackgroundAttributes(a, b) {
  9907.             var bkgData, index, chNr, channel;
  9908.  
  9909.             var case1 = (a === 0x10 || a === 0x18) && 0x20 <= b && b <= 0x2f;
  9910.             var case2 = (a === 0x17 || a === 0x1f) && 0x2d <= b && b <= 0x2f;
  9911.             if (!(case1 || case2)) {
  9912.                 return false;
  9913.             }
  9914.             bkgData = {};
  9915.             if (a === 0x10 || a === 0x18) {
  9916.                 index = Math.floor((b - 0x20) / 2);
  9917.                 bkgData.background = backgroundColors[index];
  9918.                 if (b % 2 === 1) {
  9919.                     bkgData.background = bkgData.background + '_semi';
  9920.                 }
  9921.             } else if (b === 0x2d) {
  9922.                 bkgData.background = 'transparent';
  9923.             } else {
  9924.                 bkgData.foreground = 'black';
  9925.                 if (b === 0x2f) {
  9926.                     bkgData.underline = true;
  9927.                 }
  9928.             }
  9929.             chNr = a < 0x18 ? 1 : 2;
  9930.             channel = this.channels[chNr - 1];
  9931.             channel.setBkgData(bkgData);
  9932.             this.lastCmdA = null;
  9933.             this.lastCmdB = null;
  9934.             return true;
  9935.         }
  9936.  
  9937.         /**
  9938.          * Reset state of parser and its channels.
  9939.          */
  9940.  
  9941.     }, {
  9942.         key: 'reset',
  9943.         value: function reset() {
  9944.             for (var i = 0; i < this.channels.length; i++) {
  9945.                 if (this.channels[i]) {
  9946.                     this.channels[i].reset();
  9947.                 }
  9948.             }
  9949.             this.lastCmdA = null;
  9950.             this.lastCmdB = null;
  9951.         }
  9952.  
  9953.         /**
  9954.          * Trigger the generation of a cue, and the start of a new one if displayScreens are not empty.
  9955.          */
  9956.  
  9957.     }, {
  9958.         key: 'cueSplitAtTime',
  9959.         value: function cueSplitAtTime(t) {
  9960.             for (var i = 0; i < this.channels.length; i++) {
  9961.                 if (this.channels[i]) {
  9962.                     this.channels[i].cueSplitAtTime(t);
  9963.                 }
  9964.             }
  9965.         }
  9966.     }]);
  9967.  
  9968.     return Cea608Parser;
  9969. }();
  9970.  
  9971. exports.default = Cea608Parser;
  9972.  
  9973. },{}],38:[function(require,module,exports){
  9974. 'use strict';
  9975.  
  9976. var Cues = {
  9977.  
  9978.   newCue: function newCue(track, startTime, endTime, captionScreen) {
  9979.     var row;
  9980.     var cue;
  9981.     var indenting;
  9982.     var indent;
  9983.     var text;
  9984.     var VTTCue = window.VTTCue || window.TextTrackCue;
  9985.  
  9986.     for (var r = 0; r < captionScreen.rows.length; r++) {
  9987.       row = captionScreen.rows[r];
  9988.       indenting = true;
  9989.       indent = 0;
  9990.       text = '';
  9991.  
  9992.       if (!row.isEmpty()) {
  9993.         for (var c = 0; c < row.chars.length; c++) {
  9994.           if (row.chars[c].uchar.match(/\s/) && indenting) {
  9995.             indent++;
  9996.           } else {
  9997.             text += row.chars[c].uchar;
  9998.             indenting = false;
  9999.           }
  10000.         }
  10001.         cue = new VTTCue(startTime, endTime, text.trim());
  10002.  
  10003.         if (indent >= 16) {
  10004.           indent--;
  10005.         } else {
  10006.           indent++;
  10007.         }
  10008.  
  10009.         // VTTCue.line get's flakey when using controls, so let's now include line 13&14
  10010.         // also, drop line 1 since it's to close to the top
  10011.         if (navigator.userAgent.match(/Firefox\//)) {
  10012.           cue.line = r + 1;
  10013.         } else {
  10014.           cue.line = r > 7 ? r - 2 : r + 1;
  10015.         }
  10016.         cue.align = 'left';
  10017.         cue.position = 100 * (indent / 32) + (navigator.userAgent.match(/Firefox\//) ? 50 : 0);
  10018.         track.addCue(cue);
  10019.       }
  10020.     }
  10021.   }
  10022.  
  10023. };
  10024.  
  10025. module.exports = Cues;
  10026.  
  10027. },{}],39:[function(require,module,exports){
  10028. 'use strict';
  10029.  
  10030. Object.defineProperty(exports, "__esModule", {
  10031.   value: true
  10032. });
  10033.  
  10034. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };
  10035.  
  10036. function noop() {}
  10037.  
  10038. var fakeLogger = {
  10039.   trace: noop,
  10040.   debug: noop,
  10041.   log: noop,
  10042.   warn: noop,
  10043.   info: noop,
  10044.   error: noop
  10045. };
  10046.  
  10047. var exportedLogger = fakeLogger;
  10048.  
  10049. //let lastCallTime;
  10050. // function formatMsgWithTimeInfo(type, msg) {
  10051. //   const now = Date.now();
  10052. //   const diff = lastCallTime ? '+' + (now - lastCallTime) : '0';
  10053. //   lastCallTime = now;
  10054. //   msg = (new Date(now)).toISOString() + ' | [' +  type + '] > ' + msg + ' ( ' + diff + ' ms )';
  10055. //   return msg;
  10056. // }
  10057.  
  10058. function formatMsg(type, msg) {
  10059.   msg = '[' + type + '] > ' + msg;
  10060.   return msg;
  10061. }
  10062.  
  10063. function consolePrintFn(type) {
  10064.   var func = window.console[type];
  10065.   if (func) {
  10066.     return function () {
  10067.       for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
  10068.         args[_key] = arguments[_key];
  10069.       }
  10070.  
  10071.       if (args[0]) {
  10072.         args[0] = formatMsg(type, args[0]);
  10073.       }
  10074.       func.apply(window.console, args);
  10075.     };
  10076.   }
  10077.   return noop;
  10078. }
  10079.  
  10080. function exportLoggerFunctions(debugConfig) {
  10081.   for (var _len2 = arguments.length, functions = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
  10082.     functions[_key2 - 1] = arguments[_key2];
  10083.   }
  10084.  
  10085.   functions.forEach(function (type) {
  10086.     exportedLogger[type] = debugConfig[type] ? debugConfig[type].bind(debugConfig) : consolePrintFn(type);
  10087.   });
  10088. }
  10089.  
  10090. var enableLogs = exports.enableLogs = function enableLogs(debugConfig) {
  10091.   if (debugConfig === true || (typeof debugConfig === 'undefined' ? 'undefined' : _typeof(debugConfig)) === 'object') {
  10092.     exportLoggerFunctions(debugConfig,
  10093.     // Remove out from list here to hard-disable a log-level
  10094.     //'trace',
  10095.     'debug', 'log', 'info', 'warn', 'error');
  10096.     // Some browsers don't allow to use bind on console object anyway
  10097.     // fallback to default if needed
  10098.     try {
  10099.       exportedLogger.log();
  10100.     } catch (e) {
  10101.       exportedLogger = fakeLogger;
  10102.     }
  10103.   } else {
  10104.     exportedLogger = fakeLogger;
  10105.   }
  10106. };
  10107.  
  10108. var logger = exports.logger = exportedLogger;
  10109.  
  10110. },{}],40:[function(require,module,exports){
  10111. "use strict";
  10112.  
  10113. if (!ArrayBuffer.prototype.slice) {
  10114.   ArrayBuffer.prototype.slice = function (start, end) {
  10115.     var that = new Uint8Array(this);
  10116.     if (end === undefined) {
  10117.       end = that.length;
  10118.     }
  10119.     var result = new ArrayBuffer(end - start);
  10120.     var resultArray = new Uint8Array(result);
  10121.     for (var i = 0; i < resultArray.length; i++) {
  10122.       resultArray[i] = that[i + start];
  10123.     }
  10124.     return result;
  10125.   };
  10126. }
  10127.  
  10128. },{}],41:[function(require,module,exports){
  10129. 'use strict';
  10130.  
  10131. var URLHelper = {
  10132.   // build an absolute URL from a relative one using the provided baseURL
  10133.   // if relativeURL is an absolute URL it will be returned as is.
  10134.   buildAbsoluteURL: function buildAbsoluteURL(baseURL, relativeURL) {
  10135.     // remove any remaining space and CRLF
  10136.     relativeURL = relativeURL.trim();
  10137.     if (/^[a-z]+:/i.test(relativeURL)) {
  10138.       // complete url, not relative
  10139.       return relativeURL;
  10140.     }
  10141.  
  10142.     var relativeURLQuery = null;
  10143.     var relativeURLHash = null;
  10144.  
  10145.     var relativeURLHashSplit = /^([^#]*)(.*)$/.exec(relativeURL);
  10146.     if (relativeURLHashSplit) {
  10147.       relativeURLHash = relativeURLHashSplit[2];
  10148.       relativeURL = relativeURLHashSplit[1];
  10149.     }
  10150.     var relativeURLQuerySplit = /^([^\?]*)(.*)$/.exec(relativeURL);
  10151.     if (relativeURLQuerySplit) {
  10152.       relativeURLQuery = relativeURLQuerySplit[2];
  10153.       relativeURL = relativeURLQuerySplit[1];
  10154.     }
  10155.  
  10156.     var baseURLHashSplit = /^([^#]*)(.*)$/.exec(baseURL);
  10157.     if (baseURLHashSplit) {
  10158.       baseURL = baseURLHashSplit[1];
  10159.     }
  10160.     var baseURLQuerySplit = /^([^\?]*)(.*)$/.exec(baseURL);
  10161.     if (baseURLQuerySplit) {
  10162.       baseURL = baseURLQuerySplit[1];
  10163.     }
  10164.  
  10165.     var baseURLDomainSplit = /^(([a-z]+:)?\/\/[a-z0-9\.\-_~]+(:[0-9]+)?)?(\/.*)$/i.exec(baseURL);
  10166.     if (!baseURLDomainSplit) {
  10167.       throw new Error('Error trying to parse base URL.');
  10168.     }
  10169.  
  10170.     // e.g. 'http:', 'https:', ''
  10171.     var baseURLProtocol = baseURLDomainSplit[2] || '';
  10172.     // e.g. 'http://example.com', '//example.com', ''
  10173.     var baseURLProtocolDomain = baseURLDomainSplit[1] || '';
  10174.     // e.g. '/a/b/c/playlist.m3u8'
  10175.     var baseURLPath = baseURLDomainSplit[4];
  10176.  
  10177.     var builtURL = null;
  10178.     if (/^\/\//.test(relativeURL)) {
  10179.       // relative url starts wth '//' so copy protocol (which may be '' if baseUrl didn't provide one)
  10180.       builtURL = baseURLProtocol + '//' + URLHelper.buildAbsolutePath('', relativeURL.substring(2));
  10181.     } else if (/^\//.test(relativeURL)) {
  10182.       // relative url starts with '/' so start from root of domain
  10183.       builtURL = baseURLProtocolDomain + '/' + URLHelper.buildAbsolutePath('', relativeURL.substring(1));
  10184.     } else {
  10185.       builtURL = URLHelper.buildAbsolutePath(baseURLProtocolDomain + baseURLPath, relativeURL);
  10186.     }
  10187.  
  10188.     // put the query and hash parts back
  10189.     if (relativeURLQuery) {
  10190.       builtURL += relativeURLQuery;
  10191.     }
  10192.     if (relativeURLHash) {
  10193.       builtURL += relativeURLHash;
  10194.     }
  10195.     return builtURL;
  10196.   },
  10197.  
  10198.   // build an absolute path using the provided basePath
  10199.   // adapted from https://developer.mozilla.org/en-US/docs/Web/API/document/cookie#Using_relative_URLs_in_the_path_parameter
  10200.   // this does not handle the case where relativePath is "/" or "//". These cases should be handled outside this.
  10201.   buildAbsolutePath: function buildAbsolutePath(basePath, relativePath) {
  10202.     var sRelPath = relativePath;
  10203.     var nUpLn,
  10204.         sDir = '',
  10205.         sPath = basePath.replace(/[^\/]*$/, sRelPath.replace(/(\/|^)(?:\.?\/+)+/g, '$1'));
  10206.     for (var nEnd, nStart = 0; nEnd = sPath.indexOf('/../', nStart), nEnd > -1; nStart = nEnd + nUpLn) {
  10207.       nUpLn = /^\/(?:\.\.\/)*/.exec(sPath.slice(nEnd))[0].length;
  10208.       sDir = (sDir + sPath.substring(nStart, nEnd)).replace(new RegExp('(?:\\\/+[^\\\/]*){0,' + (nUpLn - 1) / 3 + '}$'), '/');
  10209.     }
  10210.     return sDir + sPath.substr(nStart);
  10211.   }
  10212. };
  10213.  
  10214. module.exports = URLHelper;
  10215.  
  10216. },{}],42:[function(require,module,exports){
  10217. 'use strict';
  10218.  
  10219. Object.defineProperty(exports, "__esModule", {
  10220.   value: true
  10221. });
  10222.  
  10223. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /**
  10224.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       * XHR based logger
  10225.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      */
  10226.  
  10227. var _logger = require('../utils/logger');
  10228.  
  10229. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  10230.  
  10231. var XhrLoader = function () {
  10232.   function XhrLoader(config) {
  10233.     _classCallCheck(this, XhrLoader);
  10234.  
  10235.     if (config && config.xhrSetup) {
  10236.       this.xhrSetup = config.xhrSetup;
  10237.     }
  10238.   }
  10239.  
  10240.   _createClass(XhrLoader, [{
  10241.     key: 'destroy',
  10242.     value: function destroy() {
  10243.       this.abort();
  10244.       this.loader = null;
  10245.     }
  10246.   }, {
  10247.     key: 'abort',
  10248.     value: function abort() {
  10249.       var loader = this.loader,
  10250.           timeoutHandle = this.timeoutHandle;
  10251.       if (loader && loader.readyState !== 4) {
  10252.         this.stats.aborted = true;
  10253.         loader.abort();
  10254.       }
  10255.       if (timeoutHandle) {
  10256.         window.clearTimeout(timeoutHandle);
  10257.       }
  10258.     }
  10259.   }, {
  10260.     key: 'load',
  10261.     value: function load(url, responseType, onSuccess, onError, onTimeout, timeout, maxRetry, retryDelay) {
  10262.       var onProgress = arguments.length <= 8 || arguments[8] === undefined ? null : arguments[8];
  10263.       var frag = arguments.length <= 9 || arguments[9] === undefined ? null : arguments[9];
  10264.  
  10265.       this.url = url;
  10266.       if (frag && !isNaN(frag.byteRangeStartOffset) && !isNaN(frag.byteRangeEndOffset)) {
  10267.         this.byteRange = frag.byteRangeStartOffset + '-' + (frag.byteRangeEndOffset - 1);
  10268.       }
  10269.       this.responseType = responseType;
  10270.       this.onSuccess = onSuccess;
  10271.       this.onProgress = onProgress;
  10272.       this.onTimeout = onTimeout;
  10273.       this.onError = onError;
  10274.       this.stats = { trequest: performance.now(), retry: 0 };
  10275.       this.timeout = timeout;
  10276.       this.maxRetry = maxRetry;
  10277.       this.retryDelay = retryDelay;
  10278.       this.loadInternal();
  10279.     }
  10280.   }, {
  10281.     key: 'loadInternal',
  10282.     value: function loadInternal() {
  10283.       var xhr;
  10284.  
  10285.       if (typeof XDomainRequest !== 'undefined') {
  10286.         xhr = this.loader = new XDomainRequest();
  10287.       } else {
  10288.         xhr = this.loader = new XMLHttpRequest();
  10289.       }
  10290.  
  10291.       xhr.onloadend = this.loadend.bind(this);
  10292.       xhr.onprogress = this.loadprogress.bind(this);
  10293.  
  10294.       xhr.open('GET', this.url, true);
  10295.       if (this.byteRange) {
  10296.         xhr.setRequestHeader('Range', 'bytes=' + this.byteRange);
  10297.       }
  10298.       xhr.responseType = this.responseType;
  10299.       this.stats.tfirst = null;
  10300.       this.stats.loaded = 0;
  10301.       if (this.xhrSetup) {
  10302.         this.xhrSetup(xhr, this.url);
  10303.       }
  10304.       this.timeoutHandle = window.setTimeout(this.loadtimeout.bind(this), this.timeout);
  10305.       xhr.send();
  10306.     }
  10307.   }, {
  10308.     key: 'loadend',
  10309.     value: function loadend(event) {
  10310.       var xhr = event.currentTarget,
  10311.           status = xhr.status,
  10312.           stats = this.stats;
  10313.       // don't proceed if xhr has been aborted
  10314.       if (!stats.aborted) {
  10315.         // http status between 200 to 299 are all successful
  10316.         if (status >= 200 && status < 300) {
  10317.           window.clearTimeout(this.timeoutHandle);
  10318.           stats.tload = performance.now();
  10319.           this.onSuccess(event, stats);
  10320.         } else {
  10321.           // error ...
  10322.           if (stats.retry < this.maxRetry) {
  10323.             _logger.logger.warn(status + ' while loading ' + this.url + ', retrying in ' + this.retryDelay + '...');
  10324.             this.destroy();
  10325.             window.setTimeout(this.loadInternal.bind(this), this.retryDelay);
  10326.             // exponential backoff
  10327.             this.retryDelay = Math.min(2 * this.retryDelay, 64000);
  10328.             stats.retry++;
  10329.           } else {
  10330.             window.clearTimeout(this.timeoutHandle);
  10331.             _logger.logger.error(status + ' while loading ' + this.url);
  10332.             this.onError(event);
  10333.           }
  10334.         }
  10335.       }
  10336.     }
  10337.   }, {
  10338.     key: 'loadtimeout',
  10339.     value: function loadtimeout(event) {
  10340.       _logger.logger.warn('timeout while loading ' + this.url);
  10341.       this.onTimeout(event, this.stats);
  10342.     }
  10343.   }, {
  10344.     key: 'loadprogress',
  10345.     value: function loadprogress(event) {
  10346.       var stats = this.stats;
  10347.       if (stats.tfirst === null) {
  10348.         stats.tfirst = performance.now();
  10349.       }
  10350.       stats.loaded = event.loaded;
  10351.       if (event.lengthComputable) {
  10352.         stats.total = event.total;
  10353.       }
  10354.       if (this.onProgress) {
  10355.         this.onProgress(stats);
  10356.       }
  10357.     }
  10358.   }]);
  10359.  
  10360.   return XhrLoader;
  10361. }();
  10362.  
  10363. exports.default = XhrLoader;
  10364.  
  10365. },{"../utils/logger":39}]},{},[28])(28)
  10366. });
  10367. //# sourceMappingURL=hls.js.map
Add Comment
Please, Sign In to add comment